Skip to content

Instantly share code, notes, and snippets.

View DavidAntliff's full-sized avatar

David Antliff DavidAntliff

View GitHub Profile
@DavidAntliff
DavidAntliff / multi_option.py
Created November 30, 2016 00:33
Python: accept multiple instances of a command line argument
"""
Copyright 2016 David Antliff; this file is licensed under the terms of the Apache license version 2.0. For a full copy of the license, see https://www.apache.org/licenses/LICENSE-2.0
Accept two styles of repeated options on the command line.
Style 1 - each instance repeats the option itself. E.g.
$ python prog --option A --option B
Style 2 - each instance occurs after a single instance of the option. E.g.
@DavidAntliff
DavidAntliff / partition_by_set.py
Last active March 15, 2017 01:37
Python: partition a string with a set of delimiters
import re
def partition(string, delimiters):
"""Split a string into a (head, sep, tail) tuple based on the
first occurrence of a delimiter in the string.
This is similar to str.partition() except it accepts a set of delimiters.
The set can be a list/tuple of characters, or a string."""
seps = "".join(delimiters)
return re.match(r"([^{seps}]*)([{seps}]?)(.*)".format(seps=seps), string).groups()
@DavidAntliff
DavidAntliff / coerce_iterable.py
Created March 15, 2017 01:38
Coerce a scalar or sequence into an iterable
def coerce_iterable(scalar_or_sequence):
"""If scalar_or_sequence is not iterable, wrap it so that the return value is."""
try:
_ = tuple(x for x in scalar_or_sequence)
result = scalar_or_sequence
except TypeError:
# The user has probably specified a single entity and forgotten to
# define it as a proper tuple, so be friendly and handle as a scalar instance:
result = (scalar_or_sequence,)
return result
@DavidAntliff
DavidAntliff / custom_logging.py
Last active March 21, 2017 22:29
Python: install custom logging handlers for stdout and stderr based on --debug/--verbose flags
import logging
import sys
def init_logging(name, log_level):
# install handlers for stdout (DEBUG, INFO) and stderr (WARNING, ERROR)
# http://stackoverflow.com/a/16066513/143397
logger = logging.getLogger(name)
logger.setLevel(log_level)
@DavidAntliff
DavidAntliff / git-rinse.sh
Created March 21, 2017 22:28
Git Rinse - revert a project back to a just-cloned state quickly
#!/bin/bash
# Note: this removes all uncommitted changes and untracked files!
git clean -xfd
git submodule foreach --recursive git clean -xfd
git reset --hard
git submodule foreach --recursive git reset --hard
git submodule update --init --recursive
@DavidAntliff
DavidAntliff / txt2csv.py
Created October 24, 2017 22:42
Convert xxd hexdump to CSV file for spreadsheet import
# Assumes in_txt was generated by `xxd -g1 in.bin > in.txt`
import csv
with open(in_txt) as fin, open(out_csv, 'w') as fout:
o=csv.writer(fout, quotechar='"', quoting=csv.QUOTE_ALL)
for line in fin:
row = line.rstrip('\n').split(sep=' ', maxsplit=17)
# remove one leading space from last item
row[-1] = row[-1][1:]
@DavidAntliff
DavidAntliff / float_to_rgba.py
Created December 19, 2017 02:26
Encode 32bit float into three 8bit RGBA channels
#!/usr/bin/env python
# Store 32-bit floating point number within three 8bit channels of a 32-bit RGBA pixel.
# Only suitable for normalised input values in the range [0.0, 1.0).
#
# Refer: https://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
import numpy as np
def frac(x):
return x - np.floor(x)
@DavidAntliff
DavidAntliff / dice_roll.py
Created October 22, 2018 11:28
Simple simulation of rolling dice
#!/usr/bin/env python
# Python 3.x
import random
rolls = 5000 # the more results the better
scaling = 10 # scale the histogram to fit the screen
dice = (20,) # a single d20
#dice = (6, 6) # two d6s
@DavidAntliff
DavidAntliff / matplotlib-macos-notes.md
Last active August 15, 2019 02:41
Build Python 3.7.3 via pyenv on MacOS Mojave with matplotlib support

Errors about undefined symbols

Something something __Py_UnixMain _main python.o:

$ brew uninstall binutils

Xcode headers are not properly installed.

Error is:

@DavidAntliff
DavidAntliff / disable-acpi-wakeup.py
Created August 13, 2020 23:45
Deactivate ACPI devices that may cause hibernation to fail
#!/usr/bin/env python
"""
Deactivate ACPI devices that may cause hibernation to fail
"""
from dataclasses import dataclass
import subprocess
@dataclass