D2b

#! /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]}))

Posted in Uncategorized | Leave a comment

Sphere

Plot a 3D sphere with Python

#!/usr/bin/python3
import numpy as np
import matplotlib.pyplot as plt
theta, phi = np.linspace(0, 2 * np.pi, 50), np.linspace(0, np.pi, 20)
THETA, PHI = np.meshgrid(theta, phi)
R = 1.0
X = R * np.sin(PHI) * np.cos(THETA)
Y = R * np.sin(PHI) * np.sin(THETA)
Z = R * np.cos(PHI)
fig = plt.figure()
ax = fig.add_subplot(1,1,1, projection='3d')
plot = ax.plot_wireframe(X, Y, Z, rstride=1, cstride=1, linewidth=.1, color='red', antialiased=False, alpha=1)
plt.show()

Posted in Uncategorized | Leave a comment

Ellipse

#! /usr/bin/python3
import math
import sys
a = float(sys.argv[1])
b = float(sys.argv[2])
h = ((a - b) / (a + b))**2
eps = sys.float_info.epsilon
def binom_half(n):
    coef = 1.0
    for k in range(n):
        coef *= (0.5 - k) / (k + 1)
    return coef
perimeter = 0.0
n = 0
term = 1.0  
while abs(term) > eps:
    coef = binom_half(n)
    term = (coef**2) * h**(2*n)
    perimeter += term
    n += 1
perimeter *= math.pi * (a + b)
print(f"Ellipse perimeter: {perimeter:.17f}")
print(f"Series converged after {n} terms")

Posted in Uncategorized | Leave a comment

Ellipsoid

#! /usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
r = 10
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = r * np.outer(np.cos(u), np.sin(v))
y = r * np.outer(np.sin(u), np.sin(v))
z = r * np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(x, y, z, color='linen', alpha=0.5)
theta = np.linspace(0, 2 * np.pi, 100)
z = np.zeros(100)
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z, color='black', alpha=0.75)
ax.plot(z, x, y, color='black', alpha=0.75)
zeros = np.zeros(1000)
line = np.linspace(-10,10,1000)
ax.plot(line, zeros, zeros, color='black', alpha=0.75)
ax.plot(zeros, line, zeros, color='black', alpha=0.75)
ax.plot(zeros, zeros, line, color='black', alpha=0.75)
plt.show()

Posted in Uncategorized | Leave a comment

Maze

#!/usr/bin/python3
from random import shuffle, randrange
def makemaze(w=20,h=12):
    vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)]
    ver = [["|  "] * w + ['|'] for _ in range(h)] + [[]]
    hor = [["+--"] * w + ['+'] for _ in range(h + 1)]
    def walk(x, y):
        vis[y][x] = 1
        d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]
        shuffle(d)
        for (xx, yy) in d:
            if vis[yy][xx]: continue
            if xx == x: hor[max(y, yy)][x] = "+  "
            if yy == y: ver[y][max(x, xx)] = "   "
            walk(xx, yy)
    walk(randrange(w), randrange(h))
    s = ""
    for (a, b) in zip(hor, ver):
        s += ''.join(a + ['\n'] + b + ['\n'])
    return s
print(makemaze())

Posted in Uncategorized | Leave a comment

Say

#!/usr/bin/env python3
import sys
n = int(sys.argv[1])
ones = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
teens = ["ten", "eleven", "twelve", "thirteen", "fourteen","fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
tens = ["", "", "twenty", "thirty", "forty","fifty", "sixty", "seventy", "eighty", "ninety"]
if n < 10:
    print(ones[n])
elif n < 20:
    print(teens[n - 10])
else:
    t = n // 10
    o = n % 10
    if o == 0:
        print(tens[t])
    else:
        print(f"{tens[t]}-{ones[o]}")

Posted in Uncategorized | Leave a comment

Truthtable

Boolean truth tables in Python

#!/usr/bin/env python3
import sys
from itertools import product
bexp=" ".join(sys.argv[1:])
code=compile(bexp,"<string>","eval")
names=code.co_names
print("\n" + " ".join(names),":",bexp)
for values in product(range(2), repeat=len(names)):
    env=dict(zip(names,values))
    print(" ".join(map(str,values)),":",int(eval(code,env)))

Posted in Uncategorized | Leave a comment

Morse

Morse code generator with Sed

#!/bin/sed -rf
s/.*/\U&/
s/$/\nA.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-.O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-..-Y-.--Z--../
:a
s/([A-Z])([^\n]*\n.*\1([-.]+))/\3 \2/
ta
s/\n.*//

Posted in Uncategorized | Leave a comment

Triangle

Calculate area and perimeter of any triangle

#!/usr/bin/python3
import sys, math
a, b, c = map(float, sys.argv[1:])
if a + b <= c or a + c <= b or b + c <= a:
    print("Error: not a valid triangle")
    sys.exit(1)
peri = a + b + c
area = math.sqrt((a + b + c) *
                 (a + b - c) *
                 (a - b + c) *
                 (-a + b + c)) / 4
print("Perimeter =", peri)
print("Area =", area)
Posted in Uncategorized | Leave a comment

Vidir

Vidir (part of Debian’s moreutils) lets me edit the names of files in a directory in vim as though the directory was just a file, which it really is.

 

Posted in Uncategorized | Leave a comment