Skip to content

Instantly share code, notes, and snippets.

@SF-300
SF-300 / coins.py
Created June 12, 2024 15:07
My take on an algorithm to generate all possible coins combinations that add up to given amount (a.k.a. vending machine change problem)
"""
This module provides functions for splitting an amount into coins using given denominations.
The problem of generating change for a given amount, also known as the vending machine change problem (a special case of the knapsack problem), involves finding all possible combinations of coins that add up to a given amount.
"""
import functools
def split_iter(amount: int, denominations: tuple[int]):
if not denominations or amount < 0:
@SF-300
SF-300 / delays.py
Last active July 3, 2023 18:23
Declaratively describe delays - mostly for retry actions.
"""
This module provides a declarative way to describe delay strategies for controlling the interval between repeated actions, such as retrying a network request.
There are two categories of strategies:
1. Root Strategies: These provide the base logic for calculating delay time.
- Linear: Increases delay time linearly.
- Exponential: Increases delay time exponentially.
2. Modifier Strategies: These adjust the delay time calculated by a root strategy.
@SF-300
SF-300 / komorebi_async_events.py
Last active November 17, 2023 21:12
async reading of win32 named pipe containing komorebi window manager events
# NOTE(zeronineseven): Heavily based on https://gist.github.com/denBot/4136279812f87819f86d99eba77c1ee0
import asyncio
import contextlib
import json
from contextlib import AsyncExitStack
from pathlib import Path
from typing import AsyncContextManager, Protocol, AsyncIterator, Never
import win32event
import win32pipe
@SF-300
SF-300 / winuds.pyx
Created April 2, 2023 12:05
UDS under Windows POC
from ctypes import windll, Structure, c_char, c_ushort, c_char_p, POINTER, c_int, WinError
from ctypes.wintypes import WORD
from typing import Literal, TypeAlias
__all__ = "test",
_ExtraInfo: TypeAlias = Literal["peername", "socket", "sockname"]
@SF-300
SF-300 / namespace.py
Last active March 23, 2023 11:06
More convenient syntax for SimpleNamespace instances creation.
from types import SimpleNamespace
from typing import Any
__all__ = "NamespaceMeta", "Namespace"
class NamespaceMeta(type):
"""Provides namespacing infrastructure.
This metaclass provides an alternative (and hopefully more convenient) syntax for creating 'types.SimpleNamespace'
instances using 'class' syntax.
@SF-300
SF-300 / sigslot.py
Created February 7, 2023 20:27
Simple signal pattern implementation with async slots support.
import weakref
import inspect
from typing import Callable, TypeVar, Protocol
__all__ = "Listenable", "Signal",
_Slot = TypeVar("_Slot", bound=Callable, contravariant=True)
@SF-300
SF-300 / anyof_constraint.py
Last active January 18, 2023 16:14
Any-of constraint building using SQLAlchemy
import operator as op
import sqlalchemy as sa
__all__ = "anyof_constraint",
def anyof_constraint(*cols, at_least_one: bool = False) -> sa.CheckConstraint:
if len(cols) < 2:
raise ValueError("At least 2 columns MUST be provided to create any-of constraint!")
@SF-300
SF-300 / composite.py
Last active January 9, 2023 12:24
Postgres composites for SQLAlchemy 1.4
from typing import TypeAlias, Type
from frozendict import frozendict
import sqlalchemy as sa
import sqlalchemy.types
import sqlalchemy.event
import sqlalchemy.schema
import sqlalchemy.sql.sqltypes
__all__ = "define_composite", "CreateComposite", "DropComposite"
@SF-300
SF-300 / sdi.py
Last active February 10, 2023 10:25
Standalone FastAPI-like dependency injector POC
import asyncio
import contextlib
import inspect
from inspect import Parameter, Signature
from dataclasses import dataclass
from contextlib import AsyncExitStack, AbstractContextManager, AbstractAsyncContextManager
from typing import Callable, ParamSpec, TypeVar
__all__ = "Depends", "inject_and_run"
@SF-300
SF-300 / fastapi_utils.py
Last active February 15, 2023 11:45
Mounting ASGI subapps through FastAPI's router
import unittest.mock
from fastapi import FastAPI as _FastAPI, APIRouter as _APIRouter, routing
__all__ = "FastAPI", "APIRouter"
class APIRouter(_APIRouter):
def include_router(self, router, **kwargs) -> None:
prefix = kwargs.get("prefix", "")