X

X0

$ units -t '1 mm/sec' 'furlongs per fortnight'

6.0128848


X1


X2

Christmas ornaments for nerds. A Bloch Sphere.


X3

A mathematician once confided
That a Möbius band is one-sided,
And you’ll get quite a laugh,
If you cut one in half,
For it stays in one piece when divided.


X4

Compile C programs on the fly at the shell prompt:

echo 'main() { printf("Hello world!\n"); }' | gcc -w -x c - -o hello

echo '#include
int fibonacci(int n){return n<2?n:fibonacci(n-1)+fibonacci(n-2);}
int main(){printf("%d\n",fibonacci(19));return 0;}' | gcc -x c - -o fib19


X5

Generate magic squares of odd order with bc under bash

#! /bin/bc -q
define magic_constant(n) {
    return(((n * n + 1) / 2) * n)
}
define print_magic_square(n) {
    auto i, x, col, row, len, old_scale
    old_scale = scale
    scale = 0
    len = length(n * n)
    print "Magic constant for n=", n, ": ", magic_constant(n), "\n"
    for (row = 1; row <= n; row++) {
        for (col = 1; col <= n; col++) {
            x = n * ((row + col - 1 + (n / 2)) % n) + \
                ((row + 2 * col - 2) % n) + 1
            for (i = 0; i < len - length(x); i++) {
                print " "
            }
            print x
            if (col != n) print " "
        }
        print "\n"
    }
    scale = old_scale
}
temp = print_magic_square(3)
quit


X6

There is a formula that gives the volume of a Chicago style deep dish pie with thickness a and radius z: pi zz a


X7

Deriving Egyptian fractions with Python

(Egyptian fractions are a finite sum of distinct unit fractions)

#!/usr/bin/env python3
import sys
from sympy import Rational
from sympy.ntheory.egyptian_fraction import egyptian_fraction
try:
    n,d = map(int, sys.argv[1].split('/'))
    if d == 0: raise ValueError("zero denominator")
except Exception as e:
    print(f"Usage: {sys.argv[0]} numerator/denominator ({e})")
    sys.exit(1)
r = Rational(n,d)
e = egyptian_fraction(r)
print(f"{r} = {' + '.join(f'1/{x}' for x in e)}")


X8

Then there is Star Trek. I was one year old when it first aired, but I saw it in endless syndication from as early as I can remember. The likes of Harlan Ellison and Robert Bloch wrote it. Then came peak Star Trek with the Next Generation. After it reached its groove with the 3rd season we saw some of the best hours of television ever. With DS9, instead of boldly going to explore strange new worlds the strangers came to the station. Still, there were almost no bad episodes and a few memorable ones, including a self-insertion into the TOS Tribbles episode. Voyager was boldly coming back home from where no man has gone before, like starting at Yellowstone with pressure not to stop anywhere because the kids keep saying, “Are we home yet?” Enterprise scratched my itch for filling in the 22nd Century lacuna of canon Trek but it had its own problems. Kelvin timeline? No. Jar Jar Abrams did the same thing to Trek as he did to Star Wars. I haven’t seen S-TP or STD or anything else, nor do I ever want to.


X9

I am old enough to remember watching Star Wars in the theater, first run. Just Star Wars. No bloody III or VII or IX. The only CGI on screen is the quaint computer readouts. It came out of nowhere and changed everything. It created an immersive self-consistent universe that was similar in some ways to our own, yet in other ways entirely new. The sequel is astonishing in the way it deepened the mythos. The arc of Han Solo in the original trilogy from selfish rogue to someone a princess could love is timeless. The redemption arc of Anakin Skywalker across the first six films is truly epic. Then Jar Jar Abrams comes along and gives us an essentially shot-for-shot remake of A New Hope. After that Rian Johnson, who is otherwise an excellent filmmaker, took the entire setup from VII and deconstructed everything by killing off the Big Bad and democratizing the Force, which undermines the whole reason for tracking the Skywalker bloodline. I didn’t even bother to watch part IX.


XA

In my mind’s eye there is a group of people who embrace the good parts of Catholicism, the universality and historical pedigree, while maintaining a stance of no tolerance for the abuse of innocents and they look askance at the traditions that seem to cut women out of the loop. Credopunk is an inspired choice for the name of this movement. They approach the Blessed Sacrament while wearing a sash with crosses and metal spikes. The saint Credopunks ask to intercede for them is Jeanne d’Arc obviously. The favorite X-man of Credopunks is Nightcrawler. They’re into shows like The Pope’s Exorcist. They make #Catholicism seem so dang cool even Adventist kids sign up for RCIA. There’s a Credopunk convent with the sisters blinged out like Lisbeth Salander.


XB

Convert decimal to 16 bit binary and trim leading zeros:


#! /bin/bash
D2B=({0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1})
echo $((10#${D2B[$1]}))


XC

python3 -c "for i in range(0x1f640, 0x1f650): print(f'{i:#06x} {chr(i)}')"


XD


XE


XF


XG


XH

python3 -c "from datetime import datetime; d=(datetime(datetime.today().year,12,25)-datetime.today()).days; print(f'Only {d} shopping days until Christmas.')"


XI

Convert csv piped from stdin to sc format with Python

#!/usr/bin/env python3
import sys
import csv
import string
letters = string.ascii_uppercase
reader = csv.reader(sys.stdin) 
for row, fields in enumerate(reader):
    for col, val in enumerate(fields):
        if not val.strip():
            continue
        col_letter = letters[col]
        print(f'leftstring {col_letter}{row} = "{val}"')


XJ


XK

Random band name generator with Python

#!/usr/bin/python3
import random
with open("band.txt") as f:
    words = [w.strip() for w in f if w.strip()]
def make_band_name():
    n = random.choice([2, 3])  
    return " ".join(random.sample(words, n))
for _ in range(10):
    print(make_band_name())

Surf Spooky Baby
Contaminated Digestion Tango
Free Pistols
Arthur We’re Beat
Carnage Bull Mogen
Throwing Breast
Cool Balls
Vomit Liberty Beer
Charlie Death
Cheesecake Style


XL

Conway’s Game of Life

ffplay -f lavfi -i life=s=400x300:mold=10:r=30:ratio=0.1:death_color=#C83232:life_color=#00ff00,scale=1200:800:flags=32


XM


XN

showcolor() { display -size 300x300 xc:"#${1}"; }


XO

Herman and the Herberts

The Sex Phasers

Alpha and the Quadrants

The Alternative Rock Factor

Borgs Like Girls

Prime Directive Violators

Warp Core Meltdown


XP

Calculate Easter for 1900-2368 with Python

#!/usr/bin/python3
import sys
y=int(sys.argv[1]);c=y//100;n=y-19*(y//19);k=(c-17)//25
i=c-c//4-(c-k)//3+19*n+15;i-=30*(i//30)
i-=(i//28)*(1-(i//28))*(29//(i+1))*((21-n)//11)
j=y+y//4+i+2-c+c//4;j-=7*(j//7)
l=i-j;m=3+(l+40)//44;d=l+28-31*(m//4)
print(f”{m}/{d}/{y}”)


XQ


XR

Lake Diablo, Washington


XS

Calculus fun with Python

#!/usr/bin/python3
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-4, 4, 400)
f = np.arctan(x**2)
df = 2*x / (x**4 + 1)
plt.plot(x, f, 'b', label='f(x) = arctan(x²)')
plt.plot(x, df, 'r', label="f'(x) = 2x/(x⁴+1)")
plt.axhline(0, color='black', linewidth=0.5)
plt.axvline(0, color='black', linewidth=0.5)
plt.ylim(-2, 2)
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('f(x) and f\'(x)')
plt.grid(True, linestyle=':', alpha=0.7)
plt.show()


XT

Days between today and any date with Python

#!/usr/bin/python3
import sys; from datetime import datetime,date
formats=["%m/%d/%Y","%m/%d/%y","%Y-%m-%d","%d-%m-%Y","%d %b %Y","%d %B %Y"]
for f in formats:
  try: d=datetime.strptime(sys.argv[1],f).date(); break
  except: pass
else: exit("bad format")
print(abs((date.today()-d).days))


XU

Find palindromic words in a list with Python

#!/usr/bin/python3
def words(fileobj):
    for line in fileobj:
        for word in line.split():
            yield word
with open("words.txt") as wordfile:
    wordgen = words(wordfile)
    for word in wordgen:
        if word == word[::-1]:
            print(word, end=" ")
    print()


XV

Using Python to graph relativistic apparent speed as a starship approaches c

#!/usr/bin/python3
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(figsize=(8,6))
major_ticks = np.arange(0, 101, 5)
unit_ticks = np.arange(0, 101, 1)
minor_ticks = np.arange(0, 101, 0.2)
ax.set_xticks(major_ticks)
ax.set_yticks(major_ticks)
ax.set_xticks(unit_ticks, minor=True)
ax.set_yticks(unit_ticks, minor=True)
ax.grid(which='major', color='gray', linestyle='-', linewidth=0.8, alpha=0.8)
ax.grid(which='minor', color='black', linestyle='-', linewidth=0.5, alpha=0.7)
x = np.arange(0.7, 0.999, 0.0001)
y = x / np.sqrt(1 - x**2)
plt.plot(x * 100, y, color='blue', linewidth=2)
ax.set_xlim(70, 100)
ax.set_ylim(0, max(y)*1.1)
plt.xlabel("Real speed (percentage of c)")
plt.ylabel("Apparent speed (multiple of c)")
plt.tight_layout()
plt.show()


XW

Use gs to extract and display a single page from a PDF:

tmp=$(mktemp --suffix=.pdf) && gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -dFirstPage=54 -dLastPage=54 -sOutputFile="$tmp" "Who's Who in Lesbian and Gay Writing.pdf" && evince "$tmp" && rm "$tmp"


XX

Plot a cube in Python

#!/usr/bin/python3
import numpy as np
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection
import matplotlib.pyplot as plt
points = np.array([[-1, -1, -1],
[1, -1, -1 ],
[1, 1, -1],
[-1, 1, -1],[-1, -1, 1],
[1, -1, 1 ],
[1, 1, 1],
[-1, 1, 1]])
Z = points
Z = 10.0*Z
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
r = [-1,1]
X, Y = np.meshgrid(r, r)
ax.scatter3D(Z[:, 0], Z[:, 1], Z[:, 2])
verts = [[Z[0],Z[1],Z[2],Z[3]],
[Z[4],Z[5],Z[6],Z[7]],
[Z[0],Z[1],Z[5],Z[4]],
[Z[2],Z[3],Z[7],Z[6]],
[Z[1],Z[2],Z[6],Z[5]],
[Z[4],Z[7],Z[3],Z[0]]]
ax.add_collection3d(Poly3DCollection(verts, facecolors='cyan', linewidths=1, edgecolors='r',
alpha=.20))
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()


XY

Sort the Holy Bible by verse length with Perl

perl -e 'print sort {length $b length $a} ' kjv.txt


XZ