Skip to content

Instantly share code, notes, and snippets.

@ValentaTomas
ValentaTomas / set_once.go
Created November 21, 2024 02:13
Thread-safe way to wait and propagate result/error to multiple places.
package utils
import (
"fmt"
"sync"
)
type result[T any] struct {
value T
err error
@ValentaTomas
ValentaTomas / tunnel.go
Last active November 21, 2024 02:12
Resend the same value to several places without handling subscribers. (Not recommended for production.)
type Tunnel[T any] struct {
ch chan T
}
func (t *Tunnel[T]) Send(ctx context.Context, value T) error {
select {
case t.ch <- value:
return nil
case <-ctx.Done():
return ctx.Err()
@ValentaTomas
ValentaTomas / readLine.ts
Created July 11, 2024 06:33
Transform ReadableStream to async iterator of lines
async function* readLines(stream: ReadableStream<Uint8Array>) {
const reader = stream.getReader();
let buffer = ''
try {
while (true) {
const { done, value } = await reader.read();
if (value !== undefined) {
buffer += new TextDecoder().decode(value)
@ValentaTomas
ValentaTomas / must.go
Created March 23, 2024 00:29
Go utility for ensuring a proper value that panics otherwise
func Must[T any](obj T, err error) T {
if err != nil {
panic(err)
}
return obj
}
@ValentaTomas
ValentaTomas / ttl_cache.py
Last active January 8, 2024 11:39
Generic Python TTL cache that uses threads
import threading
import time
from typing import Callable, TypeVar, Generic, Any, Dict, Tuple, List
T = TypeVar("T")
class TTLCache(Generic[T]):
def __init__(
@ValentaTomas
ValentaTomas / stopwatch.py
Created December 22, 2023 14:04
Measure execution time of a function
def stopwatch():
def decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
elapsed_time = end_time - start_time
print(f"time taken {elapsed_time: 2f}")
return result
@ValentaTomas
ValentaTomas / hash.ts
Last active October 13, 2023 20:13
Hash files
import * as crypto from 'crypto'
const delimiter = '\0'
export function getFilesHash(files: { name: string; content: string }[]) {
const shasum = crypto.createHash('sha1')
files.forEach(({ name, content }) => {
shasum.update(name)
// Add delimiter to hash to prevent collisions between files where the join of the name and content is the same
@ValentaTomas
ValentaTomas / random.sh
Last active October 4, 2024 07:51
Generate random string (the chars are only hex, not alphanumerical)
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
@ValentaTomas
ValentaTomas / id.py
Created August 4, 2023 14:26
Random alphanumeric id generator
import random
import string
characters = string.ascii_letters + string.digits
def id(length: int):
return "".join(random.choices(characters, k=length))
@ValentaTomas
ValentaTomas / deferred_future.py
Last active December 20, 2023 20:20
Deferred future for controlling async flow (there are existing asyncio features for doing this)
import asyncio
import json
from typing import TypeVar, Generic, List
T = TypeVar("T")
class DeferredFuture(Generic[T]):
def __init__(self):