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

Box

Put text in an ASCII art box:

#!/usr/bin/env python3
import sys
print("+" + "-" * 62 + "+")
for line in sys.stdin:
    print(f"| {line.rstrip():<60} |")
print("+" + "-" * 62 + "+")
Posted in Uncategorized | Leave a comment

1 Liners

Print all primes less than 5000:

$ python3 -c 'print([i for i in range(2,5000) if all(i%j for j in range(2,int(i**0.5)+1))])'

Break a GIF into individual frames:

ffmpeg -i taarna.gif frame_%d.jpg

List all the words in a file with no matches in the dictionary:

aspell list < huckfinn.txt

Play a G major chord on ‘guitar’ using the sox package:

play -n synth pl G2 pl B2 pl D3 pl G3 pl D4 pl G4 delay 0 .05 .1 .15 .2 .25 remix - fade 0 4 .1 norm -1

Convert a PDF file to JPEG:

pdftocairo path/to/file.pdf -jpeg

Tally a column of figures in awk:

awk '{sum += $3} END {print "Total:", sum}' tribes

Tell Python to recite the powers of two in English

seq 1 16|while read n;do echo $((2**n));done|python3 -c "import sys,inflect;p=inflect.engine();[print(p.number_to_words(int(x.strip()))) for x in sys.stdin if x.strip()]"

Extract pages from a PDF file:

gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -dFirstPage=34 -dLastPage=34 -sOutputFile=test2.pdf The-Cambridge-Handbook-of-Physics-Formulas.pdf

Display an image without a border:

feh --borderless /home/teresita/Downloads/48773.jpg &

Batch convert HTML to text:

for i in *.html; do lynx --dump "$i" > "${i%%.*}.txt";done

Build a list of words from a file:

cat gettysburg.txt | tr ' ' '\012'|tr '[A-Z]' '[a-z]' |sed "s/punct://g" |sort|uniq

Sort the Holy Bible by verse length with Perl:

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

Batch convert HTML to text:

for i in *.html; do lynx --dump "$i" > "${i%%.*}.txt";done

Use awk to print a count of words ending by letter:

awk 'length > 1{++a[substr(tolower($0), length)]}END{for (k in a) print a[k], k}' words.big | sort -n

Grab a stretch of unicode while inside #vim

:py3 import vim;vim.current.buffer.append(" ".join(chr(i) for i in range(945,970)))

Get a weather forecast at the console:

curl -s -L https curl wttr.in/seattle

Shuffle and rename the files in a directory of images

echo '#!/bin/bash' > files; chmod 744 files; ls -1 | shuf | nl -i1 -s' ' -nrz -w5 | awk '{print "mv " $2 " " $1 ".jpg"}' >> files ; ./files

Build thumbnails with the same basename from a directory of video files using ffmpegthumbnailer and bash:

for oldfile in *.mp4; do filename="${oldfile%.*}"; ffmpegthumbnailer -i "$filename.mp4" -o "$filename.jpg"; done

Calculate parallel resistance (or series capacitance) for any number of discrete components with Python

python3 -c "import sys; print(f'{1/sum(1/float(x) for x in sys.argv[1:]):.2f}')" 1800 2700 3300

 

 

 

 

 

 

Posted in Uncategorized | Leave a comment

Wrap

Reformat standard input to any width

#!/usr/bin/python3
import sys
import textwrap
w=int(sys.argv[1])
for line in sys.stdin:
    print(textwrap.fill(line,width=w))

Posted in Uncategorized | Leave a comment

TOF

Interplanetary mission velocity change and time of flight using Python (example used is outbound leg to Mars):

#!/usr/bin/env python3
import sys
from math import sqrt, pi, radians, sin
muP, muD, r1, rp1, muA, r2, rp2, inc = map(float, sys.argv[1:])
a = (r1 + r2) / 2.0
tof = pi * sqrt(a**3 / muP)
v1 = sqrt(muP / r1)
v2 = sqrt(muP / r2)
vt1 = sqrt(muP * (2.0 / r1 - 1.0 / a))
vt2 = sqrt(muP * (2.0 / r2 - 1.0 / a))
vinf1 = abs(vt1 - v1)
vinf2 = abs(v2 - vt2)
vc1 = sqrt(muD / rp1)
vp1 = sqrt(vinf1**2 + 2.0 * muD / rp1)
dv1 = vp1 - vc1
vc2 = sqrt(muA / rp2)
vp2 = sqrt(vinf2**2 + 2.0 * muA / rp2)
dv2 = vp2 - vc2
plane_speed = min(vt1, vt2)
plane = 2.0 * plane_speed * sin(radians(inc) / 2.0)
print(f"Transfer time   {tof/86400:12.3f}    days")
print(f"Injection Δv       {dv1:12.6f} km/s")
print(f"Capture Δv         {dv2:12.6f} km/s")
print()
print(f"Best case total Δv {dv1+dv2:12.6f} km/s")
print(f"Plane change       {plane  :12.6f} km/s")
print(f"Worst case total Δv{dv1+dv2+plane:12.6f} km/s")

 

Posted in Uncategorized | Leave a comment

GreatCircle

Calculate a great circle route in kilometers:

#!/usr/bin/env python3
import sys
from math import radians, degrees, sin, cos, sqrt, asin
lat1, lon1, lat2, lon2 = map(float, sys.argv[1:5])
dLat = radians(lat2 - lat1)
dLon = radians(lon2 - lon1)
lat1 = radians(lat1)
lat2 = radians(lat2)
a = sin(dLat / 2)**2 + cos(lat1) * cos(lat2) * sin(dLon / 2)**2
c = 2 * asin(sqrt(a))
print(6372.8 * c)

Nashville International Airport (BNA)

  N 36°7.2',   W 86°40.2'     (36.12,   -86.67)          

Los Angeles International Airport (LAX)

  N 33°56.4',  W 118°24.0'    (33.94,  -118.40)

Posted in Uncategorized | Leave a comment

Lagrange

Find barycentric L1 and L2 Lagrange points from normalized mass ratio

#!/usr/bin/env python3
import sys
from scipy.optimize import brentq
R = float(sys.argv[1])
m1 = R / (R + 1.0)
m2 = 1.0 / (R + 1.0)
x1 = -m2
x2 =  m1
def f(x):
    r1 = abs(x - x1)
    r2 = abs(x - x2)
    return (
        x
        - m1 * (x - x1) / r1**3
        - m2 * (x - x2) / r2**3
    )
eps = 1e-12
L1 = brentq(f, x1 + eps, x2 - eps)
L2 = brentq(f, x2 + eps, x2 + 2.0)
r1 = x2 - L1
r2 = L2 - x2
print(f"Primary   : {x1:.12f}")
print(f"Secondary : {x2:.12f}")
print(f"L1        : {L1:.12f}")
print(f"L2        : {L2:.12f}")
print(f"L1 offset : {r1:.12f}")
print(f"L2 offset : {r2:.12f}")

Posted in Uncategorized | Leave a comment