Skip to content

Instantly share code, notes, and snippets.

View ninivert's full-sized avatar

Nicole Vadot ninivert

View GitHub Profile
@ninivert
ninivert / monitor_cpu.py
Last active March 20, 2025 11:02
Periodically poll CPU usage using a context manager
import psutil
import datetime
# NOTE: we cannot use threading, because if the main thread is busy with CPU stuff, the background thread will never run
# import threading
import multiprocessing
from contextlib import contextmanager
def _monitor_cpu(event: multiprocessing.Event, queue: multiprocessing.Queue, interval: float):
cpu_data = []
queue.put(cpu_data)
@ninivert
ninivert / vec.py
Created December 20, 2024 11:05
tuple class that supports elementwise math operations
from collections.abc import Iterable
import operator
import math
def full(x):
while True:
yield x
class vec(tuple):
@ninivert
ninivert / demo_linspace_interval_union.py
Last active October 4, 2024 14:04
Linspace on a union of (adjacent) intervals
import textwrap
import matplotlib.pyplot as plt
for intv_list in [(0.0, 1.1)], [(0.5, 1.0), (1.0, 0.0)], [(0.8, 1.0), (1.0, -1.0), (-1.0, -0.8)]:
nsamples_arr = [2,3,4,8,13,32]
fig, axs = plt.subplots(ncols=len(nsamples_arr), figsize=(3*len(nsamples_arr), 3), sharey=True)
for ax, nsamples in zip(axs.flat, nsamples_arr):
linspace, indices = linspace_interval_union(intv_list, nsamples)
assert len(linspace) == nsamples
assert len(indices) == len(intv_list)
import unittest.mock
def myfn(x):
return x+1
# needed so we don't recurse infinitely, because myfn will become replaced with newfn
_myfn = myfn
def newfn(x):
return _myfn(x)+1
@ninivert
ninivert / tuple3sort.py
Created July 29, 2024 09:42
constant-time sort of a tuple of length 3
def tuple3sort(t1: float, t2: float, t3: float) -> tuple[float, float, float]:
"""sorts a 3-tuple using 2 or 3 comparisons"""
if t1 <= t2:
if t2 <= t3: return (t1, t2, t3)
elif t1 <= t3: return (t1, t3, t2)
else: return (t3, t1, t2)
else:
if t3 <= t2: return (t3, t2, t1)
elif t1 <= t3: return (t2, t1, t3)
else: return (t2, t3, t1)
@ninivert
ninivert / echo_partial.py
Created June 27, 2024 08:56
Partial application of a function, that also returns returns its arguments
import functools
class echo_partial(functools.partial):
"""wrapper around a function that also returns its arguments"""
def __call__(self, /, *args, **kwargs):
return args, kwargs, super().__call__(*args, **kwargs)
def add(x, y):
return x+y
@ninivert
ninivert / view_diagonals.py
Last active June 10, 2024 10:08
Create a view into all (anti-)diagonals of a numpy array (with any number of dimensions)
import numpy as np
def view_diagonals(arr: np.ndarray) -> np.ndarray:
"""Returns a view of all the diagonals in the array `arr`
If `arr` has shape (n1, n2, *rest),
then `view_diagonals(arr)` has shape (ndiags, nelmts, *rest), where
- `ndiags = max(1, n1 - n2 + 1)`
- `nelmts = min(n1, n2)`
"""
//////////////////////////////////////////////////////////////////////////////////////////
// Main Class
//////////////////////////////////////////////////////////////////////////////////////////
class DOMControls {
/**
* The constructor step up the class, option defaults and prepares the DOM
*/
constructor(options, parent, globalCallback, DOMNames) {
@ninivert
ninivert / mouse-tracker.js
Last active December 21, 2019 21:56
Utility to track the mouse position on a webpage
/**
* Mouse tracker class
* Tracks the position of the mouse relative to an element which was given to the constructor
* Supports touch and css transformations
* Initalization: elementMouseTracker = new MouseTracker(element)
* Usage: element.addEventListener(<any click, mousemove or touch event>, function () { <read data from elementMouseTracker> })
* MouseTracker.p: mouse position
* .pp: previous mouse position
* .cp: click position
* .button: which buttons are pressed
@ninivert
ninivert / flex-center-overflow-fix.scss
Created October 21, 2018 16:45
CSS snippet to have centered flex children overflow nicely
// Every line of this is crucial
// to center the item AND have if overflow correctly when the view is too narrow
.flex {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;