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
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)}")
X9
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
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}"; }
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
1















