code:
from collections import defaultdict

files = ['sunday.txt', 'monday.txt', 'tuesday.txt', 'wednesday.txt',
         'thursday.txt', 'friday.txt', 'saturday.txt'
]

totals = defaultdict(float)

for fn in files:
    with open(fn) as f:
        for line in f.readlines():
            lat, long, prec = line.split()  # strings
            totals[(lat, long)] += float(prec)

# See what we have:
import pprint
pprint.pprint(totals)

rawDescription: How to create Python function that sums values from 7 daily files into one weekly file?

description: Create Python function that sums values from 7 daily files into one weekly file


rawDescription: python list items & convert language codes to names

description: Python list items & convert language codes to names


code:
from collections import Counter

def normalize_list(L, threshold):
    cntr = Counter(L)
    least_count = cntr.most_common()[-1][1]
    if least_count > threshold:
        least_count -= 1
    cntr.subtract([item for k in cntr.keys() for item in [k] * least_count])
    return list(cntr.elements())

rawDescription: Python list reduction

description: Python list reduction


rawDescription: Matplotlib can't suppress figure window

description: Matplotlib can't suppress figure window


code: [item for item in a if item % 2 != 0]

rawDescription: python for loop with "reducing" list

description: Python for loop with "reducing" list


code: sorted(output, key=lambda k: int(k) if k.isdigit() else float('-inf'))

rawDescription: Python3: sorting a list of dictionary keys


code:
df = pd.read_csv("basic.csv", usecols=["item1", "item2", "item3", "item4"])
df.apply(pd.value_counts)

rawDescription: extract basic count per values using the chunksize parameter in pandas

description: Extract basic count per values using the chunksize parameter in pandas


code:
re.search('(.*)((?!thumb))(.*)', '/tmp/somewhere/thumb').groups()
re.search('(.*?)((?!thumb))(.*)', '/tmp/somewhere/thumb').groups()
re.search('(.*?)((?!thumb))(.*?)', '/tmp/somewhere/thumb').groups()

rawDescription: negative lookahead assertion not working in python

description: Negative lookahead assertion not working in python


code:
import numpy as np
A = [1,2,3,4,5]
B = [50,40,30,20,10]
C = np.vstack((A,B)) # float so that I can use np.nan

i = np.arange(0, 6, 2)[:, None]
selections = np.logical_and(A >= i, A < i+2)[None]

D, selections = np.broadcast_arrays(C[:, None], selections)
D = D.astype(float)     # allows use of nan, and makes a copy to prevent repeated behavior
D[~selections] = np.nan # exclude these elements from mean

D = np.nanmean(D, axis=-1)

rawDescription: Averaging out sections of a multiple row array in Python


code:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(123456)
import pandas as pd

df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'],
                  columns=['x', 'y','z','w'])

plt.style.use('ggplot')
colors = plt.rcParams['axes.color_cycle']

fig, axes = plt.subplots(nrows=2, ncols=2)
for ax, col in zip(axes.flat, df.columns):
    ax.pie(df[col], labels=df.index, autopct='%.2f', colors=colors)
    ax.set(ylabel='', title=col, aspect='equal')

axes[0, 0].legend(bbox_to_anchor=(0, 0.5))

fig.savefig('your_file.png') # Or whichever format you'd like
plt.show()

rawDescription: How to make MxN piechart plots with one legend and removed y-axis titles in Matplotlib

description: Make MxN piechart plots with one legend and removed y-axis titles in Matplotlib


code:
import os
os.startfile('C:/') # opens explorer at C:\ drive

rawDescription: Make OS open directory in Python

description: Make OS open directory in Python


code:
form_backup = BackupForm(request.POST,
                         instance=Backup,
                         systemid=system.id)
form_backup = BackupForm(initial=form_backup_defaults,
                         systemid=system.id)

rawDescription: How to pass initial parameter to django's ModelForm instance?

description: Pass initial parameter to django's ModelForm instance


code:
def assign_csr_to_dense(sparse, dense):
    rows = sum((m * [k] for k, m in enumerate(np.diff(sparse.indptr))), [])
    dense[rows, sparse.indices] = sparse.data

rawDescription: Load sparse scipy matrix into existing numpy dense matrix


code:
import numpy as np
a = np.arange(10)
a
i = 2
a[i*2::2] *= (i-1.0)/i
a

rawDescription: changing values in a list while looping through it?

description: Changing values in a list while looping through it


rawDescription: If test on Pandas DataFrame

description: If test on Pandas DataFrame


rawDescription: How to create a new dictionary from old one using a given mapping?

description: Create a new dictionary from old one using a given mapping


code:
net_list = []

# ...

net_list.append(Net(userIP, userMask))
print(net_list[-1])

rawDescription: Python- Use value of pop as object name

description: Python- Use value of pop as object name


rawDescription: pandas DataFrame split the column and extend the rows

description: Pandas DataFrame split the column and extend the rows


code:
class SharedCleanupMixin:
    def clean(self):
        cleaned_data = super(SharedCleanupMixin, self).clean()
        # other validation routines
        return cleaned_data

rawDescription: Using super() from outside a class in Django (or alternative to it, if any)


rawDescription: Referencing ids within screenmanager object


code:
import csv
from datetime import datetime
date_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

rows = ['foo', 'bar', date_object]

with open('export.csv', 'wb') as csv_file:
    writer = csv.writer(csv_file, delimiter=',', quoting=csv.QUOTE_MINIMAL)
    writer.writerow(rows)

rawDescription: pyExcelerator date format

description: PyExcelerator date format


code:
with open("notes.txt") as text:
    new_text = multiple_replace(replacements, text.read())
with open("notes2.txt", "w") as result:
    result.write(new_text)

rawDescription: How can I do multiple substitutions using regex in python?

description: Do multiple substitutions using regex in python


rawDescription: python union of multiple ranges

description: Python union of multiple ranges


code:
# This SConstruct does nothing more than load the SConscript in this dir
# The Environment() is created in the SConstruct script
# This dir can be built standalone by executing scons here, or together
# by executing scons in the parent directory
env = Environment()
SConscript('SConscript', exports = ['env'])

rawDescription: Real Hierarchical Builds with SCons?

description: Real Hierarchical Builds with SCons


code:
latitude = float(rows[0])
longitude = float(rows[1])
longitude_two = longitude
latitude_two = latitude

rawDescription: How to update a counter variable when reading a file in Python?

description: Update a counter variable when reading a file in Python


code:
def save(self, **kwargs):
    Tournament(title = self.title)

rawDescription: Save() in ManyToMany relation

description: Save() in ManyToMany relation


code:
from __future__ import unicode_literals
s=['xx','yy','zz','aa']
s

rawDescription: How to achieve forward compatible string literals in python?

description: Achieve forward compatible string literals in python


code:
df = read_csv(StringIO(data),sep='\s+')
df
df.dtypes

rawDescription: Pandas groupby: How to get a union of strings


code:
d = {"foo": 12, "bar": 2, "jim": 4, "bob": 17}
[k for k, v in d.items() if v > 6] # Use d.iteritems() on python 2.x

rawDescription: How to filter dictionary keys based on its corresponding values

description: Filter dictionary keys based on its corresponding values


rawDescription: List position changing

description: List position changing


code:
import os

file_contents = []
for file in os.listdir("directory_to_search"):
    if file.endswith(".txt"):
        with open('input.txt', 'rb') as f:
            file_contents.append(" ".join(line.strip() for line in f))

rawDescription: How to find the all text files from the path and combine all the lines in that text files to one text file

description: Find the all text files from the path and combine all the lines in that text files to one text file


code:
query = (session.query(
    Record.datetime, Record.record_number,
    RecordMeasurement.power, RecordMeasurement.voltage, RecordMeasurement.temperature,
    )
    .filter(Record.record_pkid==RecordMeasurement.record_fkid)
)

rawDescription: contructing a dataframe from joined SQLAlchemy query

description: Contructing a dataframe from joined SQLAlchemy query


code:
s
n
[int(''.join(str(x) for x in s[i*n: i*n + n])) for i in range(len(s)/n)]

rawDescription: Parse simple array and save it on a file


code:
foo = Foo()
dir(foo)

rawDescription: Alter list of attributes listed by dir function


code:
columns = ['{}_E{}'.format(date, earning.replace('Earning', ''))
           for earning, date in df2.columns.tolist()]
df2.columns = columns
print(df2)
#                      2014-01_E1  2014-02_E1  2014-01_E2  2014-02_E2
# Company_code Person
# 1            Jonh           100         500         200         600
#              Peter          300         500         400         600
# 2            Jonh           300         NaN         400         NaN

rawDescription: Python summarize row into column (Pandas pivot table)


code:
import inspect

argspec = inspect.getargspec(somefunction)

rawDescription: Listing variables expected by a function in Python?


code:
for i in range(0, len(m), 2):
    two_rows = m[i:i+2]

rawDescription: Pulling data from a numpy array

description: Pulling data from a numpy array


code:
STATUS_CHOICES = (
    ('open', _('open')),
    ('closed', _('closed'))
)

class MyModel(models.Model):
    status = models.CharField(max_length=10, choices=STATUS_CHOICES)

rawDescription: Internationalize the attributes of an object


code:
def get_cars(self, request):
    page = request.GET.get('page')
    ...
    #Everything else described above.
    ...

rawDescription: django pagination understanding issue

description: Django pagination understanding issue


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.rcsetup import cycler

np.random.seed(2016)

rcParams = plt.matplotlib.rcParams
def get_prop_cycle():
    prop_cycler = rcParams['axes.prop_cycle']
    if prop_cycler is None and 'axes.color_cycle' in rcParams:
        clist = rcParams['axes.color_cycle']
        prop_cycler = cycler('color', clist)
    return prop_cycler

fig, ax = plt.subplots(nrows=2)
x,y = np.random.normal(size=(2,250))
theta = np.arctan2(y,x)
c = np.digitize(theta, np.histogram(theta)[1])

ax[0].scatter(x,y,c=c)
ax[0].set_title('using default colormap')

colors = [item['color'] for item in get_prop_cycle()]
c = np.take(colors, c, mode='wrap')

ax[1].scatter(x,y,c=c)
ax[1].set_title('using color cycle')
plt.show()

rawDescription: Using matplotlib's color cycle as a colormap


code:
item = self.tree.AppendItem(root, obj.name)
self.tree.SetItemData(item, wx.TreeItemData(obj))

rawDescription: wx.Treectrl item look up table

description: Wx.Treectrl item look up table


code:
# do what you're doing
range = [data.min(),data.max()]
bins = np.arange(range[0],range[1]+2) - 0.5
heights,edges = np.histogram(data, bins=bins, range=range)
edges = edges[:-1]+(edges[1]-edges[0]) # shift first x coordinate to edges[1]

fig, ax = plt.subplots()
ax.plot(edges,heights)

rawDescription: Numpy.histogram joining bins

description: Numpy.histogram joining bins


code:
def increment_digits(string):
    return ''.join([x if not x.isdigit() else str((int(x) + 1) % 10) for x in string])

increment_digits('SX00182')
increment_digits('SX11293')

rawDescription: Python: add 1 to each digit that is an integer


rawDescription: Return rows and columns from a 2d array using values from a 1d array in Numpy


rawDescription: replace while loop with range function

description: Replace while loop with range function


rawDescription: Remove a word with certain constraints from a string


code: np.hypot(*(xx - yy))

rawDescription: calculating distance between two numpy arrays

description: Calculating distance between two numpy arrays


code:
seq = iter([1, 2, None, 3, None, None])  #    [1, 2, None, 3, None, None]
                                         # next^
all(x is None for x in seq)
                                         #    next^
any(x is None for x in seq)
                                         #             next^
return all(x is None for x in seq)       # all returns False when 3 is encountered

rawDescription: Pythonic way to determine whether not null list entries are 'continuous'


code:
import queue
class Foo(object):
    def __init__(self, bar):
        self.bar = bar
f1 = Foo('foo')
f2 = Foo('bar')
f3 = Foo('baz')
f4 = Foo('bar')
q = queue.PriorityQueue()
q.put((5,0,f1))
q.put((3,0,f2))
q.put((3,1,f3))
q.put((1,0,f4))

rawDescription: Python equivalent of Java Comparator

description: Python equivalent of Java Comparator


rawDescription: Methods of creating a structured array

description: Methods of creating a structured array


rawDescription: Capture live network traffic from a virtual machine using python


code:
by_timeofday
by_timeofday.loc[:,"Area2"]  # this is a 'Series' not a 'DataFrame'
df = pd.DataFrame(by_timeofday.loc[:,"Area2"])  # make 'DataFrame' out of the 'Series'
df.T # transpose
df = pd.DataFrame(by_timeofday.loc[:,"Area2"]).T  # all in one
df["Date"] = "01.01.2011"
df

rawDescription: Reorganizing DataFrame and writing to SQL database


rawDescription: Reshape list of lists based on position of the element


rawDescription: Matching Regex in Python

description: Matching Regex in Python


code:
def applyfs(funcs, args):
    """
    Applies several functions to single set of arguments. This function takes
    a list of functions, applies each to given arguments, and returns the list
    of obtained results. For example:

        >>> from operator import add, sub, mul
        >>> list(applyfs([add, sub, mul], (10, 2)))
        [12, 8, 20]

    :param funcs: List of functions.
    :param args:  List or tuple of arguments to apply to each function.
    :return:      List of results, returned by each of `funcs`.
    """
    return map(lambda f: f(*args), funcs)

rawDescription: Selecting a subset of functions from a list of functions in python


code:
with open('filename.txt','rb') as f:

    ch = f.read()

rawDescription: Search Patterns replacement using lambda


code: hasattr(A,'B')

rawDescription: Why does python put 'A' in global namespace when I import A.B.C


code: diff_list = list(diff)

rawDescription: compare list elements

description: Compare list elements


code:
data = ['text', 'foo2', 'foo1', 'sample']
indeces = (i for i,val in enumerate(data) if val.startswith('foo'))

rawDescription: How to find an index of an item in a list, searching the item with a regular expression in Python?

description: Find an index of an item in a list, searching the item with a regular expression in Python


rawDescription: Two problems on writing a script to compute markov joint distribution (in python)


code:
s='%(name)s has a %(animal)s that is %%(animal_age)s years old'
s % {'name': 'Dolly', 'animal': 'bird', 'animal_age': 10}

rawDescription: Python String Substitute Dict: Skip Key and Leave Formatter


code:
used_names = set()
final_result = []
for k, g in itertools.groupby(query_result, key=lambda x: x['item']):
    final_result.append(sorted(g, key=lambda item: item['endtime'], reverse=True)[0])

rawDescription: python sort dictionary by key and list by another key

description: Python sort dictionary by key and list by another key


code:
nt = type(None)
nt.bla = 23

rawDescription: Adding method to Python's NoneType

description: Adding method to Python's NoneType


code:
(
c[0::2].apply_sync(lambda : "Hello"),
c[1::2].apply_sync(lambda : "World")
)

rawDescription: can ipython parallel operate across different sets of nodes

description: Can ipython parallel operate across different sets of nodes


rawDescription: How can I convert an RFC 822 timestamp into a human readable format in Python?

description: Convert an RFC 822 timestamp into a human readable format in Python


code:
class Alpha(object):
    def __init__(self):
        bravo = [1, 2, 3]
        charlie = 7

class Delta(object):
    def __init__(self):
        echo = [Alpha(), Alpha()]
        foxtrot = {
            "golf": "hotel"
        }

rawDescription: How to use a string to (safely) access deep Python properties?

description: Use a string to (safely) access deep Python properties


code:
xs
xs[3]
type(xs[3])

rawDescription: How do I generate PuLP variables and constrains without using exec?

description: Generate PuLP variables and constrains without using exec


code:
for inv in next_il:
   total_m2 += inv.maturity_amount or 0

rawDescription: Handling NoneType when using addition

description: Handling NoneType when using addition


code:
from itertools import groupby, cycle

output = [res for k, g in groupby(l) for orig, res in zip(g, cycle([k] + [-1] * (k - 1)))]

rawDescription: Creating a dummy index list from a list of repeating inegers


code:
module
package

rawDescription: Will python add name in packages namespace with from * import *?


code:
import subprocess

# Simple command
subprocess.call(['ls', '-1'], shell=True)

rawDescription: How to run a python script that takes command line arguments with a double click

description: Run a python script that takes command line arguments with a double click


code:
import feedparser

body = feedparser._sanitizeHTML(body, 'utf8')

rawDescription: A "safe" python HTML text formatting (ala textile)


code: unit_coords = np.random.random(size=(size, 2))

rawDescription: Pythonic way to generate random uniformly distributed points withing hollow square lamina


code:
from pylab import *
from numpy import ma

x = y = linspace(-6, 6, 100)
X, Y = meshgrid(x, y)

z3 = X*X + Y*Y  # circular pattern

# first, do this with a masked array
figure()
# z4 = 3 diagonal square
# zm = a uniform image (ones), with a mask of squares (~z4)
z4 =  np.repeat(np.repeat(eye(3, dtype=bool), 40, axis=0), 40, axis=1)
zm = ma.masked_where(~z4, ones((120,120)))
imshow(z3, cmap=cm.jet)
imshow(zm, cmap=cm.bwr, alpha=.3, vmin=0, vmax=1) #cm.bwr is an easy way to get red

# do this by changing alpha for each pixel
figure()
z5 = zeros((120, 120, 4), dtype=float)
z5[..., 0] = 1
z5[..., 3] = .4*z4.astype(float)
imshow(z3, cmap=cm.jet)
imshow(z5)

show()

rawDescription: matplotlib markers / mask on image pixels

description: Matplotlib markers / mask on image pixels


code: np.fromfunction(lambda i, j: j == m*i+c, (height, width), dtype=np.float)

rawDescription: Looping through a 2D numpy array (e.g. to create a line)


rawDescription: How to multiply sequence by non-int of type 'float'?

description: Multiply sequence by non-int of type 'float'


code:
import timeit
import locale
locale.setlocale(locale.LC_NUMERIC, "")

userplays = { "Alice"   : { "AC/DC" : 2,
                            "The Raconteurs" : 3,
                            "Mogwai" : 1
                          },
              "Bob"     : { "The XX" : 4,
                            "Lady Gaga" : 3,
                            "Mogwai" : 1,
                            "The Raconteurs" : 1
                          },
              "Charlie" : { "AC/DC" : 7,
                            "Lady Gaga" : 7
                          }
            }

def f1():
    """set from a generator expression"""
    set(b for v in userplays.values() for b in v.keys())

def f2():
    """keys from a dict comprehension"""
    {k:v for v in userplays.values() for k in v.keys()}.keys()

def f3():
    """set comprehension"""
    {b for v in userplays.values() for b in v.keys()}

def f4():
    """set from a list comprehension"""
    set([b for v in userplays.values() for b in v.keys()])

def test_table(funcs, c):
    results={k.__name__:timeit.Timer(k).timeit(c) for k in funcs}
    fastest=sorted(results,key=results.get, reverse=True)
    table=[]
    table.append([' ','rate/s']+fastest)
    for e in fastest:
        temp=[]
        temp.append(e)
        temp.append(int(round(float(c)/results[e])))
        t2=['{:.1%}'.format((results[x]-results[e])/results[e]) for x in fastest]
        table.append(temp+t2)
    print()
    for e in funcs:
        print('{}: {}'.format(e.__name__, e.__doc__))
    print()
    pprint_table(table)

def format_num(num):
    """Format a number according to given places.
    Adds commas, etc. Will truncate floats into ints!"""

    try:
        inum = int(num)
        return locale.format("%.*f", (0, inum), True)

    except (ValueError, TypeError):
        return str(num)

def get_max_width(table, index):
    """Get the maximum width of the given column index"""
    return max([len(format_num(row[index])) for row in table])

def pprint_table(table):
    col_paddings = []
    for i in range(len(table[0])):
        col_paddings.append(get_max_width(table, i))

    for row in table:
        # left col
        print(row[0].ljust(col_paddings[0] + 1),end=' ')
        # rest of the cols
        for i in range(1, len(row)):
            col = format_num(row[i]).rjust(col_paddings[i] + 2)
            print (col,end=' ')
        print()

test_table([f1,f2,f3,f4],100000)

rawDescription: Build list using only list comprehensions, no function


code:
id, TITLE, FNAME, SNAME, GENDER, ADD1, ADD2, ADD3, ADD4, PCODE, PHONE, MOBILE, DOB
Dana

rawDescription: I need some help Write random test data to csv file using faker


code:
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(800, 600)
        self.main_window = MainWindow

        # blah blah

        self.textEdit = QtGui.QTextEdit(self)
        self.pushButton = QtGui.QPushButton(self)
        self.pushButton.clicked.connect(self.test)

    def test(self):
        self.main_window.textEdit.append('button pushed')

rawDescription: PyQT: How to access MainWindow widgets from an external function?


code:
format, enc = mimetypes.guess_type(filename)
main, sub = format.split('/')
mb = MIMEBase(main, sub)

rawDescription: Using mimetypes.guess_type with email.mime.base.MIMEBase


code: return "Decimal('%s')" % str(self)

rawDescription: string quoting issues in doctests

description: String quoting issues in doctests


code: ds['new_var'] = ds['var_name'] * arr_2d

rawDescription: Speeding up reading of very large netcdf file in python


code:
# python
import h5py
import numpy
points = numpy.array([ [1., 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ])
with h5py.File('test.h5', 'w') as f:
    f['/Points'] = points

rawDescription: export matlab variable to text for python usage

description: Export matlab variable to text for python usage


code:
lines = []
with open('path/to/input/file') as infile:
    for line in infile:
        for src, target in replacements.iteritems():
            line = line.replace(src, target)
        lines.append(line)
with open('path/to/input/file', 'w') as outfile:
    for line in lines:
        outfile.write(line)

rawDescription: replacing text in a file with Python

description: Replacing text in a file with Python


rawDescription: Numpy: multiplying by a vector of ones

description: Numpy: multiplying by a vector of ones


code:
with open('scorefile.csv', 'r') as csv_file:
    for line in csv_file:
       ...

rawDescription: Sorting a csv file alphabetically on Python


code: scipy.interpolate.griddata(points, values, xi, method='linear', fill_value=nan)

rawDescription: use of matlab meshgrid

description: Use of matlab meshgrid


code:
args, kwargs = (1, 2), {"a":3, "b":4}
Process(target=f, args=args, kwargs=kwargs).start()
# Or
pool = Pool()
args, kwargs = (1, 2), {"a":3, "b":4}
pool.apply_async(f, args, kwargs)

rawDescription: Run function with positional and optional arguments in parallel in python (follow up)


code: [[1 if j <= 1 else 2]*3 for j in range(3)]

rawDescription: Python: List comprehension to assign different values


code:
insertQuery = 'INSERT INTO foo VALUES (%s, %s, %s)'

conn = psycopg2.connect(connString)
cursor = conn.cursor()

cursor.execute(insertQuery, (1, 'Alice', datetime.date(2014, 12, 4)))
cursor.execute(insertQuery, (2, 'Bob', None))

conn.commit()
conn.close()

rawDescription: Python Dates - Converting None to Null

description: Python Dates - Converting None to Null


code:
while True:
    try:
        players_chosen_hit = input('Please tell me where the hit is: 1-9  (q to quit) ')
        if players_chosen_hit == "q":
            print("Goodbye")
            break
        players_chosen_hit = int( players_chosen_hit)
        if players_chosen_hit in possibleusershipplaces:
            break
    except ValueError:
        print("Invalid entry")

rawDescription: Python - Error Checking

description: Python - Error Checking


code:
def recording(request):
  typex = Exptype.objects.all().values('id', 'exp_type')
  payer = Payer.objects.all()

  if request.is_ajax():
    var = int(request.POST.get("expvalue", ""))
    subt = serializers.serialize('json', Subtype.objects.filter(exptype=var), fields=('exp_subtype'))
    response_data = {}
    try:
        response_data['result'] = 'ok - submit'
        response_data['message'] = subt
    except:
        response_data['result'] = 'Failure'
        response_data['result'] = 'the script failed'

    return HttpResponse(json.dumps(response_data), content_type="application/json")

return render(request, 'expenses/recording.html', {
                    'payer': payer,
                    'typex': typex,
            })

rawDescription: Django - reloading element through AJAX

description: Django - reloading element through AJAX


rawDescription: How can i vectorize list using sklearn DictVectorizer

description: Vectorize list using sklearn DictVectorizer


code:
arr = np.random.uniform(size=(3,256,256))*255
arr = np.ascontiguousarray(arr.transpose(1,2,0))
img = Image.fromarray(arr, 'RGB')
img.save('out.png')

rawDescription: How to save a 3 channel numpy array as image

description: Save a 3 channel numpy array as image


code:
def test_func(expect):
    expect('a' == 'b')
    expect(1 != 1)
    a = 1
    b = 2
    expect(a == b, 'a:%s b:%s' % (a,b))

rawDescription: How to run all PyTest tests even if some of them fail?

description: Run all PyTest tests even if some of them fail


code:
class FixedValueProperty(object):
    def __init__(self, value):
        self.value = value
    def __get__(self, inst, cls):
        if inst is None:
            return self
        return self.value

rawDescription: python attribute lookup without any descriptor magic?

description: Python attribute lookup without any descriptor magic


code:
old_sort = MyList.sort
def new_sort(self, cmp=None, key=None, reverse=None):
    if cmp is None and key is None:
        key = int
    return old_sort(self, cmp, key, reverse)
MyList.sort = types.UnboundMethodType(new_sort, None, MyList)

rawDescription: How do you use redefine a method and still use the original unmodified inherited method in the method?

description: Use redefine a method and still use the original unmodified inherited method in the method


code: (0.38 * x) + 1.396 # note simplified maths and syntax

rawDescription: Learning Python, Why isn't this working?

description: Learning Python, Why isn't this working


code: df.groupby(['date', 'location']).apply(lambda sdf: sdf if len(sdf) > 1 else None)

rawDescription: Choosing particular rows from pandas dataframe


rawDescription: Any way to speed up Python and Pygame?

description: Any way to speed up Python and Pygame


code:
from itertools import permutations
def anagrams(s):
  return ("".join(p) for p in permutations(s))

rawDescription: Anagram not matching up (string to list), Python


rawDescription: Python: simplest way to get list of values from dict?


rawDescription: False Unused Import Statement in PyCharm?


code:
def createFreeSpaces(fbyte, lbyte):
    fmt = '555555 0 0 "FREE: [{}.{}]"'
    return [fmt.format(x,y) for x in range(fbyte + 1, lbyte) for y in range(8)]

rawDescription: Modifying this simple array creation function on a more Pythonic way


code:
theDict = {'cereal': ['as', '1w', '45'],
       'pop': ['gh', 'er', '65'],
       'crackle': ['yu', 'po', '22']}

for key, values in theDict.items():
    for value in values:
        if value == 'po':
            print(key)

rawDescription: Python: Iterate through Dictionary Values and outPut the Key


code:
def test(count):
    return [random.randint(1, 365) for x in range(count)]

rawDescription: Python 3.3: Birthday Probablity

description: Python 3.3: Birthday Probablity


rawDescription: Basic trigonometry isn't working correctly in python


code:
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request',
    ...
    )

rawDescription: Django 1.6: Redirect to last page after login not working


code:
import os
import tempfile

with tempfile.NamedTemporaryFile(delete=False) as f:
     f.write('\n'.join(inbuff).encode('utf-8'))

p = Popen(['/path/to/myapp', '-i', f.name], stdout=PIPE)
outbuff, conditionbuff = [], []
for line in iter(p.stdout.readline, ''):
    line = line.strip().decode('utf-8')
    if 'condition' in line:
        conditionbuff.append(line)
    else:
        outbuff.append(line)
p.stdout.close()
p.wait()
os.remove(f.name) #XXX add try/finally for proper cleanup

rawDescription: Can you open stdin as a file on MS Windows in Python?

description: Open stdin as a file on MS Windows in Python


rawDescription: Loop over time and over list elements with python -- one-dimensional lake temperature model simulation


code:
editor_cursor.execute("""
    UPDATE boxes SET x1=CAST(x1/:smallest_box_size as INTEGER),
                     y1=CAST(y1/:smallest_box_size as INTEGER),
                     z1=CAST(z1/:smallest_box_size as INTEGER),
                     x2=CAST(x2/:smallest_box_size as INTEGER),
                     y2=CAST(y2/:smallest_box_size as INTEGER),
                     z2=CAST(z2/:smallest_box_size as INTEGER)""",
    {'smallest_box_size': smallest_box_size})

rawDescription: Can I speed up a large data set operation in SQLite / Python?

description: Speed up a large data set operation in SQLite / Python


rawDescription: how to merge some columns data from different txt files in Python?

description: Merge some columns data from different txt files in Python


code:
df = DataFrame(np.arange(20).reshape(10,2),columns=['A','B'])
df['status'] = ['A']*4 + ['invalid'] * 2 + ['P'] * 4

rawDescription: Modifying a column depending on multiple conditions from another column, Pandas


rawDescription: How to sort a structured list of stock data for later access in Python?

description: Sort a structured list of stock data for later access in Python


code:
from django.db import models
t = Topo()
is_model = isinstance(t, models.model)

rawDescription: Need to find if the given variable is an instance or class


code:
import yaml

with open(filename, "r+") as data:
    scores_dict = yaml.loads(data.read())
    scores_dict[student_full_name] = correct # if already exist it will be updated otherwise it will be added
    data.seek(0)
    data.write(yaml.dump(scores_dict, default_flow_style=False))
    data.truncate()

rawDescription: How Do I Change the Data Stored in a Text File in Python?


rawDescription: Rearrange row elements using numpy in Python


code:
screen = pygame.display.set_mode((100, 100))
screen.blit(surface, (0, 0))
pygame.display.flip()

rawDescription: How can I tranform this (100, 100) numpy array into a grayscale sprite in pygame?

description: Tranform this (100, 100) numpy array into a grayscale sprite in pygame


code: Template("a small number : ${number}e6")

rawDescription: python : template var without space

description: Python : template var without space


code:
from PyQt5.QtCore import QCoreApplication
from PyQt5.QtWidgets import (QMainWindow, QApplication)

from view import Ui_MainWindow

class Main(QMainWindow, Ui_MainWindow):

    def __init__(self, parent=None):
        super(Main, self).__init__(parent)
        self.setupUi(self)

if __name__ == "__main__":
    import sys

    QCoreApplication.setApplicationName("app name")
    QCoreApplication.setApplicationVersion("app version")
    QCoreApplication.setOrganizationName("Your name")
    QCoreApplication.setOrganizationDomain("Your URL")

    app = QApplication(sys.argv)
    form = Main()
    form.show()
    sys.exit(app.exec_())

rawDescription: Can't make PyQt5 Gui work, python3

description: Can't make PyQt5 Gui work, python3


code:
def Strtime2Num(result):
    date_object = datetime.strptime(Strtime,"%Y-%m-%dT%H:%M%S+0800")
    Strtime = date_object.strftime('%Y%m%d%H%M')
    return int(result)

rawDescription: How to write date and time from string to Sqlite table?

description: Write date and time from string to Sqlite table


code:
A = [1,2,3]
B = [3,1,2]
all(i in B for i in A)
B = [3,1,4]
all(i in B for i in A)

rawDescription: Comparing 2 lists out of order

description: Comparing 2 lists out of order


code:
import scipy
x = scipy.matrix([1,2,3]).transpose()
x
y = x.T.tolist()[0]
y

rawDescription: Creating a list from a Scipy matrix

description: Creating a list from a Scipy matrix


rawDescription: Combining elements of a list in python to a single element


code:
i = headers.split().index('Rx')
# now use line[i]

rawDescription: remove rows which have a specific attribute less than or equal to 0

description: Remove rows which have a specific attribute less than or equal to 0


rawDescription: How to "else" in a list comprehension when the condition is non-boolean?


code: unq_cnt = np.bincount(unq_inv)

rawDescription: How to get lists of indices to unique values efficiently?

description: Get lists of indices to unique values efficiently


code:
class Foo(object):
    def __eq__(self, other):
        if isinstance(other, Wildcard):
            return NotImplemented
        else:
            return False

f = Foo()

f == 1
f == Foo()
f == w

rawDescription: How can I make a Python object always return true for an equality test?

description: Make a Python object always return true for an equality test


code:
{'address': u'Level 4. 36 Carrington St Sydney. NSW 2000', 'name': u'A D Hill & Co', 'number': u'0292991733'}
{'address': u'Suite 103, Level 1. 84 Pitt Street Sydney. NSW 2000', 'name': u'A2Z Insolvency Solutions', 'number': u'02 8065 6607'}
{'address': u'810 George St Sydney. NSW 2000', 'name': u'AAA iPro Services Australia', 'number': u'1300554959'}
{'address': u'Level 39. 2 Park St Sydney. NSW 2000', 'name': u'AccFin Services', 'number': u'0290047825'}
...

rawDescription: Webscraping a messy webpage with python and beautiful soup


rawDescription: Easiest way to store a single timestamp in appengine


rawDescription: How do I alternate between different marker colors on matplotlib?

description: Alternate between different marker colors on matplotlib


code: result = pd.merge(samples, df, how='inner')

rawDescription: Select pandas frame rows based on two columns' values


code:
xs = range(100, 200)
ys = range(150, 250)
xs = map(lambda n: tuple(range(n, n + 10)), xs)
ys = map(lambda n: tuple(range(n, n + 10)), ys)
def profile_pairing():
    list(izip_pairs(xs, ys, lambda x, y: cmp(x[:4], y[:4])))
def profile_keying():
    list(izip_keys(xs, ys, lambda v: v[:4]))
from timeit import Timer
Timer(profile_pairing).timeit(1000)
Timer(profile_keying).timeit(1000)
xs = map(lambda n: tuple(range(n, n + 10)), range(1000, 2000))
ys = map(lambda n: tuple(range(n, n + 10)), range(1500, 2500))
Timer(profile_pairing).timeit(100)
Timer(profile_keying).timeit(100)
xs = map(lambda n: tuple(range(n, n + 10)), range(10000, 20000))
ys = map(lambda n: tuple(range(n, n + 10)), range(15000, 25000))
Timer(profile_pairing).timeit(10)
Timer(profile_keying).timeit(10)
xs = map(lambda n: tuple(range(n, n + 10)), range(100000, 200000))
ys = map(lambda n: tuple(range(n, n + 10)), range(150000, 250000))
Timer(profile_pairing).timeit(1)
Timer(profile_keying).timeit(1)

rawDescription: Python: Fast and minimalistic way to zip and pair matching elements in two lists


code:
def run() :
    while True :
        task = q.get()
        if task == 'stop':
            break
        # simulate processing time *before* actual reporting
        time.sleep(2)
        print('Just finished task number',task)
        q.task_done()

rawDescription: The correct implementation of queue.Queue when multithreading in Python


code:
import matplotlib.pyplot as plt

def main():
    # Make an example pie plot
    fig = plt.figure()
    ax = fig.add_subplot(111)

    labels = ['Beans', 'Squash', 'Corn']
    wedges, plt_labels = ax.pie([20, 40, 60], labels=labels)
    ax.axis('equal')

    make_picker(fig, wedges)
    plt.show()

def make_picker(fig, wedges):
    import webbrowser
    def on_pick(event):
        wedge = event.artist
        label = wedge.get_label()
        webbrowser.open('http://images.google.com/images?q={0}'.format(label))

    # Make wedges selectable
    for wedge in wedges:
        wedge.set_picker(True)

    fig.canvas.mpl_connect('pick_event', on_pick)

if __name__ == '__main__':
    main()

rawDescription: how to create hyperlink in piechart

description: Create hyperlink in piechart


code:
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect

def affiche(request):
    form = AfficheForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            Select = form.cleaned_data['Select']
            if Select == '1':
                url = reverse('affiche_all', args=(),
                    kwargs={'devise': 'EURO'})
                return HttpResponseRedirect(url)

rawDescription: python redirect to another view

description: Python redirect to another view


code:
import re
data = 'John - Smith : 0123\nchildren: \n  Sam\n  Kim'
match = re.match(r'(\w+) - (\w+) : (\d+).*?children:(.*)', data, re.S)
match.groups()

rawDescription: reverse template with python

description: Reverse template with python


code: entry_user_profile = form.save()

rawDescription: how to fill out the form initial data?

description: Fill out the form initial data


rawDescription: Get business days between start and end date using pandas


rawDescription: Efficiently combining values of two lists in Python


rawDescription: numpy iterating over multidimensional array

description: Numpy iterating over multidimensional array


code:
dico = {'key1': [],
        'key2': [],
        'key3': ['value1', 'value1'],
        'key4': ['value2', 'value2'],
        'key5': ['value3'],
        'key6': ['value1', 'value2', 'value3']}
new_dict = {}
for key, values in dico.items():
    for value in values:
        new_dict.setdefault(value, set()).add(key)

new_dict
{key: list(values) for key, values in new_dict.items()}

rawDescription: Get a string list from a word

description: Get a string list from a word


code: n = minn if n < minn else maxn if n > maxn else n

rawDescription: How to limit a number to be within a specified range? (Python)

description: Limit a number to be within a specified range? (Python)


code:
import re
with open('numbers') as fhandle:
    for line in fhandle:
        line = line.strip()
        separators = re.sub(r'\d', '', line, flags=re.U)
        for sep in separators[:-1]:
            line = line.replace(sep, '')
        if separators:
            line = line.replace(separators[-1], '.')
        print(line)

rawDescription: Python: Detect number separator symbols and parse into a float without locale


code:
import sys
import importlib

module_name = sys.argv[1]
class_name = sys.argv[2]

module = importlib.import_module(module_name)
cls = getattr(module, class_name)

obj = cls()
obj.writeByte(0x0)

rawDescription: In Python 3.2 how would I dynamically open and compile a class from a specified file?


rawDescription: How to build a dictionary with a key and value being a list of list containing a list and matched to a value within a list

description: Build a dictionary with a key and value being a list of list containing a list and matched to a value within a list


code: a.intersection(b) == b

rawDescription: Check if none of the multiple chars appears in string A?


code: repl_string = "(?s)Fruit=[^\n]*\nId=" + user_inputted_id_to_match + ".*?(?=Fruit)"

rawDescription: Delete lines from text file using regex sub


code: result = zip(*oRS.GetRows(1))

rawDescription: How do I change ADO ResultSet format in python?

description: Change ADO ResultSet format in python


code:
a = range(5)
list(itertools.chain(*[[x, x] if x % 2 == 1 else [x] for x in a]))
# => [0, 1, 1, 2, 3, 3, 4]

rawDescription: List of integers with recurring odd numbers


code: df["size"] = df.groupby(['A', 'B']).transform(len)

rawDescription: How to find subgroups statistics in pandas?

description: Find subgroups statistics in pandas


code:
import os.path
my_new_string = "C:\\Users\\User\\code\\Python\\final\\mega_1237665428090192022_cts.ascii"
os.path.basename(my_new_string)
basename = os.path.basename(my_new_string)
basename.split('_')[0]
import re
re.match(r'[A-Za-z]+', basename).group()

rawDescription: Python Regular Expression searching backwards


code:
def getFileName(self):
    return filename

rawDescription: How to print a return value from a function inside a class

description: Print a return value from a function inside a class


code:
import pprint
import random

categories = [0,1,3] #complete pool of numbers
restrictedNumbers = [0, 1] #numbers to only appear once
unrestrictedNumbers = [num for num in categories if num not in restrictedNumbers] #can appear any number of times

matrix = [[0, 0, 0, 0, 0] for l in range(10)] #10 rows, 5 columns matrix of zeros
def returnShuffled(startList):
    random.shuffle(startList)
    return startList

newMatrix = [returnShuffled(restrictedNumbers + [random.choice(unrestrictedNumbers) for _ in range(len(row) - len(restrictedNumbers))]) for row in matrix]
pprint.pprint(newMatrix)

rawDescription: randomly fill 2d matrix with conditions

description: Randomly fill 2d matrix with conditions


code:
mp.rcParams['axes.linewidth'] = .5
mp.rcParams['lines.linewidth'] = .5
mp.rcParams['patch.linewidth'] = .5

rawDescription: matplotlib linewidth when saving a PDF

description: Matplotlib linewidth when saving a PDF


code:
import os

with os.popen('ls') as pipe:
    for line in pipe:
        print (line.strip())

rawDescription: Python: Nice way to iterate over shell command result


code: rdd = sc.textFile("file:///path/*.txt")

rawDescription: pyspark - multiple input files into one RDD and one output file

description: Pyspark - multiple input files into one RDD and one output file


rawDescription: Python/JSON: Merge default and user configuration


code: df.map_partitions(func, columns=...)

rawDescription: python dask DataFrame, support for (trivially parallelizable) row apply?

description: Python dask DataFrame, support for (trivially parallelizable) row apply


code:
M,N,R = A.shape
Final_Product = A.reshape(-1,R).dot(Combinations.T).T.reshape(-1,M,N)

rawDescription: Vectorize large NumPy multiplication

description: Vectorize large NumPy multiplication


code:
import fileinput

for line in fileinput.input('test.txt', inplace=True):
    if line.startswith('unlock_time'):
        print('# {}'.format(line))
    else:
        print(line)

rawDescription: Single line commands from Python

description: Single line commands from Python


code: lambda x, i=i: x+i

rawDescription: Have Python 2.7 functions remember value and not reference? Closure Weirdness


code:
def missingArgs(func, argdict):
    return set(getRequiredArgs(func)).difference(argdict)

rawDescription: Can you list the keyword arguments a Python function receives?

description: List the keyword arguments a Python function receives


code: obj = falcondup.falconpeer.FalconPeer()

rawDescription: How to import and create my class from my module?

description: Import and create my class from my module


code:
import csv
with open(r'C:\Users\Gord\Desktop\broken.csv', 'rb') as csv_in:
    inpTweets = csv.reader(csv_in, skipinitialspace=True)
    header_row = True
    for row in inpTweets:
        if header_row:
            header_row = False
        else:
            print(row)

rawDescription: A single CSV column includes commas - Python


code:
with open('test.txt', 'w') as fp:
    data = json.load(response)
    json.dump(data, fp)

rawDescription: Trying update Twitter status with scraper data using Twython. Unsure on what to do


code:
class A:pass
A.__name__
A().__class__.__name__       #using an instance of that class

rawDescription: getting object name and function name

description: Getting object name and function name


code: print(list(data['clubs']))

rawDescription: Inserting dict objects from a list with key-value pairs to a new list


code:
from bs4 import BeautifulSoup
import requests
url = "http://www.bbc.com/news/world/asia/"
r = requests.get(url)
soup = BeautifulSoup(r.content)
india_links = lambda tag: getattr(tag, 'name', None) == 'a' and 'href' in tag.attrs and 'india' in tag.get_text().lower()
results = soup.find_all(india_links)
from pprint import pprint
pprint(results)

rawDescription: How to extract html links with a matching word from a website using python

description: Extract html links with a matching word from a website using python


code:
common = []
for k in Dict:
    if len(set(inp).intersection(Dict[k].values())) == len(inp):
        common.append(k)

rawDescription: dictionary of dictionaries, get keys in common for values

description: Dictionary of dictionaries, get keys in common for values


rawDescription: What does '[0]' mean in Python?

description: What does '[0]' mean in Python


code:
import jellyfish
jellyfish.levenshtein_distance('jellyfish', 'smellyfish')
jellyfish.jaro_distance('jellyfish', 'smellyfish')
jellyfish.damerau_levenshtein_distance('jellyfish', 'jellyfihs')

rawDescription: Letter combinations between a string in a list


rawDescription: adding values to default dict list of values

description: Adding values to default dict list of values


code: processmenu.add_cascade(...,  command = main())

rawDescription: Tkinter automatically opens my file

description: Tkinter automatically opens my file


code:
{
    "_id" : ObjectId("5055a7abac2ec70755816f7b"),
    "produit_up" : [
        {
            "abus" : 0,
            "avctype" : "image/jpeg",
            "date" : "2012-09-15",
            "description" : "ddsfdsf sdfsdfsdf",
            "id" : "alucaard134773657029",
            "namep" : "nokia 3310",
            "nombre" : 2,
            "orientation" : "portrait",
            "photo" : ObjectId("5054d3fa3a5f3a0598b792a2"),
            "prix" : 24,
            "tags" : [
                "ddsfdsf",
                "sdfsdfsdf"
            ],
            "vend" : false
        }
    ]
}

rawDescription: how to get only one subdocument using $in

description: Get only one subdocument using $in


code:
import pandas as pd

def with_pandas_groupby(func, x, b):
    grouped = pd.Series(x).groupby(b)
    return grouped.agg(func)

rawDescription: Applying a function by bins on a vector in Numpy


rawDescription: How to Show Build Results in OSX Terminal from Sublime Text 2


code:
#!/usr/bin/env python

class Custom(object):
    def __init__(self):
        self.data = {"a":1, "b":2, "c":3, "special":0}
        self.current = 0

    def __iter__(self):
        return self

    def next(self):
        key = [k for k, v in self.data.iteritems() if v == self.current]
        if not key:
            raise StopIteration
        self.current += 1
        return key[0]

if __name__ == '__main__':
    obj = Custom()
    for i in obj:
        print(i)

rawDescription: Special use for __iter__ and __next__

description: Special use for __iter__ and __next__


code: profiles = [r.profile for r in thingie.relation_set.all()]

rawDescription: How Do I Select all Objects via a Relationship Model


code:
@mock.patch('module_under_test.do_remotely_after_one_minute')
@mock.patch('module_under_test.do_remotely_after_two_minutes')
def test_fun(mock_dratm, mock_draom):
    module_under_test.fun(a, b)

rawDescription: How to provide additional argument in a public function for testing purposes?

description: Provide additional argument in a public function for testing purposes


code:
import datetime
import jday
import jday2

# The date we are interested in
a = dict(year=2015, month=12, day=1, hour=22, minute=8, second=0)
dt = datetime.datetime(**a)  # 2015-12-01 22:08:00

# The original signature of the function
jdate1 = jday.JD(a['year'], a["month"], a["day"], a["hour"], a["minute"], a["second"])
# 2457358.422222222

# The new signature that accepts a normal date object
# Note that we use keyword "date" argument
jdate2 = jday.JD(date=dt)
# 2457358.422222222

# The new signature that accepts a normal date object
jdate3 = jday2.JD(dt)
# 2457358.422222222

rawDescription: Formatting python datetime object as argument


code:
import script1
for porsche in script1.porsche_container:
    ...

rawDescription: Create and retrieve object list in Python


code:
c = np.where(boolvec[:, None], a, b)
c

rawDescription: Selecting columns in numpy based on a Boolean vector


code: sol = fsolve(lambda x: myfunc(x) - 3, x0)

rawDescription: Python find root for non-zero level

description: Python find root for non-zero level


code:
with open("Input.txt") as in_file:
    matrix = [[int(num) for num in line.split()] for line in in_file]

matrix

rawDescription: ColSum of matrix from file python

description: ColSum of matrix from file python


code:
application = webapp2.WSGIApplication([
    ('/SampleClass', SampleClass),
    ('/UserLogout', UserLogout),
    (decorator.callback_path, decorator.callback_handler())
], debug=True)

rawDescription: google app engine python

description: Google app engine python


code:
import hashlib

teststr = "foo"
filename = "file.txt"

def md5_for_file(f, block_size=2**20):
    md5 = hashlib.md5()
    while True:
        data = f.read(block_size)
        if not data:
            break
        md5.update(data.encode('utf8'))
    return md5.digest()

md5 = hashlib.md5()
md5.update((teststr + "\n").encode('utf8'))
digest = md5.digest()
f = open(filename, 'r')
print(md5_for_file(f) == digest)

rawDescription: How in Python check if two files ( String and file ) have same content?


code:
remove_user.user = None
self.session.commit()

rawDescription: Removing/Adding an Object from a Collection in SQLAlchemy


code:
from operator import itemgetter
min((e for e in mylist if e[1]), key = itemgetter(1))[0]

rawDescription: Python index min value list of list

description: Python index min value list of list


code:
def lang():
            windll = ctypes.windll.kernel32
            language = str(windll.GetUserDefaultUILanguage())
            return language

def port():
        Ardport = "not found"
        c = wmi.WMI()
        wql = "Select * From Win32_USBControllerDevice"
        for item in c.query(wql):
            s = str(item.Dependent.Caption)
            strfind = "Raptor"
            if (s.find(strfind) >= 0):
                Ardport = str(item.Dependent.Caption)
        return Ardport

rawDescription: def function returning wrong value (python 2.7)

description: Def function returning wrong value (python 2.7)


code:
import csv

with open('csvfile.csv') as infile, open('outputfile.txt', 'w') as outfile:
    out_csv = csv.writer(outfile)
    out_csv.writerow(["'{}'".format(row['location']) for row in csv.DictReader(infile)])

rawDescription: Handling last line in Python CSV file reading


code:
class Delegate:
    def __init__(self, cls):
        self._delegate_cls = cls
    def __getattr__(self, name):
        x = getattr(self._delegate_cls, name)
        if hasattr(x, "__get__"):
            return x.__get__(self)
        return x

rawDescription: python: super()-like proxy object that starts the MRO search at a specified class

description: Python: super()-like proxy object that starts the MRO search at a specified class


code: print("Getting anagrams and saving them...", progress, "/", total, " or: ", progress * 100 // total, "% done.", sep="", end="\r")

rawDescription: Displaying a floor division

description: Displaying a floor division


code:
with open('Supercars', 'wb') as f:
   pickle.dump(records, f)

rawDescription: Iterating over particular attributes of instances of objects in python


code:
a=5
b=eval('x+5') #won't work -- x isn't defined

rawDescription: Python: have a user-defined function as an input while keeping the source-code inaccessible?


code: newButton = Button(newtop, command=lambda top=newtop: top.destroy())

rawDescription: Destroying a dynamically created widget

description: Destroying a dynamically created widget


code:
varBind = varBinds[0]
oid, value = varBind
str(value)

rawDescription: Parsing or Splitting pysnmp output to update into database


code:
def getActors(item_url):
    response = requests.get(item_url)
    soup = BeautifulSoup(response.content, "lxml")  # or BeautifulSoup(response.content, "html5lib")
    tempActors = []
    try:
        return(soup.find(text="Actors:").find_parent("tr").find_all(text=True)[1:])
    except AttributeError:
        return ['n/a']

rawDescription: Removing string unicode marks from list and having each item on separate line


code:
class Location(model.Models):
    ...

class Assessment(model.Models):
    location = models.ForeignKey(Location)
    ...

class Category(model.Models):
    assessment = models.ForeignKey(Assessment)
    ...

rawDescription: How to get id from url to use in relationship database?

description: Get id from url to use in relationship database


code:
import lxml.html as LH
import itertools

def find_nearest(elt):
    preceding = elt.xpath('preceding::*/@href')[::-1]
    following = elt.xpath('following::*/@href')
    parent = elt.xpath('parent::*/@href')
    for href in roundrobin(parent, preceding, following):
        return href

def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # http://docs.python.org/library/itertools.html#recipes
    # Author: George Sakkis
    pending = len(iterables)
    nexts = itertools.cycle(iter(it).next for it in iterables)
    while pending:
        try:
            for n in nexts:
                yield n()
        except StopIteration:
            pending -= 1
            nexts = itertools.cycle(itertools.islice(nexts, pending))

tekst = '''

      Claus Hjort spiller med mrkede kort

Af: Dennis Kristensen

Claus Hjort Frederiksens argumenter for at afvise
      trepartsforhandlinger har ikke hold i virkeligheden. Hans rinde er nok
      snarere at forberede det ideologiske grundlag for en Løkke Rasmussens
      genkomst som statsministe

      Ls mere
      |
      Kommentarer (4)

'''

to_find = "Rasmussen"
doc = LH.fromstring(tekst)

for x in doc.xpath('//*[contains(text(),{s!r})]'.format(s = to_find)):
    print(find_nearest(x))

rawDescription: Find nearest link with BeautifullSoup (python)


code:
from datetime import date, timedelta
list(daterange(date(2000, 1, 1), date(2000, 2, 1), timedelta(days=7)))

rawDescription: How to match a list of dates to a pattern?

description: Match a list of dates to a pattern


code:
def my_property(name, postprocess=postprocess):
    return MyDescriptor(name, postprocess)

class Example(object):
    prop1 = my_property('prop1')
    prop2 = my_property('prop2')

rawDescription: Implementing Python persistent properties


code:
with open('file.txt', 'r') as f: #open the file
    contents = function(f) #put the lines to a variable.

rawDescription: How to Open a file through python

description: Open a file through python


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

class Locale(object):
    def __init__(self, locale):
        LC_ALL_MASK = 8127
        # LC_COLLATE_MASK = 8
        self.libc = ctypes.CDLL("libc.so.6")
        self.ctx = self.libc.newlocale(LC_ALL_MASK, locale, 0)

    def strxfrm(self, src, iteration=1):
        size = 3 * iteration * len(src)
        dest =  ctypes.create_string_buffer('\000' * size)
        n = self.libc.strxfrm_l(dest, src, size,  self.ctx)
        if n < size:
            return dest.value
        elif iteration<=4:
            return self.strxfrm(src, iteration+1)
        else:
            raise Exception('max number of iterations trying to increase dest reached')

    def __del__(self):
        self.libc.freelocale(self.ctx)

rawDescription: Sorting list of string with specific locale in python


code: template = '{:<25} {:<14} {:<6}' # numbers are width, '<' means 'align to left'

rawDescription: Python tabulate, appending element to current table


code:
a = """ {"price" : '10.25'} """
import ast
new_dict = ast.literal_eval(a.strip())
import json
json.dumps(new_dict)

rawDescription: Python's simplejson does not parse a simple json string


code:
def f(y):
    return y + 4

rawDescription: Function parameter semantics (with nested functions)


code:
from __future__ import print_function

num = int(input("Number of lines: "))  # Use raw_input() on Python 2

for count in range(num, 0, -1):
    print('x' * count)
    print()

rawDescription: How to output N lines with N, N-1, .., 1 characters per line

description: Output N lines with N, N-1, .., 1 characters per line


rawDescription: Python: Convert hex string to int and back


code:
a = np.arange(1000).reshape(500, 2)
mask = np.ones(a.shape[0], dtype=bool)
mask[498] = False
out = np.apply_along_axis(test, 1, a[mask])

rawDescription: Python/Numpy - Masked Arrays are Very Slow


rawDescription: Apply function to Dataframe GroupBy Object and return dataframe


rawDescription: I want to return the 'a' of the URL instead of the whole URL


code:
def myfunction():
    todo = itertools.cycle([do1, do2, do3])
    start = time.time()
    while time.time() < start + 5:
        todo.next()()

rawDescription: How to make a function return after 5 seconds passed in Python?

description: Make a function return after 5 seconds passed in Python


code:
import collections
Record = collections.namedtuple('Record', ['person', 'location', 'time', 'amount'])
allrecords = []

rawDescription: Good libraries in R or Python for analytics of network/graph data


code:
page_sizes = dict((n, x) for x, n in vars(QtGui.QPrinter).items() if
                  isinstance(n, QtGui.QPrinter.PageSize))
page_sizes[QtGui.QPrinter.A4]
'A4'

rawDescription: pyqt convert enum value to key

description: Pyqt convert enum value to key


code: result = [x.split(":::",1)[1] for x in s.split('.') if x]

rawDescription: Splitting in python

description: Splitting in python


code:
import os
import foo.bar

print(os.path.abspath(foo.bar.__file__))

rawDescription: How to find the location of a python package installed via egg-link?

description: Find the location of a python package installed via egg-link


code: #!/usr/bin/env python

rawDescription: Making Python script accessible system wide


code:
def by_30m(d):
    dt = datetime.datetime.strptime(d["Date[G]"]+"-"+d["Time[G]"], "%d-%b-%Y-%H:%M:%S.%f")
    return (dt.year, dt.month, dt.day, dt.hour, dt.minute // 30)

rawDescription: Grouping value by time frames

description: Grouping value by time frames


code:
if raw_input.lower().strip() in command: # Check to see if input is defined in the dictionary.
   os.chdir(command[raw_input][0]) # Gets Tuple item 0 (e.g. C:\Program Files.....)
   os.startfile(command[myIraw_inputput][1]) # Gets Tuple item 1 (e.g. Skype.exe)

rawDescription: Organizing a large python script

description: Organizing a large python script


code:
from itertools import product
list(product((0, 1), repeat=4))

rawDescription: Generating all possibly length n combinations of two items in python


code:
import json
class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, complex):
            return [obj.real, obj.imag]
        return json.JSONEncoder.default(self, obj)
dumps(2 + 1j, cls=ComplexEncoder)
ComplexEncoder().encode(2 + 1j)
list(ComplexEncoder().iterencode(2 + 1j))

rawDescription: Serializing a user-defined class in Python


code: tup1 == tup2 == tup3 == tup4

rawDescription: creating namedtuple instances with kwargs

description: Creating namedtuple instances with kwargs


code:
with open ("words.txt", "r") as myfile:
    data = myfile.read().replace('\n', '')
    print(data)
    freq = 0
    for char in data:
        if char == Symbol:
            freq = freq + 1
    print(freq)

rawDescription: Counting specific letters or symbols in a text file in Python


code:
def MetaClass(name, bases, attrs):
    cls = type(name, bases, attrs)
    set_pyqtproperties(cls, attrs.get('properties', ''))
    return cls

class LightDMUser(QObject):
    properties = "display background"
    __metaclass__ = MetaClass

rawDescription: Can anyone help condense this Python code?


code:
import subprocess

CMD = ['fping', 'param1', 'param2']

result = subprocess.check_output(CMD)

rawDescription: Using fping to get ping times in Python

description: Using fping to get ping times in Python


rawDescription: Different starting indices for slices in NumPy


rawDescription: How to extract the text between two spans with lxml (or BeautifulSoup)?

description: Extract the text between two spans with lxml (or BeautifulSoup)


code:
room = "|                     |"
chest = "[Chest]"
door = "Door"
def insert_object(new_object: str, position: int) -> str:
    room_start = room[0:position]  # Gets the part of the room before the 'object'
    end_position = position + len(new_object)  # Gets the position after the object 'ends'
    room_end = room[end_position:]  # Gets the part of the room after the object 'ends'
    new_room = room_start + new_object + room_end  # Pieces these parts together, with the object in the middle
    return new_room  # Returns the result

x = insert_object(chest, 3)
print(x)

rawDescription: How do I format code to print with the same width every time?

description: Format code to print with the same width every time


rawDescription: get cluster labels in mllib kmeans pyspark

description: Get cluster labels in mllib kmeans pyspark


code:
import functools

def italic(f):
    return functools.update_wrapper(lambda: "<italic/>" + f() + "</italic>", f)

rawDescription: A better way to write python closures?

description: A better way to write python closures


rawDescription: Stretching a panel to fill the whole window as opposed to just a corner


code:
def get_db_prep_value(self, value, *args, **kwargs):
    if value is not None:
        return datetime.datetime.strptime(value[0:4] + "-" + value[4:6] + "-" + value[6:], "%Y-%m%d")

def get_prep_lookup(self, lookup_type, value):
    return self.get_db_prep_value(value)

rawDescription: Django model query truncate column's value


code:
def getKeyCode(self):
    select.select([sys.stdin], [], [])

    with self._curses_lock:

        c = self._curses_screen.getch()
        if c == 27:
            next_c = self._curses_screen.getch()

    return c

rawDescription: Preventing race condition with ncurses+python


code:
from AppKit import NSWorkspace
def is_alias (path):
    uti, err = NSWorkspace.sharedWorkspace().typeOfFile_error_(
        os.path.realpath(path), None)
    if err:
        raise Exception(unicode(err))
    else:
        return "com.apple.alias-file" == uti

rawDescription: Python: Check if a directory is an alias


rawDescription: Differentiate between single and double click in python


rawDescription: what does [[...]] mean in python?

description: What does [[...]] mean in python


code:
from __future__ import print_function
import time
import gmpy2

def sieve(limit=1000000):
    '''Returns a generator that yields the prime numbers up to limit.'''

    # Increment by 1 to account for the fact that slices do not include
    # the last index value but we do want to include the last value for
    # calculating a list of primes.
    sieve_limit = gmpy2.isqrt(limit) + 1
    limit += 1

    # Mark bit positions 0 and 1 as not prime.
    bitmap = gmpy2.xmpz(3)

    # Process 2 separately. This allows us to use p+p for the step size
    # when sieving the remaining primes.
    bitmap[4 : limit : 2] = -1

    # Sieve the remaining primes.
    for p in bitmap.iter_clear(3, sieve_limit):
        bitmap[p*p : limit : p+p] = -1

    return bitmap.iter_clear(2, limit)

if __name__ == "__main__":
    start = time.time()
    result = list(sieve(1000000000))
    print(time.time() - start)
    print(len(result))

rawDescription: Speed up bitstring/bit operations in Python?


code:
def save_file(filename, new_list):
    with open(filename, 'w') as f:
        f.write(''.join(new_list))

rawDescription: Python, adding a file into another file

description: Python, adding a file into another file


code:
def relu(x):
    return theano.tensor.switch(x<0, 0, x)
HiddenLayer(..., activation=relu)

rawDescription: Theano HiddenLayer Activation Function

description: Theano HiddenLayer Activation Function


code:
def getPermutations(string):
    if len(string) == 1:
        yield string
    else:
        for i in xrange(len(string)):
            for perm in getPermutations(string[:i] + string[i+1:]):
                yield string[i] + perm

rawDescription: Python: using a recursive algorithm as a generator


rawDescription: object inside another object in python

description: Object inside another object in python


code:
def drawing_group(g, name='a'):
    layout = g.layout("fr")
    visual_style = {}
    for e in g.es:
        if e['company'] is True:
            e['color'] = 'blue'
        elif e['res'] is True:
            e['color'] = 'red'
        elif e['std'] is True:
            e['color'] = 'green'
    visual_style["vertex_size"] = 1
    visual_style["layout"] = layout
    visual_style["bbox"] = (500, 500)
    visual_style["margin"] = 20
    visual_style['hovermode'] = 'closest'
    igraph.plot(g, 'output/gr_%s.png' % (str(num) + name), **visual_style)

rawDescription: How to assign different colors to different edges using igraph in Python?

description: Assign different colors to different edges using igraph in Python


code:
__import__('aaa')
__import__('os')

rawDescription: Is there a better way to determine something is a module in python


code:
# Small random input list
# Print nested lists shapes
np.concatenate(projected,0)
np.concatenate(projected,0).shape

rawDescription: Losing dimensions of a numpy array

description: Losing dimensions of a numpy array


rawDescription: Finding unique solution puzzle python

description: Finding unique solution puzzle python


rawDescription: python: how to convert a dependency dictionary into a dependency tree dictionary to be later converted into json

description: Python: how to convert a dependency dictionary into a dependency tree dictionary to be later converted into json


code: bin_pow(a, n, sqr=A.sqr)

rawDescription: Referencing a class' method, not an instance's


code:
from itertools import izip_longest

...

d = defaultdict(list)
for maker, model, year in izip_longest(maker, model, year):
    d[maker].append((model, year))

rawDescription: Merge three list to Dictionary but everything is out of place/not printed


code:
np.any(np.all(x == e, axis=-1))
np.any(np.all(y == e, axis=-1))

rawDescription: what does it mean to be `in` numpy array

description: What does it mean to be `in` numpy array


code:
def main():
    result = ""
    cards = ["2D","3C","5H","5D","JS"]
    previous = cards[0]
    current = cards[1]

    i = 1
    while i < len(cards) and result == "":

        previous = cards[i-1]
        current = cards[i]

        if current[0] == previous[0]:
            result = previous + current

        i = i + 1

    print(result)

main()

rawDescription: Trying to make this work with two characters and not just one


code:
x
[" ".join(item) for item in x.astype('S4')]
[" ".join(item) for item in x.astype('S14')]

rawDescription: convert multidimensional numpy array to list of string

description: Convert multidimensional numpy array to list of string


code:
import numpy as np
import pandas as pd

a = np.random.rand(50)
b = np.random.randint(10, 15, 50)

s = pd.Series(a)
s.groupby(b).apply(pd.Series.reset_index, drop=True).unstack(level=0)

rawDescription: Array reshaped according to keys

description: Array reshaped according to keys


code:
f = Foo()
f.x = D()
f.x

rawDescription: Why descriptors (in Python) cannot be inserted (placed) in ALREADY initialized object?


code:
metadata_json = json.dumps(metadata)
myfile.write('%d\n' % len(metadata_json))
myfile.write(metadata_json)
myfile.write(data)

rawDescription: optimal method to parse a json object in a datafile

description: Optimal method to parse a json object in a datafile


code:
from string import ascii_lowercase, ascii_uppercase
ascii_lowercase
ascii_uppercase

rawDescription: python random.sample("abc",3) . how to use regular expressions in place of "abc"

description: Python random.sample("abc",3) . how to use regular expressions in place of "abc"


code:
dis.dis(f)
dis.dis(g)

rawDescription: does return(value) stop a python script

description: Does return(value) stop a python script


code:
inject = "'; SELECT name,cardnum FROM credit_cards; --"
most_popular(inject, 'LOL')

rawDescription: A weird space issue Python

description: A weird space issue Python


code:
from itertools import izip
mylist = ['apple','banana','pear','orange']
values = [3,1,2,4]
[i[1] for i in sorted(izip(values, mylist))]

rawDescription: How to order list according to array values in python?

description: Order list according to array values in python


code:
a = np.arange(25).reshape(5,5)
a

rawDescription: Sort rows and columns of a matrix by another list with numpy


code:
df
df = df.fillna(pd.rolling_mean(df, 7, min_periods=1).shift(-3))
df

rawDescription: how to interpolate data in csv file with rolling/moving average? (Python)

description: Interpolate data in csv file with rolling/moving average? (Python)


rawDescription: Using Lambda Function in Python to generate a wavelength of numbers from -1.0 to 1.0


rawDescription: Python classmethod and(?) instancemethod


code:
max_index = NumberList.index(max(NumberList))
min_index = NumberList.index(min(NumberList))

rawDescription: Calculate rainfall with lists in python

description: Calculate rainfall with lists in python


code:
self.id, *rest = line.split('\t')
self.x1, self.y1, self.x2, self.y2 = map(float, rest)

rawDescription: Python: tuple assignment while at same time converting type


rawDescription: Counting frequency of words in documents using python regex


code:
from copy import copy

def f(a, b, c):
    l = copy(locals())

rawDescription: Printing options of the function in the command prompt line


code:
import re
db = '''\
www.sales   1D IN   A   10.0.0.1
www.learning    1D IN   CNAME   something
www.it 1D IN    AAAA    1::0::whatever
'''
re.findall(r"(\S+).*(?:\sA\s|\sCNAME\s)", db)

rawDescription: How to match an OR expression without grouping it?

description: Match an OR expression without grouping it


code: f.subs(x, 1)

rawDescription: How to define a mathematical function in SymPy?

description: Define a mathematical function in SymPy


code:
def percentage_split(seq, percentages):
   assert sum(percentages) == 1.0
   prv = 0
   size = len(seq)
   cum_percentage = 0
   for p in percentages:
       cum_percentage += p
       nxt = int(cum_percentage * size)
       yield seq[prv:nxt]
       prv = nxt

rawDescription: Separate a list into four parts based on percentage even if the list is not divisible by 10. Python


code: self.render('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />{{aString}}', aString=aUnicodeString)

rawDescription: Unicode strings in tornado web app

description: Unicode strings in tornado web app


code:
...
(regexp, decorator(view)),
...

rawDescription: Overriding Django views with decorators

description: Overriding Django views with decorators


code:
import json

class Foo(object):
  def __init__(self, name, value):
    self.name = name
    self.value = value

myfoo = Foo('abc', 'xyz')
with open('foo.txt', 'w') as f:
  f.write(' '.join(["myfoo.%s = %s" % (k,v) for k,v in myfoo.__dict__.iteritems()]))

rawDescription: Write Python object attributes to txt file


code:
import pdb
def func():
    a = "blablabla"
    b = 1234
    c = some_calculation_of_a_and_b(a,b)
    pdb.set_trace()

rawDescription: Dump function variables to workspace in python/ipython


rawDescription: Python - number of digits in exponent

description: Python - number of digits in exponent


code:
for channel_number in channel_numbers:
    channel_data = band2['channel%d' % channel_number]
    column = [
        'Channel %d' % channel_number,
        str(channel_data[0]),
        '%s/%s' % (channel_data[1], channel_data[2]),
        str(channel_data[3])
    ]
    cell_widths = map(len, column)
    column_width = max(cell_widths)
    for i in range(len(column)):
        cell = column[i]
        padded_cell = cell + ' '*(column_width-len(cell))
        table[i].append(padded_cell)

for line in table:
    # If tabs don't make the columns align properly, try iterating through
    # column in line, and padding it with the appropriate number of spaces.
    print(' '.join(line))

rawDescription: Print out dictionary in a table format?

description: Print out dictionary in a table format


rawDescription: Finding punctuation marks in noisy text

description: Finding punctuation marks in noisy text


code:
import numpy as np

d = 5
n = 100
N = 100000
is_boundary = np.zeros(N, dtype=bool)
tpoints = np.random.normal(size=(N, d))
tperm = np.arange(N)
for i in range(n):
    hpoint = np.random.normal(size=d)
    region = np.cumsum(is_boundary) * 2 + (np.inner(hpoint, tpoints) < 0.0)[tperm]
    region_order = np.argsort(region)
    is_boundary[1:] = np.diff(region[region_order])
    tperm = tperm[region_order]
print(np.sum(is_boundary))

rawDescription: A fast way to count non-empty regions

description: A fast way to count non-empty regions


code:
Web = raw_input("Enter a value ")
Replaced = read_file("myfile.txt").replace("web-iphone", Web)
write_file("myfile.txt", Replaced)

rawDescription: Edit text in file in python

description: Edit text in file in python


code:
import  temp_test

p = ast.parse(inspect.getsource(temp_test))
Imports().visit(p)

rawDescription: How to textually find an imported name in a module

description: Textually find an imported name in a module


code: np.argmax(a == v[:,None],axis=1)

rawDescription: Row wise element search in an array

description: Row wise element search in an array


code: df = df.set_index(['Company', 'date'], inplace=True)

rawDescription: set multi index of an existing data frame in pandas

description: Set multi index of an existing data frame in pandas


code: ' AND '.join([ "my_id = '" + id + "'" for id in ids ])

rawDescription: Combine a list items and string

description: Combine a list items and string


code: pd.pivot_table(df4,index=['Max'], values=['A', 'B', 'C'], aggfunc = [np.sum])

rawDescription: Pandas :Add certain row of a dataframe to a certain row of the other dataframe


code:
def assign_attribute_value(request, id_item_type):
    ...
    return type_func[item_type.choice](item_type=item_type)

rawDescription: Can't return a HttpResponse inside a def in a view


code:
from playhouse.sqlite_ext import FTS5Model
FTS5Model.fts5_installed()

rawDescription: python and sqlite3, check if I can use fts5 extension?

description: Python and sqlite3, check if I can use fts5 extension


code:
from itertools import izip
foo = [["a", "b"], ["c", "d"]]
[''.join(a) for (a) in izip(*foo)]

rawDescription: Python .join() with a 2d array

description: Python .join() with a 2d array


code:
import csv
import sys
writer = csv.writer(sys.stdout)

rawDescription: Django/Jinja2 : Generate (data for) CSV via template syntax


code: M = tuple(buffer(M, i, Nb) for i in range(0, len(M), Nb))

rawDescription: Buffers and Memoryview Objects explained for the non-C programmer


code:
import Tkinter as tki # Tkinter -> tkinter in Python3

class App(object):

    def __init__(self):
        self.root = tki.Tk()

    # create a Frame for the Text and Scrollbar
        txt_frm = tki.Frame(self.root, width=600, height=600)
        txt_frm.pack(fill="both", expand=True)
        # ensure a consistent GUI size
        txt_frm.grid_propagate(False)
        # implement stretchability
        txt_frm.grid_rowconfigure(0, weight=1)
        txt_frm.grid_columnconfigure(0, weight=1)

    # create a Text widget
        self.txt = tki.Text(txt_frm, borderwidth=3, relief="sunken")
        self.txt.config(font=("consolas", 12), undo=True, wrap='word')
        self.txt.grid(row=0, column=0, sticky="nsew", padx=2, pady=2)

    # create a Scrollbar and associate it with txt
        scrollb = tki.Scrollbar(txt_frm, command=self.txt.yview)
        scrollb.grid(row=0, column=1, sticky='nsew')
        self.txt['yscrollcommand'] = scrollb.set

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

rawDescription: How to attach a Scrollbar to a Text widget?

description: Attach a Scrollbar to a Text widget


code: df.columns = pd.MultiIndex.from_arrays([level0, df.columns])

rawDescription: Creating Multi-hierarchy pivot table in Pandas


code: missing_ids=df2[df2['Date_y'].isnull()] #gives the whole necessary dataframe

rawDescription: Pandas Dataframe Groupby Determine Values in 1 group vs. another group


rawDescription: Is there a better way to assign a default value for next()


code:
widget_list = [builder.get_object('<widget_name>_{0}'.format(i))
               for i in range(1, n+1)]

rawDescription: Widget repeaters in gtk3 using python and glade


code:
def fn(self):
    pass

dir(fn)
fn.__get__

rawDescription: Python Method object creation

description: Python Method object creation


code:
import numpy as np
np.ndarray(shape=(5,6), dtype=np.object)

rawDescription: How to create a void matrix (not filled with ones or zeros) in Python of expected dimensions M times N?

description: Create a void matrix (not filled with ones or zeros) in Python of expected dimensions M times N


code:
@foo
def bar():
    pass

rawDescription: Optionally use decorators on class methods


rawDescription: Confusion over how to share and modify class level data between instances.


code:
with open('/path/to/image.png', 'r') as f:
    img = YourImage(f.read())
    for _ in range(1,10000):
        Bullet2(img)

rawDescription: Python class attributes usage and initialization


code: plt.suptitle('Name:{0}, MJD:{1}, std dev > {2:.2f}'.format(pname, mjd[i], rmslevel), fontsize=12, fontweight='bold')

rawDescription: limit plot title to only show a certain number of decimal places

description: Limit plot title to only show a certain number of decimal places


code:
integral, err = quad(integrand, 0, 100, args=(b, c))
np.allclose(100, integral)

rawDescription: get all solutions (2 unkowns) from fsolve in python 3.2

description: Get all solutions (2 unkowns) from fsolve in python 3.2


code: df.grouby('grp').apply(ols_res, xcols=['x1', 'x2'], ycol='y')

rawDescription: Python pandas: how to run multiple univariate regression by group


code: adjustframe.index.name = 'group'

rawDescription: pandas get index for a row value

description: Pandas get index for a row value


code:
class ProductForm(ModelForm):
    long_desc = forms.CharField(widget=forms.Textarea(attrs={'cols': 10, 'rows': 20}))
    short_desc = forms.CharField(widget=forms.Textarea)
    class Meta:
        model = Product

rawDescription: Change the width of form elements created with ModelForm in Django


rawDescription: Convert timestamp since epoch to datetime.datetime


rawDescription: Sum of all numbers inside a string

description: Sum of all numbers inside a string


code:
import re
re.findall(r'@(\S+)', ' I want to tell @susan and @rick that I love you all')

rawDescription: python string parse with @ and space

description: Python string parse with @ and space


code:
class MultipleMacroFor(object):
    def __init__(self, macro, names):
        self._macro = macro
        self._names = names

    def get_renderable(self, macro_var):
        return get_template_attribute(self.macro, macro_var)

def MultipleMacroForFactory(macro, names):
    attrs = dict()
    for name in names:
        attrs[name] = property(
            lambda self, name=name: self.get_renderable(name)
            )

    clsname = "MultipleMacroFor%s" % "".join(
        name.capitalize() for name in names
        )

    return type(clsname, (MultipleMacroFor,), attrs)(macro, names)

rawDescription: Python passing in a list of parameters to be used as dynamic properties


code:
def reverse_lines(filename, BUFSIZE=4096):
    f = open(filename, "rb")
    f.seek(0, 2)
    p = f.tell()
    remainder = ""
    while True:
        sz = min(BUFSIZE, p)
        p -= sz
        f.seek(p)
        buf = f.read(sz) + remainder
        if '\n' not in buf:
            remainder = buf
        else:
            i = buf.index('\n')
            for L in buf[i+1:].split("\n")[::-1]:
                yield L
            remainder = buf[:i]
        if p == 0:
            break
    yield remainder

rawDescription: How to read file in reverse order in python3.2 without reading the whole file to memory?

description: Read file in reverse order in python3.2 without reading the whole file to memory


code:
import inspect

class SpecialNodeVisitor(ast.NodeVisitor):
    def visit_FunctionDef(self, node):
        print(node)  # prints any node of type FunctionDef

_ast_nodes = inspect.getmembers(
    ast,
    lambda t: isinstance(t, type) and issubclass(t, ast.AST) and t is not ast.AST)
for name, node in _ast_nodes:
    name = 'visit_' + name
    if not hasattr(SpecialNodeVisitor, name):
        setattr(SpecialNodeVisitor, name, ast.NodeVisitor.generic_visit)

rawDescription: How to invoke super when the parent method may not be defined?

description: Invoke super when the parent method may not be defined


code:
df3 = pd.pivot_table(df, values=['D','E'], rows=['B'], aggfunc=[np.sum, np.mean])
df3
df3 = df3.ix[:, [('sum', 'D'), ('mean','E')]]
df3.columns = ['D', 'E']
df3

rawDescription: define aggfunc for each values column in pandas pivot table

description: Define aggfunc for each values column in pandas pivot table


rawDescription: Send e-mail if conditions are met, then sleep for one hour


rawDescription: Matrix-like printing of 2D arrays in Python


rawDescription: Python BeautifulSoup parsing specific text


code:
def OnNew(self, evt):
    if self.panel:
        self.panel.Destroy()
    self.panel = MainPanel(self)
    self.SendSizeEvent()

rawDescription: wxPython Panel in existing window: slow and small

description: WxPython Panel in existing window: slow and small


rawDescription: Removing parentheses and comma

description: Removing parentheses and comma


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

x = np.arange(10)
y = np.random.random(10)

fig = plt.figure()
plt.xlim(0, 10)
plt.ylim(0, 1)
graph, = plt.plot([], [], 'o')

def animate(i):
    graph.set_data(x[:i+1], y[:i+1])
    return graph

ani = FuncAnimation(fig, animate, frames=10, interval=200)
plt.show()

rawDescription: How can i make points of a python plot appear over time?

description: Make points of a python plot appear over time


code:
for span in h.xpath('//span[@id]'):
    span_id = span.attrib.get('id', None)
    parent_class = span.getparent().attrib.get('class', None)
    if parent_class is None:
        continue
    if redundant_span(span_id, parent_class):
        span.tag = "JUNK"
etree.strip_tags(h, "JUNK")

rawDescription: lxml strip_tags results in AttributeError

description: Lxml strip_tags results in AttributeError


code:
import datetime
datetime.datetime

rawDescription: How to get a dot notation of a python module?

description: Get a dot notation of a python module


rawDescription: Can number of matches in a regex be looped over?


code:
import numpy as np
np.take(list_data,arr_index)

rawDescription: NumPy: 1D numpy array to slice a list

description: NumPy: 1D numpy array to slice a list


code: cluster_entries = [ [0] for i in range(28) ]

rawDescription: Python list of list selective insertion

description: Python list of list selective insertion


code:
from Tkinter import *
settings = {"foo": 1, "bar": 1, "baz": 1}

def makeSomething(name):
    settings[name] = 2

root = Tk()
Button(root, text='Set foo',command=lambda *args: makeSomething("foo")).pack()
Button(root, text='Set bar',command=lambda *args: makeSomething("bar")).pack()
Button(root, text='Set baz',command=lambda *args: makeSomething("baz")).pack()
#...etc

rawDescription: Change the value of a variable with a button (Tkinter)


code:
video_count = 0
def capture (self,length):
    video_count+=1
    self.camera.start_recording(str(video_count) + '.h264')
    self.camera.wait_recording(length)
    self.camera.stop_recording()

rawDescription: Assigning incremental filenames within a cycle


code: df['data_prime'] = df['data'].apply(lambda x: 3*x)

rawDescription: Spreadsheet Manipulation Tricks w/ Python's Pandas


code:
df = pd.DataFrame({'A':[11,11,22,22],'mask':[0,0,0,1],'values':np.arange(10,30,5)})

grouped = df.groupby("A")

result = grouped.agg('first')
result

rawDescription: pandas dataframe groupby like mysql, yet into new column

description: Pandas dataframe groupby like mysql, yet into new column


code:
keep_running = True
while (keep_running):
    lo += 1
    for i in range(len(l)):
        if not l[i] < 3:
            # this will effectively
            # stop the while loop:
            keep_running = False
            break
        print(lo)

rawDescription: python combine 'while loop' with 'for loop' to iterate through some data

description: Python combine 'while loop' with 'for loop' to iterate through some data


code:
def equation(l):
    b = float(l[1])    # this avoids int division
    return b / sum([b/i for i in l])

rawDescription: Relation between the length of the list and the math formula


code: sage -python /path/to/my/script.py

rawDescription: Using Sage Math library within Python

description: Using Sage Math library within Python


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


code: t_EXPRESSION = r'\[.*\]'

rawDescription: Does ply.lex Parse The Same Token Once?

description: Does ply.lex Parse The Same Token Once


code:
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

    def __hash__(self):
        return hash((self.x, self.y))

rawDescription: How to override operator "in" in set of objects of my own class(Point)?

description: Override operator "in" in set of objects of my own class(Point)


code: return isprime

rawDescription: Why does my Python function work in the console, but not when called within code?


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


code:
array=[]
array_elem=['0.0']
for i in range(3):
    array.append(array_elem)

rawDescription: Python list processing issue

description: Python list processing issue


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

rawDescription: How to create rolling percentage for groupby DataFrame

description: Create rolling percentage for groupby DataFrame


code:
from itertools import groupby

def block_start(line, start=[None]):
    if 'Rank' in line:
       start[0] = not start[0]
    return start[0]

with open(filename) as file:
     block_sizes = [sum(1 for line in block) # find number of lines in a block
                    for _, block in groupby(file, key=block_start)] # group
print(block_sizes)
# -> [4, 4, 1]

rawDescription: Counting jump(no of lines) between first two 'String' occurrences in a file


code:
a = [item for item in a if item in b]
a

rawDescription: Remove item from Object set that doesn't exist in query set


code:
import pandas as pd
i = pd.read_csv('foo.csv', sep=' ')
i
i['A']

rawDescription: Storing each column in a separate dictionary using python


rawDescription: How to check word in file with list element by using index?

description: Check word in file with list element by using index


code:
number_of_inputs = 4
dictionary = {'one', 'two', 'three', 'four', 'five', 'six', 'seven'}
print_diff()

rawDescription: Check variables against a dictionary, and print the dictionary contents remaining


code:
def filter_by_key(key, value, objects):
    return [o for o in objects if region[key] == value][0]

try:
    region = filter_by_key('region', region_name, feed['config']['regions'])
    instance_type = filter_by_key('type', instace_type_name, region['instanceTypes'])
    # ...
    return decimal.Decimal(prices['USD'])
except IndexError:
    raise Exception("Failed to determine price for instance with region=%r, type=%r, size=%r, platform=%r" %
                (region_name, instance_type_name, instance_size_name, platform_name))

rawDescription: How can i improve the readablility of nested if and for statements

description: Improve the readablility of nested if and for statements


code:
def partial_k(f, k, seq):
    seq = tuple(seq)  # To handle any iterable
    def wrapper(x):
        return f(*(seq[:k] + (x,) + seq[k:]))
    return wrapper

print(partial_k(f, 2, [0, 1])(10))
print(partial_k(f, 1, [0, 1])(10))

rawDescription: Freezing all but one positional arguments


code:
from timeit import timeit
import random
from itertools import groupby
import re
import string
def consecutive_groupby(string):
    three_or_more = (char for char, group in groupby(string)
                     if sum(1 for _ in group) >= 3)
    return any(three_or_more)

def consecutive_re(string):
    return re.search(r'(.)\1\1', string) is not None

# worst-case: random data with no consecutive strings
test_string = ''.join([random.choice(string.ascii_letters) for _ in range(1000)])
consecutive_re(test_string), consecutive_groupby(test_string)
timeit('consecutive(s)', 'from __main__ import test_string as s, consecutive_re as consecutive', number=10000)
timeit('consecutive(s)', 'from __main__ import test_string as s, consecutive_groupby as consecutive', number=10000)
# insert repeated characters
test_string_with_repeat = test_string[:100] + 'aaa' + test_string[100:]
consecutive_re(test_string_with_repeat), consecutive_groupby(test_string_with_repeat)
timeit('consecutive(s)', 'from __main__ import test_string_with_repeat as s, consecutive_re as consecutive', number=10000)
timeit('consecutive(s)', 'from __main__ import test_string_with_repeat as s, consecutive_groupby as consecutive', number=10000)

rawDescription: Determine if string has 3 or more duplicate sequential characters in Python


code:
def Collection_is_cheap(C, price):
    result = []
    for rest in C:
        for dish in rest.menu:
            if dish.price <= price and rest not in result:
                result.append(rest)
    return result

rawDescription: Iterating over list of namedtuples, selecting restaurants


rawDescription: How to replace unicode characters in string with something else python?

description: Replace unicode characters in string with something else python


code:
a='"THESE","ARE","WORDS","AND","I","NEED","THEM","IN","A","LIST"'
[i.strip('"') for i in a.split(",")]
['THESE', 'ARE', 'WORDS', 'AND', 'I', 'NEED', 'THEM', 'IN', 'A', 'LIST']

rawDescription: Reading a string of data (with a particular format) into a list, in Python


code:
stmnt = session.query(Reference) \
        .join(Periodical) \
        .order_by(Periodical._name) \
        .filter(Reference._mark == False)

print(stmnt)

rawDescription: Order by child object's field in SQLAlchemy?


rawDescription: Import xlrd values append to list

description: Import xlrd values append to list


code:
pattern = "(this).*(string)"
def replacement(m):
    s = m.group()
    n_groups = len(m.groups())
    # assume groups do not overlap and are listed left-to-right
    for i in range(n_groups, 0, -1):
        lo, hi = m.span(i)
        s = s[:lo] + '<markup>' + s[lo:hi] + '</markup>' + s[hi:]
    return s
re.sub(pattern, replacement, text)

rawDescription: replacing all regex matches in single line

description: Replacing all regex matches in single line


code:
reader = csv.reader(f, delimiter=b',', quoting=csv.QUOTE_MINIMAL, quotechar=b'"')
next(reader)
f.seek(0)
reader = csv.reader(f, skipinitialspace=True, delimiter=b',', quoting=csv.QUOTE_MINIMAL, quotechar=b'"')
next(reader)

rawDescription: Python Unicode CSV with newline between quotes


rawDescription: Python .1 - .1 = extremely small number w/negative exponent?


code:
from collections import defaultdict
my_dict = defaultdict(str,form)
msg = """
%(Frist_Name)s

%(Last_Name)s
 """ % my_dict

rawDescription: How can I replace named vars in a string in python from an incomplete dictionary?

description: Replace named vars in a string in python from an incomplete dictionary


code:
data = f.read()
data[:50]

rawDescription: python urllib2 urlopen response

description: Python urllib2 urlopen response


code:
ax=plt.gca()
xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S')
ax.xaxis.set_major_formatter(xfmt)

rawDescription: plotting unix timestamps in matplotlib

description: Plotting unix timestamps in matplotlib


code: next((i for i, d in enumerate(hugelist) if 735 in d['ids']), None)

rawDescription: Python: find index of item containing X in list


code:
import random
import string

vowels = 'aeiou'
consonants = [c for c in string.ascii_lowercase if c not in vowels]
consonants += ['th','ch','sh','st','ck']

n = random.randint(1, 2)
word = ''
struct = ''

while len(struct) < 3 or n:  # minimum length 3
    if n == 1:
        word += random.choice(consonants)
        struct += 'c'
    elif n == 2:
        word += random.choice(vowels)
        struct += 'v'
    n = random.randint(0, 2)

print(word)
print(struct)
print(len(struct))

rawDescription: Random word generator termination condition malfunctioning


rawDescription: Python Iterative Loop Plot values

description: Python Iterative Loop Plot values


code:
# 'symlog' scaling, however, handles negative values nicely
pyplot.xscale('symlog')

rawDescription: What is the difference between 'log' and 'symlog'?


code:
index = next(i for i, (t1, t2) in enumerate(myTup) if t2 < threshold)
del myTup[index:]

rawDescription: Smart way to delete tuples

description: Smart way to delete tuples


code:
def BinPreOrder(T):
    if not Is_EmptyBinTree(T):
        answer = [BinRoot(T)]
        left = BinPreOrder(Left(T))
        if left is not None:
           answer.extend(left)
        right = BinPreOrder(Right(T))
        if right is not None:
           answer.extend(right)
        return answer

rawDescription: returns the preorder list of a tree in python

description: Returns the preorder list of a tree in python


code:
def p_expression_add(p):
    'expression : expression ADD term'
    p[0] = (p[1][0] + p[3][0], p[1][1] + p[3][1])

rawDescription: How to evaluate line of data in python

description: Evaluate line of data in python


code:
import csv

my_dict = {
  '20140311': {
    '1030': {
      'total_price': 9421626, 'end': 6.76, 'high': 6.85, 'start': 6.78, 'low': 6.67, 'volumn': 1396431
    },
    '1130': {
      'total_price': 5042807, 'end': 6.86, 'high': 6.91, 'start': 6.76, 'low': 6.76, 'volumn': 735220
    },
    '1400': {
      'total_price': 5410292, 'end': 6.79, 'high': 6.9, 'start': 6.88, 'low': 6.76, 'volumn': 792890
    },
    '1500': {
      'total_price': 6470290, 'end': 6.83, 'high': 6.85, 'start': 6.79, 'low': 6.74, 'volumn': 954111
    }
  }
}

def initialize_keys():
  for dict1 in my_dict.itervalues():
    for dict2 in dict1.itervalues():
      return dict2.keys()

with open('mycsvfile.csv', 'wb') as f:
  w = csv.DictWriter(f, initialize_keys())
  w.writeheader()
  for dict1 in my_dict.itervalues():
    for dict2 in dict1.itervalues():
      w.writerow(dict2)

rawDescription: How to save stock data to csv file using python

description: Save stock data to csv file using python


code:
def isinter(str1,str2,str3,check=True):
    # print "Checking %s %s and %s" % (str1, str2, str3)
    p1,p2,p3 = 0,0,0
    if check:
        if len(str1)+len(str2) != len(str3):
            return False
    while p3 < len(str3):
        if p1 < len(str1) and str3[p3] == str1[p1]:
            if p2 < len(str2) and str3[p3] == str2[p2]:
                # does str3[p3] belong to str1 or str2?
                if True == isinter(str1[p1+1:], str2[p2:], str3[p3+1:], False):
                   return True
                if True == isinter(str1[p1:], str2[p2+1:], str3[p3+1:], False):
                   return True
                return False
            p1 += 1
        elif p2 < len(str2) and str3[p3] == str2[p2]:
            p2 += 1
        else:
            return False
        p3 += 1
    return p1 == len(str1) and p2 == len(str2) and p3 == len(str3)

rawDescription: Algorithm to check the order of substrings in combined string


code:
import gzip. shutil

src = gzip.open('executable.gz.jpg', 'rb')
dest = gzip.open('executable', 'wb')

shutil.copyfileobj(src, dest)

src.close()
dest.close()

rawDescription: Python: binary file to gz file and then to jpg extension and finally return again to the original binary file


code:
import sympy as syp
x = syp.Symbol('x')
miles_to_km = x * 1.609344
syp.plot(miles_to_km, (x,0,10))

rawDescription: Setting the domain of a function in Python SymPy


code:
def neighbors_sorted(code, N=3):
  num = int(code, 2)
  return sorted(num ^ (1 << i) for i in range(N))

rawDescription: Binary string comparison

description: Binary string comparison


rawDescription: (re)naming only certain column names based on index, pandas/python


code:
def to_base_5(n):
    s=""
    while n:
        s=str(n%5)+s
        n=n/5
    return s

rawDescription: How can I work with base 5 numbers in Python?

description: Work with base 5 numbers in Python


code:
x = np.array([1, 2, 3])
np.subtract.outer(x, x)

rawDescription: performing outer addition with numpy

description: Performing outer addition with numpy


code:
if inp in dic:
    print("The key is in the dictionary")

rawDescription: How to get the last item of the dictionary when looping

description: Get the last item of the dictionary when looping


code: product(*zip(L, fL))

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


code:
df
df.replace({'DSFS': {r'(\d+)\s*\-\s*(\d+)': r'\1_\2'}}, regex=True, inplace=True)
df

rawDescription: Removing word and replacing character in a column of strings


code: sqlite3.register_converter("BOOLEAN", lambda v: v != '0')

rawDescription: Storing bools in SQLite database

description: Storing bools in SQLite database


code:
def __repr__(self):
    return 'Country: %s  Model: %s' % (
        self.country.encode('utf8'), self.model.encode('utf8'))

rawDescription: How to __repr__ type unicode from database model