Skip to content

Instantly share code, notes, and snippets.

View rldotai's full-sized avatar

Brendan Bennett rldotai

View GitHub Profile
@rldotai
rldotai / ndenum.py
Created January 7, 2019 04:12
N-dimensional enumeration and iteration, similar to `numpy.ndenumerate`
import itertools
def is_iterable(x) -> bool:
"""Return `True` if `x` is iterable."""
try:
iter(x)
return True
except TypeError:
return False
@rldotai
rldotai / comfy.py
Last active July 31, 2020 22:57
Common packages and utility functions that I find helpful
"""Setting up the local environment."""
import itertools
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from functools import reduce
@rldotai
rldotai / trim_whitespace.py
Created May 25, 2018 23:27
Trimming whitespace with ImageMagick
"""
A script for cropping whitespace around images using ImageMagick.
It finds all images within a directory and its subdirectories and calls
ImageMagic's convert/trim command to crop them, storing the results in an output
directory (by default `cropped`).
Details
-------
You can specify options to only include files according to a pattern, exclude
@rldotai
rldotai / matplotlib_trajectories.py
Created February 7, 2018 00:04
Plot trajectories using matplotlib.
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
def plot_trajectories(lst, ax=None, colors=None, cmap=None, alpha=None, ):
"""Plot trajectories via matplotlib's line segments.
Parameters
@rldotai
rldotai / convenient_sort.py
Created February 5, 2018 04:04
A slightly more convenient alternative to the builtin `sorted()` which allows you to specify a key as something other than a function.
"""
A slightly more convenient alternative to the builtin `sorted()` which allows
you to specify a key as something other than a function.
For example, with a list of lists, if you wanted to sort by the last element you
could use `sort(lstseq, key=-1)` rather than `sorted(lstseq, key=lambda x: x[-1])`.
If your key *is* a function, it behaves identically to `sorted()`, because it is
really just wrapping the builtin.
Examples
--------
@rldotai
rldotai / logging_snippet.py
Created October 11, 2016 22:41
Quick logging setup
"""
A quick logging setup and some helper functions.
Some code taken from: http://inventwithpython.com/blog/2012/04/06/stop-using-print-for-debugging-a-5-minute-quickstart-guide-to-pythons-logging-module/
"""
import logging
# get a logger, set the logging level
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
@rldotai
rldotai / interruptible_threads.py
Created May 7, 2016 23:58
Python threads that can be safely terminated via KeyboardInterrupt (e.g., ctrl-c)
#!/python3
"""
Python threads with a `threading.Event` flag to allow for safe termination with
a `KeyboardInterrupt`.
While it is possible to have all threads abruptly terminate by setting
`daemon == True` on the thread object, sometimes you need to perform cleanup,
so we essentially set a flag for the threads to check, assuming they all work
via an ongoing loop.
Note that this flag could be any object that evaluates to `True` or `False`,
@rldotai
rldotai / flatten_tree.js
Created January 31, 2016 06:21
Flatten a tree into an array by combining the keys.
// Flatten a tree into an array by combining the keys.
var flatten_tree = function(obj) {
var sep = '/';
var ret = [];
function _flat(elem, base) {
base = ((base === undefined) ? '' : base + sep);
for (let i in elem){
if (!elem.hasOwnProperty(i)) continue;
let val = elem[i];
@rldotai
rldotai / README.md
Last active February 8, 2016 07:46
Javascript Development with NPM and Browserify

Sometimes it is convenient to try to develop with just npm rather than splitting into client and server versions using bower or whatever else.

Setup

npm init
npm install -D browserify
npm install -D browserify-shim
npm install -D watchify
@rldotai
rldotai / sliding_window.py
Created January 21, 2016 02:10
Extracting patches from arrays
"""
Code for extracting sliding windows from arrays.
Particularly useful when you want to take patches from images prior to performing
some operation on them, like convolution or computing the mean.
"""
import numpy as np
from itertools import zip_longest
from PIL import Image
from numpy.lib.stride_tricks import as_strided