Skip to content

Instantly share code, notes, and snippets.

# Python 3 is an iterator-first language.
# `bind` and `join` are reaching wider adoption under the names `flatmap` and `flatten`.
def flatmap(f, xs):
return (y for x in xs for y in f(x))
def flatten(xs):
return (y for x in xs for y in x)
# These don't match the `zip(*args)` behavior of `map`, but I have never actually seen that used.
@acdimalev
acdimalev / dirrec.py
Created July 6, 2019 08:50
Fun with directory recursion and Python
fix = lambda f: lambda x: f(fix(f), x)
# presume Python's obsession with iterators...
join = __import__('itertools').chain.from_iterable
bind = lambda f, xs: join(map(f, xs))
# I/O primitives...
quoted = lambda s: '"' + str.replace(s, '"', '\\"') + '"'
unquoted = lambda s: str.replace(s[1:-1], '\\"', '"')
slash = lambda s: str.replace(s, '\\', '\\\\')
unslash = lambda s: str.replace(s, '\\\\', '\\')
shell_escape = lambda s: quoted(slash(s))
shell_unescape = lambda s: unslash(unquoted(s))
import socket
import pyroute2
ip = pyroute2.IPRoute()
addrs = [
'/'.join((
dict(addr.get('attrs', [])).get('IFA_ADDRESS'),
str(addr.get('prefixlen')),
))
def bits(measurement, unit):
'''Jinja filter to convert measurement from one unit to another.
Example:
{{ '1GiB' | bits('MiB') }}
-> 1024
'''
return first(convertTo(unit)(decode(measurement)))
@acdimalev
acdimalev / posit.py
Last active January 15, 2022 21:05
Decode a Posit-encoded number
#!/usr/bin/env python3
# http://web.stanford.edu/class/ee380/Abstracts/170201-slides.pdf
from math import inf, log
NBITS = 8
ES = 1
from dataclasses import field
@dataclass
class InMessage:
line: str
prefix: str
command: str
params: list[str]
#!/usr/bin/env python3
import crypt, random, sys
(_, nick) = sys.argv
password = '{:016x}'.format(random.randrange(256 ** 8))
crypted = crypt.crypt(password)
passwd_entry = ':'.join([nick, crypted])
File Format
|-- 32 bits --|
+---------------+
| file magic | 0xa42d19a9
|---------------|
| record magic | see Record Magic
|---------------|
| total records | actual number of stored records
all() {
case $# in
0) false ;;
*) (
result=0
while read x; do
if ! "$@" "$x"; then
result=1
fi
done