Code Snippets

Featured Code Snippets

  • Wilson Score Interval for Win-Rate Confidence

    JavaScript

    MetaLens VGC (public/js/lib/stats.js). Win-rate bounds that stay honest on small samples (a 3-0 record reads as 44-100%, not 100%), plus meta diversity as the effective number of species: exp of the Shannon entropy of usage counts.

    Wilson Score Interval for Win-Rate Confidence

    MetaLens VGC (public/js/lib/stats.js). Win-rate bounds that stay honest on small samples (a 3-0 record reads as 44-100%, not 100%), plus meta diversity as the effective number of species: exp of the Shannon entropy of usage counts.

    // Wilson score interval for a binomial proportion k/n, as [lo, hi] fractions.
    export function wilson(k, n, z = 1.96) {
      if (n === 0) return [0, 0];
      const phat = k / n;
      const z2 = z * z;
      const denom = 1 + z2 / n;
      const center = phat + z2 / (2 * n);
      const adj = z * Math.sqrt((phat * (1 - phat)) / n + z2 / (4 * n * n));
      return [(center - adj) / denom, (center + adj) / denom];
    }
    
    // exp(Shannon entropy) of usage counts, normalized to proportions.
    export function effectiveSpecies(counts) {
      const total = counts.reduce((a, b) => a + b, 0);
      if (total <= 0) return 0;
      let h = 0;
      for (const c of counts) {
        if (c <= 0) continue;
        const p = c / total;
        h -= p * Math.log(p);
      }
      return Math.exp(h);
    }
  • One Slot Test for Cross-Filter Chips

    JavaScript

    MetaLens VGC (public/js/lib/aggregate.js). Positive Pokémon chips are ANDed into a single per-Pokémon test, so "Rillaboom + Life Orb" keeps teams with a Rillaboom holding Life Orb; negative chips drop any team with a match.

    One Slot Test for Cross-Filter Chips

    MetaLens VGC (public/js/lib/aggregate.js). Positive Pokémon chips are ANDed into a single per-Pokémon test, so "Rillaboom + Life Orb" keeps teams with a Rillaboom holding Life Orb; negative chips drop any team with a match.

    /** The slot test built from the positive Pokémon chips, or null if there are none. */
    function slotTest(chips, dex, { keys = true } = {}) {
      const pos = chips.filter((c) => !c.neg);
      const keySet = keys ? new Set(pos.filter((c) => KEY_KINDS.has(c.kind)).flatMap(chipKeys)) : new Set();
      const attrs = pos.filter((c) => ATTR_KINDS.has(c.kind));
      if (!keySet.size && !attrs.length) return null;
      return (mon) => (!keySet.size || keySet.has(mon.k)) && attrs.every((c) => monMatchesAttr(mon, c, dex));
    }
    
    export function filterTeams(teams, filters = {}, chips = [], dex) {
      const { tiers, place, from, to } = filters;
      const slot = slotTest(chips, dex);
      const hasAttr = chips.some((c) => !c.neg && ATTR_KINDS.has(c.kind));
      return teams.filter((team) => {
        if (tiers && tiers.length && !tiers.includes(team.tier)) return false;
        if (place === 'topcut' && !team.topCut) return false;
        if (place === 'top8' && !(team.placing != null && team.placing <= 8)) return false;
        if (place === 'winner' && team.placing !== 1) return false;
        if (from && team.date < from) return false;
        if (to && team.date > to) return false;
        for (const c of chips) {
          const has = ATTR_KINDS.has(c.kind) && !c.neg ? true : teamHasChip(team, c, dex);
          if (c.neg ? has : !has) return false;
        }
        return !hasAttr || team.mons.some(slot);
      });
    }
  • Race-Safe Data Commits in the Weekly Refresh

    GitHub Actions

    MetaLens VGC (.github/workflows/refresh-data.yml). Commits only public/data, then rebases onto the latest branch tip and pushes, up to 5 attempts with growing back-off, so a long pipeline run never clobbers newer commits.

    Race-Safe Data Commits in the Weekly Refresh

    MetaLens VGC (.github/workflows/refresh-data.yml). Commits only public/data, then rebases onto the latest branch tip and pushes, up to 5 attempts with growing back-off, so a long pipeline run never clobbers newer commits.

    - name: Commit data if changed
      id: commit
      # The pipeline can run for a long time; other commits may land on the branch
      # meanwhile. Rebase the data commit onto the latest branch tip before pushing
      # (retrying if the branch moves again). The data commit only touches
      # public/data, so on a conflict there the freshly built data wins (-X theirs
      # = the commit being replayed). --autostash keeps a stray tracked-file change
      # (e.g. from npm ci) from blocking the rebase.
      run: |
        set -o pipefail
        {
          echo "== Commit data if changed"
          # ...
          git add public/data
          if git diff --cached --quiet; then
            echo "No data changes."
            exit 0
          fi
          git commit -m 'chore: refresh data'
          branch="${GITHUB_REF_NAME}"
          for attempt in 1 2 3 4 5; do
            if git pull --rebase --autostash -X theirs origin "$branch" && git push origin "HEAD:$branch"; then
              echo "Pushed data refresh (attempt $attempt)."
              exit 0
            fi
            git rebase --abort 2>/dev/null || true
            sleep $((attempt * 15))
          done
          echo "Could not push the data refresh after 5 attempts." >&2
          exit 1
        } 2>&1 | tee -a "$RUNNER_TEMP/refresh.log"
  • Exponential Backoff with Full Jitter

    TypeScript

    Reminder System (server/src/google/backoff.ts). Retry delay for Google API calls: the ceiling doubles per attempt up to a cap, the delay is random below it, and a server Retry-After acts as a lower bound.

    Exponential Backoff with Full Jitter

    Reminder System (server/src/google/backoff.ts). Retry delay for Google API calls: the ceiling doubles per attempt up to a cap, the delay is random below it, and a server Retry-After acts as a lower bound.

    export interface BackoffOptions {
      baseMs?: number;
      capMs?: number;
      /** Server-provided Retry-After, honoured as a lower bound. */
      retryAfterMs?: number;
      random?: () => number;
    }
    
    /** Exponential backoff with full jitter. `attempt` is 1-based (the attempt that just failed). */
    export function backoffDelayMs(attempt: number, o: BackoffOptions = {}): number {
      const base = o.baseMs ?? BACKOFF_BASE_MS;
      const cap = o.capMs ?? BACKOFF_CAP_MS;
      const ceiling = Math.min(cap, base * 2 ** Math.max(0, attempt - 1));
      const jittered = Math.floor((o.random ?? Math.random)() * ceiling);
      return Math.max(jittered, o.retryAfterMs ?? 0);
    }
  • CSRF Check for State-Changing Requests

    TypeScript

    Reminder System (server/src/http/csrf.ts). Safe methods pass; anything else must carry a custom header that a cross-site form or simple request cannot send.

    CSRF Check for State-Changing Requests

    Reminder System (server/src/http/csrf.ts). Safe methods pass; anything else must carry a custom header that a cross-site form or simple request cannot send.

    /** Methods that never change state and so need no CSRF header. */
    export const SAFE_METHODS: ReadonlySet<string> = new Set(['GET', 'HEAD', 'OPTIONS']);
    export const isSafeMethod = (method: string): boolean => SAFE_METHODS.has(method);
    
    export const CSRF_MESSAGE = 'Missing X-Requested-With: fetch header';
    
    /** True when the request carries the custom header a cross-site form or simple request cannot send. */
    export const hasCsrfHeader = (req: Pick<FastifyRequest, 'headers'>): boolean => (req.headers['x-requested-with'] ?? '') === 'fetch';
    
    /** True when the request is a state-changing one that lacks the CSRF header. */
    export const failsCsrf = (req: Pick<FastifyRequest, 'method' | 'headers'>): boolean => !isSafeMethod(req.method) && !hasCsrfHeader(req);
  • Next Occurrence of a Recurring Reminder

    TypeScript

    Reminder System (server/src/services/recurrence.ts). The next due time is computed in the user's wall-clock time so a daily 9am reminder stays 9am across DST, and COUNT is reduced by every occurrence consumed.

    Next Occurrence of a Recurring Reminder

    Reminder System (server/src/services/recurrence.ts). The next due time is computed in the user's wall-clock time so a daily 9am reminder stays 9am across DST, and COUNT is reduced by every occurrence consumed.

    /**
     * Next occurrence strictly after `dueAt` (and after `opts.now`), computed in wall-clock time of `tz`
     * so a daily 9am reminder stays 9am across DST. Returns null when the series is exhausted.
     * COUNT is reduced in the returned rule by every occurrence consumed (the completed one plus any skipped),
     * because the series restarts from the new dueAt.
     */
    export function nextOccurrence(rruleStr: string, dueAt: string, tz: string, options: NextOptions = {}): NextOccurrence | null {
      const rule = rruleStr.replace(/^RRULE:/i, '');
      const opts = RRule.parseString(rule);
      if (opts.count != null && opts.count <= 1) return null;
      const w = wallOf(tz, Date.parse(dueAt));
      const m = options.anchor ? /^(\d{2}):(\d{2}):(\d{2})$/.exec(options.anchor) : null;
      const startFloat = new Date(Date.UTC(w.y, w.mo - 1, w.d, m ? +m[1]! : w.h, m ? +m[2]! : w.mi, m ? +m[3]! : w.s));
      // UNTIL is a UTC instant but the series is computed in floating local time.
      if (opts.until) opts.until = new Date(toFloating(tz, opts.until.getTime()));
      const r = new RRule({ ...opts, dtstart: startFloat });
      const threshold = options.now != null ? new Date(Math.max(startFloat.getTime(), toFloating(tz, options.now))) : startFloat;
      const next = r.after(threshold, false);
      if (!next) return null;
      let newRule = rule;
      if (opts.count != null) {
        const consumed = 1 + r.between(startFloat, next, false).length;
        if (consumed >= opts.count) return null;
        newRule = rule.replace(/COUNT=\d+/i, `COUNT=${opts.count - consumed}`);
      }
      return { dueAt: new Date(fromFloating(tz, next.getTime())).toISOString(), rrule: newRule };
    }
  • Split Text on Paragraph, Sentence, Then Word Boundaries

    JavaScript

    TL;DR Panel (src/lib/chunking.js). Breaks long page text into chunks under a size limit, preferring the largest natural boundary, then packs the pieces greedily.

    Split Text on Paragraph, Sentence, Then Word Boundaries

    TL;DR Panel (src/lib/chunking.js). Breaks long page text into chunks under a size limit, preferring the largest natural boundary, then packs the pieces greedily.

    /** Split text into pieces no longer than maxChars, preferring paragraph, then sentence, then word boundaries. */
    export function splitText(text, maxChars) {
      const limit = Number.isFinite(maxChars) ? Math.max(1, Math.floor(maxChars)) : Number.MAX_SAFE_INTEGER;
      const units = [];
      for (const para of String(text).split(/\n{2,}/)) {
        const p = para.trim();
        if (!p) continue;
        if (p.length <= limit) {
          units.push(p);
          continue;
        }
        for (const sentence of p.split(SENTENCE_SPLIT)) {
          if (sentence.length <= limit) units.push(sentence);
          else units.push(...hardSplit(sentence, limit));
        }
      }
      // Greedily pack units into chunks.
      const chunks = [];
      let cur = '';
      for (const u of units) {
        if (!cur) cur = u;
        else if (cur.length + 2 + u.length <= limit) cur += '\n\n' + u;
        else {
          chunks.push(cur);
          cur = u;
        }
      }
      if (cur) chunks.push(cur);
      return chunks;
    }
  • Seeded Random Numbers for Procedural Generation

    TypeScript

    MRT Commute 3D (src/engine/rng.ts). An integer hash and a small mulberry32 generator, so the generated city is identical on every load.

    Seeded Random Numbers for Procedural Generation

    MRT Commute 3D (src/engine/rng.ts). An integer hash and a small mulberry32 generator, so the generated city is identical on every load.

    /** 32-bit integer hash of two ints (identical results in JS and the GLSL `hash2u` in shaders). */
    export function hash2i(x: number, y: number, seed = 0): number {
      let h = (Math.imul(x | 0, 0x27d4eb2d) ^ Math.imul(y | 0, 0x165667b1) ^ Math.imul(seed | 0, 0x3c6ef372)) >>> 0;
      h ^= h >>> 15;
      h = Math.imul(h, 0x2c1b3c6d) >>> 0;
      h ^= h >>> 12;
      h = Math.imul(h, 0x297a2d39) >>> 0;
      h ^= h >>> 15;
      return h >>> 0;
    }
    
    /** Hash of two ints to [0, 1). */
    export function hash01(x: number, y: number, seed = 0): number {
      return hash2i(x, y, seed) / 4294967296;
    }
    
    /** Small fast seeded PRNG (mulberry32). */
    export class Rng {
      private s: number;
      constructor(seed: number) {
        this.s = seed >>> 0 || 0x9e3779b9;
      }
      /** Uniform [0, 1). */
      next(): number {
        let t = (this.s = (this.s + 0x6d2b79f5) >>> 0);
        t = Math.imul(t ^ (t >>> 15), t | 1);
        t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
        return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
      }
      range(a: number, b: number): number {
        return a + (b - a) * this.next();
      }
      int(a: number, bInclusive: number): number {
        return a + Math.floor(this.next() * (bInclusive - a + 1));
      }
      chance(p: number): boolean {
  • Geodetic to ECEF Coordinates

    TypeScript

    MRT Commute 3D (src/geo/geodesy.ts). Converts latitude, longitude and height on the WGS84 ellipsoid to Earth-centred metres, the frame the 3D map tiles are in.

    Geodetic to ECEF Coordinates

    MRT Commute 3D (src/geo/geodesy.ts). Converts latitude, longitude and height on the WGS84 ellipsoid to Earth-centred metres, the frame the 3D map tiles are in.

    export const WGS84 = Object.freeze({
      a: 6378137.0,
      f: 1 / 298.257223563,
      get b() {
        return this.a * (1 - this.f);
      },
      get e2() {
        return this.f * (2 - this.f);
      },
    });
    
    const DEG = Math.PI / 180;
    const A = WGS84.a;
    const E2 = WGS84.e2;
    const B = WGS84.b;
    
    /** Geodetic (degrees, metres) → ECEF metres. */
    export function geodeticToEcef(latDeg: number, lonDeg: number, height = 0, out = new Vector3()): Vector3 {
      const phi = latDeg * DEG, lam = lonDeg * DEG;
      const sp = Math.sin(phi), cp = Math.cos(phi);
      const N = A / Math.sqrt(1 - E2 * sp * sp);
      return out.set((N + height) * cp * Math.cos(lam), (N + height) * cp * Math.sin(lam), (N * (1 - E2) + height) * sp);
    }
  • Group the Work Items into Project Umbrellas

    TypeScript

    This site (src/lib/projects-core.ts). Items sort newest first with a title tiebreak, then fill each umbrella's types in config order; empty types and umbrellas drop out.

    Group the Work Items into Project Umbrellas

    This site (src/lib/projects-core.ts). Items sort newest first with a title tiebreak, then fill each umbrella's types in config order; empty types and umbrellas drop out.

    /** Newest first, ties by title. */
    export function sortWorks<T extends WorkLike>(works: readonly T[]): T[] {
      return [...works].sort((a, b) => b.data.date.getTime() - a.data.date.getTime() || a.data.title.localeCompare(b.data.title));
    }
    
    /** Umbrella id of a type, or undefined for an unknown one. */
    export function umbrellaOfType(groups: ProjectGroups, type: string): Umbrella | undefined {
      return groups.umbrellas.find((u) => u.types.some((t) => t.id === type));
    }
    
    /** Umbrellas in config order, each with its non-empty types. Umbrellas without any project are dropped (they hide themselves). */
    export function buildUmbrellas<T extends WorkLike>(groups: ProjectGroups, works: readonly T[]): UmbrellaView<T>[] {
      const sorted = sortWorks(works);
      return groups.umbrellas
        .map((umbrella) => {
          const types = umbrella.types
            .map((type) => ({ type, items: sorted.filter((w) => w.data.type === type.id) }))
            .filter((g) => g.items.length > 0);
          return { umbrella, types, items: types.flatMap((g) => g.items) };
        })
        .filter((u) => u.items.length > 0);
    }
  • Contrast and Reduced-Motion CSS Generators

    JavaScript

    AccessEase (extension/lib/css.js). The extension builds its page-wide CSS from settings: media is excluded from colour overrides, and animations get a near-zero duration so elements that animate in still end visible.

    Contrast and Reduced-Motion CSS Generators

    AccessEase (extension/lib/css.js). The extension builds its page-wide CSS from settings: media is excluded from colour overrides, and animations get a near-zero duration so elements that animate in still end visible.

    function contrastCss(mode) {
      const p = PALETTES[mode];
      if (!p) return '';
      return [
        `html,body,body *${MEDIA_EXCLUDE}{background-color:${p.bg}${B};color:${p.fg}${B};text-shadow:none${B}}`,
        // ...
      ].join('\n');
    }
    
    function motionCss() {
      // Near-zero duration (not `none`) so elements that animate *in* still end visible.
      return `*,*::before,*::after{animation-duration:.001ms${B};animation-delay:0s${B};animation-iteration-count:1${B};transition-duration:0s${B};transition-delay:0s${B};scroll-behavior:auto${B}}`;
    }
HomeProfessional
ProjectsProfessional
All ProjectsProfessional
SoftwareProjects
InteractiveProjects
Data and AnalyticsProjects
OtherProjects
ExperienceProfessional
Quick summaryProfessional
Career TimelineProfessional
UsesProfessional
QualificationProfessional
Project HubProfessional
Code SnippetsProfessional
InteractiveProfessional
ResumeProfessional
Privacy
Terms
Cookies
QuestArchiveSoftware
DueReminderSoftware
AccessEaseSoftware
TL;DR PanelSoftware
asset-vaultSoftware
gfx-kitSoftware
House KitSoftware
sg-data-hubSoftware
vin-contextSoftware
vin-workflowSoftware
Black HoleInteractive
3D RoomInteractive
QR GardenInteractive
Synthwave DriveInteractive
MRT WindowInteractive
DevPulseData and Analytics
MetaLens VGCData and Analytics
esp32-core-kitOther
Toggle light / dark
Switch sidePersonal
Pause / resume effects
Copy email
Random page
Keyboard shortcuts
Download resume (PDF)

↑↓ move · Enter open · Esc close

Keyboard shortcuts

Ctrl K / ⌘K
Search the Site
?
Keyboard shortcuts
Esc
Close

ACHIEVEMENT UNLOCKED