Python: Nested in-line "for" statements

I'll explain with an example. Let's say that you've got some existing nested for-loop that you want to inline: for bytestring in x: for i in bytestring: for k in reversed(range(8)): yield ((i & (0b1 << k)) >> k) Intuitively, you might think that you would type something like "bit for k in bits for bits in in bytes for bytes in x" — but this is wrong. Instead, …

WordPress: Restrict MathJax to a class

I write on a variety of topics, only some of which it's appropriate to have mathematical typesetting for. To avoid triggering a math rendering engine on unrelated use of $spurious dollar signs$, while activating it when $\text{necessary}\wedge\text{appropriate}$, I decided to restrict them to only elements with .language-mathjax. Here's how that's done: MathJax = { tex: { inlineMath: [ ['$', '$'] ] }, startup: { elements: ['.language-mathjax'] } }; I …

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: import cairosvg.surface from PIL import Image from io import BytesIO def svg2ico(*args, resolutions={96, 48, 32, 24, 16}, write_to=None, **kwargs): t = cairosvg.surface.Tree(*args, **kwargs) ims = [] for res in resolutions: cairosvg.surface.PNGSurface(t, f:=BytesIO(), res * 2, output_width=res, output_height=res).finish() ims.append(Image.open(f)) im = _popmax(ims, key=lambda im: sum(im.size)) # TODO Fix …

Getting OpenNIC to work with pfSense

If you're using an alternate DNS root server such as OpenNIC, and your network uses a pfSense-based router, you may find that clients are, strangely, unable to resolve unofficial TLDs, getting SERVFAIL or NXDOMAIN. There are 3 ways I can think of to quickly solve this problem for the whole network, listed here in increasing order of complication: 1. Disable the DNS resolver Go to Services > DNS Resolver …

Applying highlight.js to inline code on WordPress

If you're using the plugin Prismatic to apply highlight.js to your code excerpts, but you want it to also affect inline <code> tags (i.e. those not wrapped in <pre> blocks), simply go Settings > Prismatic > Highlight.js and paste this monster into the “Init Script” field: // This init script was written by James E. // on May 7th, 2021. Its purpose is to enable // highlight.js to apply …

Breaking out of multiple "for" loops in Python

Let's say you have some nested for-loop that you want to break out of from the inner loop: x = default for key, values in dict_of_sets:  for value in values:  if predicate(value):  x = key  break 2 # INVALID SYNTAX, SADLY… Well, it turns out that Python supports for-else, so this can be made trivial: x = default_value  for key, values in dict_of_sets:  for value in values:  if predicate(key, …