Skip to content

Instantly share code, notes, and snippets.

@mitjat
mitjat / sample.py
Created April 29, 2015 20:59
(Stratified) sampling without replacement of lines on stdin.
#!/usr/bin/env python
"""
(Stratified) sampling without replacement of lines on stdin.
Preserves random N lines of input (without replacement), discards others.
Optionally, lines can be grouped into classes based on a value extracted from the line;
in this case, N lines per group are preserved.
Order is not preserved.
Examples:
@mitjat
mitjat / springerlink-rename.js
Created September 6, 2012 17:24
Mass-download SpringerLink articles
@mitjat
mitjat / udacityplots.py
Created September 3, 2012 19:16
A drop-in replacement for the udacityplots library
import base64
import json
import matplotlib, matplotlib.pyplot
import numpy
import types
def show_plot(width, height=None):
"""
A decorator -- show the matplotlib plot after `f` completes.
Takes optional parameters (width, height) determining the size of the plot.
@mitjat
mitjat / restart_on_exception.py
Created March 8, 2012 14:32
Python function decorator for "infallible" functions: a decorated function will be retried as many times as needed until no exceptions occur. Includes fancy logging.
def restart_on_crash(log_exprs=[]):
"""
A function decorator that re-runs the wrapped function in case it raises an exception.
This is repeated until the function succeeds.
`log_exprs` is a list of strings, each string being an expression whose value at the time
of exception is displayed. Example:
>>> @restart_on_crash(log_exprs=['b', 'a+b'])
>>> def divider(a):
>>> import random; random.seed(time.time())
@mitjat
mitjat / csv_table_field.py
Created January 9, 2012 15:37
A specialized CharField which leniently parses its input as CSV (comma-separated values). Ideal for when data is to be imported from Excel - users only need to copy&paste. Also supports basic data validation.
#-*- coding:utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django import forms
from django.conf import settings
from django.utils.encoding import smart_unicode
from django.utils.encoding import force_unicode
from django.core.exceptions import ValidationError