Discovered in 2013 by then-UPMC-student Jérémie Lumbroso, and independently re-discovered by an Apple programmer last Fall (with much ado on Twitter and Hacker News), the basic idea is as follows: Take your (infinite) random bitstream as the binary digits of random $r\in\left[0,1\right)$…
Python: Using XOFs for general-purpose Random
As always, one's own stack overflow answers make the best blog posts. In this case, we craft a version of random.Random with a few modifications: Pulls its data from an arbitrary stream (in our case, a DRBG such as a hash function or deterministic CSPRNG) Wastes noticeably fewer bits when generating random integers Has fixed code for .shuffle, on the offchance CPython ever changes theirs, and to make it …
Python: Rounding fractions half-up
By default, Python's fractions
rounds halves to the nearest even number. If you, instead, want to round a fraction but send halves up, here's how that's done:
def roundhalfup(x: Fraction) -> int:
"""
Rounds x to the nearest integer, with ties being rounded towards positive infinity
"""
return floor(x + Fraction(1, 2))
Python: Nested in-line "for" statements
You must leave the for
s in the same order as in the code-block form, only popping the inner expression itself to the front:…
Converting SVG to .ico with Python
Just a super rudimentary script that I made which hooks CairoSVG up to Pillow because apparently Firefox doesn't support SVG-formatted browserAction images
Breaking out of multiple "for" loops in Python
Python doesn't support break some_label;
or break 3;
, but it does support for-else
…
Parsing the HTTP "Date" header in Python
Per RFC 7231 §7.1.1.1
Python: Using "with" with sqlite3 cursor
If you like the assurance that Python's with statement provides, but can't figure out how to properly apply it to individual cursor objects, here's how to do that: import sqlite3 from contextlib import closing con = sqlite3.connect('example.db') with con, closing(con.cursor()) as cur: cur.execute(…)
Python: "with epoll"
If you're using Python 3.4+, select.epoll
already supports context — you're clear to just write with epoll() as E: …
and everything will be OK. If not, here's how to shim it:
CGI "Basic" HTTP Authorization, in a nutshell
Simply split on "Basic ", base64decode, split on ":", and decode the username.