Skip to content

Instantly share code, notes, and snippets.

View ninlith's full-sized avatar

Okko Hartikainen ninlith

View GitHub Profile
@ninlith
ninlith / async_memoize.py
Last active January 7, 2025 12:44
Asynchronous function cache.
"""Coalescing LRU and TTL function cache."""
import asyncio
import atexit
import logging
import time
from collections import defaultdict, OrderedDict
from functools import wraps
logger = logging.getLogger(__name__)
@ninlith
ninlith / fitcat.py
Last active December 14, 2024 16:33
Fitcat. A cat that truncates long lines.
# Fitcat. A cat that truncates long lines.
import contextlib, os, shutil, sys
try:
width = os.get_terminal_size(sys.stdin.fileno()).columns
except OSError:
width = shutil.get_terminal_size().columns
with contextlib.ExitStack() as stack, contextlib.suppress(BrokenPipeError):
for f in [stack.enter_context(open(fname)) for fname in sys.argv[1:]]:
[print(line[:width].rstrip()) for line in f]
@ninlith
ninlith / unround.py
Created November 17, 2024 15:36
Unround decimal numbers.
"""
Reconstructs the numerator of a rounded rational number.
All fractions p/q are uniquely identifiable iff abs(q) <= 10**d.
Args:
x (float): Rounded decimal value.
d (int): Maximum decimal places used in rounding.
q (int): Denominator of the fraction.
r (callable, optional): Rounding function (default is round).
@ninlith
ninlith / click_all_radios.js
Created November 13, 2024 11:15
Click all radios
// @name Click all radios
// @description Selects a random radio button from each uniquely named radio group.
javascript:(() => {
Object.values(Object.groupBy(document.querySelectorAll('input[type="radio"]'), e => e.getAttribute("name"))).forEach((arr) => {
arr[Math.floor(Math.random() * arr.length)]?.click?.();
});
})();
@ninlith
ninlith / syncstat
Last active January 9, 2023 15:19
Syncthing status
#!/usr/bin/env python3
"""Syncthing status."""
# https://nelsonslog.wordpress.com/2021/10/01/syncthing-status-from-the-command-line/
# https://svn.blender.org/svnroot/bf-blender/trunk/blender/build_files/scons/tools/bcolors.py
# https://docs.syncthing.net/dev/rest.html
import json
import re
HISTSIZE=1000000
HISTFILESIZE=1000000
HISTCONTROL=ignoreboth
shopt -s histappend
shopt -s histreedit
shopt -s histverify
PROMPT_COMMAND="history -a; history -c; history -r; $PROMPT_COMMAND"
PATH=$PATH:~/bin
PATH=$PATH:~/.local/bin
@ninlith
ninlith / mitm.sh
Last active December 7, 2024 16:18
Local transparent man-in-the-middle proxy setup
#!/usr/bin/env bash
# -*- indent-tabs-mode: nil; tab-width: 4 -*-
command=${@:-"mitmproxy --mode transparent --showhost --set block_global=false"}
if [ ! -f "/etc/ssl/certs/mitmproxyuser.pem" ]; then
sudo apt --yes install inotify-tools mitmproxy nftables
sudo useradd --create-home mitmproxyuser
grep --max-count 1 "mitmproxy-ca-cert.pem" < <( \
sudo inotifywait -mrq -e close_write --format "%f" \
@ninlith
ninlith / calculate
Last active February 8, 2021 06:48
External calculation for Gedit
#!/usr/bin/env python3
# [Gedit Tool]
# Name=Calculate
# Input=selection
# Output=replace-selection
# Applicability=always
# Save-files=nothing
# Shortcut=<Primary><Alt>c
# Languages=
@ninlith
ninlith / build.txt
Last active August 24, 2024 17:15
Hybrid UEFI/BIOS multiboot USB drive
# Hybrid UEFI/BIOS multiboot USB drive
# Install required packages
sudo apt install gdisk grub2-common grub-efi-amd64-bin grub-pc-bin qemu-system
# Create an empty disk image
target_size=3.6G # $(lsblk -b --output SIZE -n -d /dev/sdX) for drive size
qemu-img create -f raw boottitikku.img "$target_size"
# Create a GUID Partition Table (GPT)
@ninlith
ninlith / mouse-bind.sh
Created November 12, 2019 21:45
A hackish way to bind extra mouse buttons under Wayland.
#!/usr/bin/env bash
# -*- indent-tabs-mode: nil; tab-width: 4 -*-
#
# An ugly way to bind extra mouse buttons under GNOME/Wayland or otherwise.
#
# Prerequisites:
#
# Effectively unbind extra mouse buttons by modifying udev/hwdb rules:
# 1. Identify scancodes:
# sudo evemu-record /dev/input/by-path/*event-mouse \