Skip to content

Instantly share code, notes, and snippets.

Avatar

James JamesTheAwesomeDude

View GitHub Profile
@JamesTheAwesomeDude
JamesTheAwesomeDude / shell.bat
Last active September 18, 2023 17:50
Open a CMD window directly in a Python venv
View shell.bat
@echo off
REM After creating a venv via py -m venv "%USERPROFILE%\.venvs\MYVENVNAMEHERE"
REM Save this as %USERPROFILE%\.venvs\MYVENVNAMEHERE\Scripts\shell.bat
REM This script is OK to call from another folder, such as %USERPROFILE%
@echo on
REM Try python -m idlelib
cmd /k "%~dp0\activate.bat"
@JamesTheAwesomeDude
JamesTheAwesomeDude / teeinto_lockstep.py
Last active June 23, 2023 15:45
tee into multiple "for" loops in parallel without async, threading, or subprocess
View teeinto_lockstep.py
import greenlet
def teeinto_lockstep(
it: 'Iterable[TypeVar("Y")]',
*consumer_callables: 'Callable[[Iterable[TypeVar("Y")]], TypeVar("R")]'
) -> 'Tuple[TypeVar("R"), ...]':
"""tee iterable *it* into multiple non-`async def` consumers, in constant memory, without `threading`.
The consumer callables must take 1 argument, which is a normal (synchronous) iterable object.
@JamesTheAwesomeDude
JamesTheAwesomeDude / Multiset.py
Last active June 14, 2023 23:56
SortedList-based Multiset
View Multiset.py
"""Multiset implementation.
"""
__all__ = ["Multiset"]
from sortedcontainers import SortedList # https://pypi.org/project/sortedcontainers/
from collections import Counter, deque
@JamesTheAwesomeDude
JamesTheAwesomeDude / joint_groupby.py
Last active July 7, 2023 13:23
groupby multiple iterables in parallel
View joint_groupby.py
def joint_groupby(*iterables, key=None, ordered=True):
"""Like itertools.groupby, but iterates through a collection of iterables.
If the value type (or the return type of key) is not comparable, you MUST pass ordered=False.
Example: [(x, tuple(sum(1 for _ in group) for group in groups)) for x, groups in joint_groupby(...)]"""
if key is None:
key = lambda x: x
iterables = [iter(it) for it in iterables]
stop = object()
buffer = [next(it, stop) for it in iterables]
@JamesTheAwesomeDude
JamesTheAwesomeDude / xgcd.py
Last active June 6, 2023 18:55
extended euclidean algorithm python
View xgcd.py
def xgcd(a, b):
"https://anh.cs.luc.edu/331/notes/xgcd.pdf"
x, x_ = 1, 0
y, y_ = 0, 1
while b:
q, b, a = *divmod(a, b), b
x, x_ = x_, x - q*x_
y, y_ = y_, y - q*y_
#assert a0*x + b0*y == math.gcd(a0, b0)
return x, y
@JamesTheAwesomeDude
JamesTheAwesomeDude / ez_generator_interface.py
Last active June 6, 2023 18:50
Wrapper function to ease generator-driven query-response pattern
View ez_generator_interface.py
def _ez_generator_interface(g):
"""Handy wrapper for generator-driven program flows.
Example usage:
def g(questions=[("What's 3 + 3?", 6), ("What's 9 + 10?", 19)]):
"Example generator function that yields queries expecting a reply"
for question, correct_answer in questions:
answer = yield question # <- KEY LINE
if int(answer) != correct_answer:
@JamesTheAwesomeDude
JamesTheAwesomeDude / postparse.py
Last active June 15, 2023 15:54
parse POST data without cgi module, for Python 3.11+
View postparse.py
import email.message, email.parser, email.policy
import urllib.parse
import re
from collections import namedtuple
try:
from resource import getpagesize
except ImportError:
import mmap
def getpagesize():
return mmap.PAGESIZE
@JamesTheAwesomeDude
JamesTheAwesomeDude / last_qualified.py
Last active June 9, 2023 18:40
Get the last element of a sequence matching some predicate
View last_qualified.py
def last_qualified(predicate, iterable, /, return_if_exhausted=True):
"""
Consumes iterable or sequence `iterable` until finding an item
not satisfying `predicate`, or until exhausted, then returns the last item
which satisfied `predicate`.
Raises ValueError if `iterable` is empty.
Raises ValueError if the first item from `iterable` does not satisfy `predicate`.
@JamesTheAwesomeDude
JamesTheAwesomeDude / normalized_lru.py
Last active March 24, 2023 14:39
Normalize function inputs before LRU cache
View normalized_lru.py
import functools
from .. import NORMALIZE_FUNC, EXPENSIVE_API_CALL
@(lambda t: lambda f: functools.wraps(f)(lambda x: f(t(x))))(NORMALIZE_FUNC)
@functools.lru_cache
def f(x):
return EXPENSIVE_API_CALL(x)
@JamesTheAwesomeDude
JamesTheAwesomeDude / createxmldoc.js
Last active February 21, 2023 15:30
Firefox/Chrome DOM stdlib: create XML document from scratch, including declaration
View createxmldoc.js
// example: createXMLDocumentWithDeclaration('http://www.topografix.com/GPX/1/1', 'gpx', null, 'version="1.0" standalone="yes"')
function createXMLDocumentWithDeclaration(namespaceURI, qualifiedNameStr, documentType=null, declarationData='version="1.0"') {
const document = new Document().implementation.createDocument(namespaceURI, qualifiedNameStr, documentType);
// https://www.w3.org/TR/xml/#NT-XMLDecl
document.insertBefore(document.createProcessingInstruction("xml", declarationData), document.firstChild);
return document;
}