Skip to content

Instantly share code, notes, and snippets.

View bedekelly's full-sized avatar

Bede Kelly bedekelly

View GitHub Profile
@bedekelly
bedekelly / hundred_prisoners.py
Created July 6, 2022 16:52
Experiment for the 100 Prisoners riddle explained by Veritasium
"""
100 prisoners are each given a number.
A room is arranged with 100 boxes, each containing a unique prisoner's number.
Each prisoner must enter the room, open at most 50 boxes, and leave without
communicating anything. Their aim is to find their own number.
If *every* prisoner finds their own number, they succeed.
If a *single* prisoner fails to find their own number, they fail.
The naive approach of each prisoner opening a random 50 boxes results in an
incredibly low chance of success, (1/2)^100.
@bedekelly
bedekelly / rehash.sh
Created April 3, 2022 11:04
Rehash CSS files and replace their occurrences in HTML files.
for file in projects shared style
do
# Move the file to a name matching its hash.
echo mv css/$file*.css css/$file-`minihash css/$file*.css`.css
mv css/$file*.css css/$file-`minihash css/$file*.css`.css
# Grab the new filename and replace all occurrences in HTML files.
filePath=`ls css/$file-*.css`
newFile="$(basename $filePath)"
echo $filePath $newFile
@bedekelly
bedekelly / useRefState.ts
Created February 24, 2022 10:38
Reactive state coupled with an immediately-updating ref
import { MutableRef, useCallback, useRef, useState } from "preact/hooks";
type RefState<T> = [MutableRef<T>, T, (newVal: T) => void];
export default function useRefState<T>(initialValue: T): RefState<T> {
const ref = useRef<T>(initialValue);
const [value, setValue] = useState(initialValue);
const setValueAndUpdateRef = useCallback((value: T) => {
ref.current = value;
@bedekelly
bedekelly / useStateWithCallback.ts
Created July 19, 2021 09:17
Use state hook with an extra "getState" parameter
export function useStateWithCallback<T>(
defaultState: T | (() => T)
): readonly [T, Dispatch<SetStateAction<T>>, () => Promise<T>] {
const [state, setState] = useState<T>(defaultState);
const getState = useCallback(() => {
return new Promise<T>((resolve) => {
setState((oldValue) => {
resolve(oldValue);
return oldValue;
@bedekelly
bedekelly / Knob.svelte
Created November 5, 2020 13:26
Svelte implementation of a 2-way-binding knob control
<!-- App.svelte -->
<script>
import Knob from './Knob.svelte';
let value = 0;
const reset = () => { value = 50 };
</script>
<Knob bind:value={value} max={100} min={0} pixelRange={200}/>
<p>
@bedekelly
bedekelly / useSequence.js
Created August 22, 2020 15:09
Simple sequence hook for use with step-by-step forms etc
function useSequence({ values, onComplete }) {
const [index, setIndex] = useState(0);
function next() {
setIndex((oldIndex) => {
if (oldIndex + 1 >= values.length) {
setImmediate(onComplete);
return oldIndex;
} else {
return oldIndex + 1;
@bedekelly
bedekelly / useFocusOnKey.js
Last active August 22, 2020 13:18
Hook enabling focus-on-key behaviour for an element
import { useEffect, useRef } from "react";
/**
* Focus the given element when a key is pressed;
* and unfocus it when Escape is pressed.
*
* e.g.
* const ref = useFocusOnKey('/');
* return <input ref={ref} />
*/
@bedekelly
bedekelly / nondeterminism.py
Created September 19, 2019 03:55
List monad (+alternative) for nondeterminism in Python
toss = {"Fair": ["Heads", "Tails"], "Biased": ["Heads", "Heads"]}
@do
def coins():
coin = yield ["Fair", "Biased"]
result = yield toss[coin]
_ = yield guard(result == "Heads")
return coin
# Probability of a biased coin, given you observed Heads, is 2/3.
@bedekelly
bedekelly / nondeterminism.hs
Created September 19, 2019 03:39
Haskell Nondeterminism
data CoinType = Fair | Biased deriving (Show)
data Coin = Head | Tail deriving (Eq,Show)
toss Fair = [Head, Tail]
toss Biased = [Head, Head]
pick = [Fair, Biased]
experiment = do
coin <- pick -- Pick a coin at random
@bedekelly
bedekelly / do_notation.py
Created September 18, 2019 10:02
Do Notation using Python's Yield Keyword
from functools import wraps
def do(f):
def partial_run(f, args, kwargs, values_so_far=()):
# First, create a NEW instance of the coroutine.
coroutine = f(*args, **kwargs)
# Advance the coroutine to the first yield point.
yielded_monad = next(coroutine)