Cmdlog

List bash commands by frequency

#!/usr/bin/env python3
import os
history_file = os.path.expanduser("~/.bash_history")
counts = {}
with open(history_file, "r", errors="ignore") as f:
    for line in f:
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        cmdline = line.split("|", 1)[0].strip()
        parts = cmdline.split()
        if not parts:
            continue
        cmd = parts[1] if parts[0] == "sudo" and len(parts) > 1 else parts[0]

        counts[cmd] = counts.get(cmd, 0) + 1
sorted_cmds = sorted(counts.items(), key=lambda x: x[1], reverse=True)
for cmd, n in sorted_cmds:
    print(f"{n} {cmd:20}")

Posted in Uncategorized | Leave a comment

Alpha

#!/usr/bin/env python3
"""
Argo Alpha-AUXMOD Performance Calculator

Models the docked Alpha capsule and Auxiliary Module in orbit.

Calculates:
- Combined operating and dry mass
- Shared AUXMOD propellant budget
- Ideal delta-v available for maneuvering and docking
- Theoretical peak solar-array output
- Comparison with the specified 7 kW electrical output

Assumptions:
- Alpha mass remains constant at 5200 kg.
- AUXMOD RCS and retro-fire systems share one propellant supply.
- All AUXMOD operating mass above dry mass is treated as propellant.
- Hypergolic specific impulse is 314 seconds.
- Solar-array output uses 35% cell efficiency and standard
  solar irradiance at Earth's orbital distance.
"""

import math

# --------------------------------------------------
# Physical constants
# --------------------------------------------------

G0 = 9.80665                  # Standard gravity (m/s^2)
SOLAR_IRRADIANCE = 1361.0     # Solar irradiance (W/m^2)

# --------------------------------------------------
# Alpha capsule
# --------------------------------------------------

ALPHA_MASS = 5200.0           # Constant operating mass (kg)
ALPHA_DIAMETER = 3.6           # Diameter (m)
ALPHA_HEIGHT = 2.0             # Overall height (m)

# --------------------------------------------------
# Auxiliary Module
# --------------------------------------------------

AUXMOD_WET_MASS = 2850.0      # Operating mass (kg)
AUXMOD_DRY_MASS = 1640.0      # Dry mass (kg)
AUXMOD_ISP = 314.0            # Hypergolic specific impulse (s)

# Shared RCS and retro-fire propellant budget
AUXMOD_PROPELLANT = (
    AUXMOD_WET_MASS - AUXMOD_DRY_MASS
)

# --------------------------------------------------
# Solar arrays
# --------------------------------------------------

SOLAR_ARRAY_AREA = 18.0       # Total deployed area (m^2)
SOLAR_CELL_EFFICIENCY = 0.35  # 35 percent
RATED_ELECTRICAL_OUTPUT = 7000.0  # Previously specified output (W)

# --------------------------------------------------
# Calculations
# --------------------------------------------------

def ideal_delta_v(initial_mass, final_mass, isp):
    """Calculate ideal delta-v using the Tsiolkovsky rocket equation."""
    if initial_mass <= final_mass:
        return 0.0

    return isp * G0 * math.log(initial_mass / final_mass)


def solar_peak_power(area, efficiency, irradiance):
    """Calculate ideal solar-array electrical output in watts."""
    return area * efficiency * irradiance


def main():
    stack_wet_mass = ALPHA_MASS + AUXMOD_WET_MASS
    stack_dry_mass = ALPHA_MASS + AUXMOD_DRY_MASS

    print("=" * 54)
    print(" ARGO ALPHA-AUXMOD PERFORMANCE")
    print("=" * 54)

    print("\nSPACECRAFT MASS")
    print(f"Alpha capsule:             {ALPHA_MASS:10,.1f} kg")
    print(f"AUXMOD operating mass:     {AUXMOD_WET_MASS:10,.1f} kg")
    print(f"AUXMOD dry mass:           {AUXMOD_DRY_MASS:10,.1f} kg")
    print(f"AUXMOD propellant budget:  {AUXMOD_PROPELLANT:10,.1f} kg")
    print(f"Combined operating mass:   {stack_wet_mass:10,.1f} kg")
    print(f"Combined dry mass:         {stack_dry_mass:10,.1f} kg")

    print("\nPROPULSION AND MANEUVERING")

    print(f"Hypergolic Isp:            {AUXMOD_ISP:10.1f} s")

    print(
        "\nHow much propellant (kg) must be reserved for "
        "retro-fire operations?"
    )
    print(
        f"Enter a value from 0 to {AUXMOD_PROPELLANT:.1f}. "
        "Press Enter for 0 kg (optimistic upper bound)."
    )

    entry = input("Retro-fire reserve (kg): ").strip()

    if entry == "":
        retro_reserve = 0.0
    else:
        try:
            retro_reserve = float(entry)
        except ValueError:
            print("Invalid input. Please enter a numeric mass.")
            return

    if not 0.0 <= retro_reserve <= AUXMOD_PROPELLANT:
        print(
            f"Reserve must be between 0 and "
            f"{AUXMOD_PROPELLANT:.1f} kg."
        )
        return

    docking_propellant = AUXMOD_PROPELLANT - retro_reserve

    # Propellant reserved for retro-fire remains aboard.
    final_mass = stack_wet_mass - docking_propellant

    docking_delta_v = ideal_delta_v(
        stack_wet_mass,
        final_mass,
        AUXMOD_ISP
    )

    maximum_delta_v = ideal_delta_v(
        stack_wet_mass,
        stack_dry_mass,
        AUXMOD_ISP
    )

    print(f"\nRetro-fire reserve:       {retro_reserve:10,.1f} kg")
    print(f"Propellant for maneuvering:{docking_propellant:9,.1f} kg")
    print(f"Mass before maneuver:     {stack_wet_mass:10,.1f} kg")
    print(f"Mass after maneuver:      {final_mass:10,.1f} kg")
    print(f"Ideal docking Δv budget:  {docking_delta_v:10,.1f} m/s")
    print(f"Absolute ideal Δv maximum:{maximum_delta_v:10,.1f} m/s")

def aligned_number(value, decimals=1, width=10, comma=True):
    formatted = f"{value:,.{decimals}f}" if comma else f"{value:.{decimals}f}"
    integer, fraction = formatted.split(".")
    return f"{integer:>{width - decimals - 1}}.{fraction}"

    print("\nSOLAR POWER")

    theoretical_power = solar_peak_power(
        SOLAR_ARRAY_AREA,
        SOLAR_CELL_EFFICIENCY,
        SOLAR_IRRADIANCE
    )


    print(f"Deployed array area:      {aligned_number(SOLAR_ARRAY_AREA)} m^2")
    print(f"Cell efficiency:          {aligned_number(SOLAR_CELL_EFFICIENCY * 100)}%")
    print(f"Solar irradiance:         {aligned_number(SOLAR_IRRADIANCE)} W/m^2")
    print(f"Theoretical peak output:  {aligned_number(theoretical_power / 1000, 2)} kW")
    print(f"Specified system output:  {aligned_number(RATED_ELECTRICAL_OUTPUT / 1000, 2)} kW")

    derating = 1.0 - RATED_ELECTRICAL_OUTPUT / theoretical_power

    print(f"Implied power derating:   {aligned_number(derating * 100)}%")


    print("\nNOTES")
    print(
        "- Delta-v is ideal: gravity, attitude-control, and other "
        "operational losses are not included."
    )
    print(
        "- The maneuvering result assumes all unreserved mass "
        "allowance is usable propellant."
    )
    print(
        "- Actual electrical output depends on array temperature, "
        "illumination angle, degradation, and power-system losses."
    )
    print("=" * 54)


if __name__ == "__main__":
    main()
======================================================
 ARGO ALPHA-AUXMOD PERFORMANCE
======================================================

SPACECRAFT MASS
Alpha capsule:                5,200.0 kg
AUXMOD operating mass:        2,850.0 kg
AUXMOD dry mass:              1,640.0 kg
AUXMOD propellant budget:     1,210.0 kg
Combined operating mass:      8,050.0 kg
Combined dry mass:            6,840.0 kg

PROPULSION AND MANEUVERING
Hypergolic Isp:                 314.0 s

How much propellant (kg) must be reserved for retro-fire operations?
Enter a value from 0 to 1210.0. Press Enter for 0 kg (optimistic upper bound).
Retro-fire reserve (kg): 300

Retro-fire reserve:            300.0 kg
Propellant for maneuvering:    910.0 kg
Mass before maneuver:        8,050.0 kg
Mass after maneuver:         7,140.0 kg
Ideal docking Δv budget:       369.4 m/s
Absolute ideal Δv maximum:     501.6 m/s
Posted in Uncategorized | Leave a comment

Rtf2txt

#!/usr/bin/env python3
import sys
import re
import codecs
SKIP_DESTINATIONS = {
    "fonttbl", "colortbl", "stylesheet", "info", "pict",
    "object", "objdata", "header", "headerl", "headerr",
    "footer", "footerl", "footerr", "filetbl", "listtable",
    "listoverridetable", "generator", "xmlnstbl", "datastore",
    "themedata", "colorschememapping", "latentstyles",
    "rsidtbl", "revtbl", "annotation", "atnauthor",
    "atnid", "atnref", "atntime", "aftncn", "aftnsep",
    "aftnsepc", "ftncn", "ftnsep", "ftnsepc",
    "object", "nonshppict", "shppict", "do", "formfield",
}
SPECIAL_CHARS = {
    "\\": "\\",
    "{": "{",
    "}": "}",
    "~": "\u00a0",      
    "_": "\u2011",       
    "-": "",            
}

SPECIAL_WORDS = {
    "emdash": "\u2014",
    "endash": "\u2013",
    "emspace": "\u2003",
    "enspace": "\u2002",
    "qmspace": "\u2005",
    "bullet": "\u2022",
    "lquote": "\u2018",
    "rquote": "\u2019",
    "ldblquote": "\u201c",
    "rdblquote": "\u201d",
    "zwj": "\u200d",
    "zwnj": "\u200c",
}


def convert(data):
    text = data.decode("latin-1")
    state = {
        "skip": False,
        "uc": 1,
        "codepage": "cp1252",
        "ignorable": False,
    }
    stack = []

    output = []
    i = 0
    n = len(text)

    def emit(s):
        if not state["skip"]:
            output.append(s)

    def decode_byte(value):
        try:
            return bytes([value]).decode(
                state["codepage"], errors="replace"
            )
        except LookupError:
            return bytes([value]).decode("cp1252", errors="replace")

    def decode_raw(s):
        """Decode raw RTF text bytes using the current code page."""
        if state["skip"]:
            return

        raw = bytes(ord(c) for c in s)
        try:
            output.append(
                raw.decode(state["codepage"], errors="replace")
            )
        except LookupError:
            output.append(raw.decode("cp1252", errors="replace"))

    while i < n:
        c = text[i]

        if c == "{":
            stack.append(state.copy())
            state = state.copy()
            state["ignorable"] = False
            i += 1
            continue

        if c == "}":
            if stack:
                state = stack.pop()
            i += 1
            continue

        if c != "\\":
            if c == "\r" or c == "\n":
                i += 1
                continue

            if c == "\t":
                emit("\t")
                i += 1
                continue

            decode_raw(c)
            i += 1
            continue

        i += 1

        if i >= n:
            break

        c = text[i]

        if c == "'":
            if i + 2 < n:
                try:
                    value = int(text[i + 1:i + 3], 16)
                    emit(decode_byte(value))
                    i += 3
                    continue
                except ValueError:
                    pass

            i += 1
            continue

        if not c.isalpha():
            i += 1

            if c == "*":
                state["ignorable"] = True
                continue

            if c in SPECIAL_CHARS:
                emit(SPECIAL_CHARS[c])
                continue

            if c == "~":
                emit("\u00a0")
                continue

            if c == "\n" or c == "\r":
                continue

            if c == ":":
                continue

            if c == "|":
                emit("|")
                continue

            if c == "\\":
                emit("\\")
                continue

            continue

        start = i
        while i < n and text[i].isalpha():
            i += 1

        word = text[start:i]

        sign = 1
        if i < n and text[i] == "-":
            sign = -1
            i += 1

        num_start = i
        while i < n and text[i].isdigit():
            i += 1

        arg = None
        if i > num_start:
            arg = sign * int(text[num_start:i])

        if i < n and text[i] == " ":
            i += 1

        if state["ignorable"]:
            state["ignorable"] = False
            state["skip"] = True
            continue

        if word in SKIP_DESTINATIONS:
            state["skip"] = True
            continue

        if word == "ansicpg" and arg is not None:
            state["codepage"] = f"cp{arg}"
            continue

        if word == "uc" and arg is not None:
            state["uc"] = max(0, arg)
            continue

        if word == "u" and arg is not None:
            value = arg if arg >= 0 else arg + 65536
            emit(chr(value))

            fallback = state["uc"]
            while fallback > 0 and i < n:
                if text[i] == "\\":
                    if i + 1 < n and text[i + 1] == "'":
                        i = min(i + 4, n)
                    elif i + 1 < n and not text[i + 1].isalpha():
                        i += 2
                    else:
                        break
                elif text[i] in "{}":
                    break
                else:
                    i += 1

                fallback -= 1

            continue

        if word in ("par", "row"):
            emit("\n")
            continue

        if word == "line":
            emit("\n")
            continue

        if word == "tab":
            emit("\t")
            continue

        if word == "page":
            emit("\n")
            continue

        if word == "sect":
            emit("\n")
            continue

        if word in SPECIAL_WORDS:
            emit(SPECIAL_WORDS[word])
            continue

        if word == "emdash":
            emit("\u2014")
            continue

        if word == "enspace":
            emit("\u2002")
            continue

        if word == "ansi":
            state["codepage"] = "cp1252"
            continue

        if word == "mac":
            state["codepage"] = "mac_roman"
            continue

        if word == "pc":
            state["codepage"] = "cp437"
            continue

        if word == "pca":
            state["codepage"] = "cp850"
            continue

    result = "".join(output)
    result = result.replace("\r\n", "\n").replace("\r", "\n")

    result = re.sub(r"[ \t]+\n", "\n", result)

    result = re.sub(r"\n{4,}", "\n\n\n", result)

    return result


def main():
    data = sys.stdin.buffer.read()
    result = convert(data)
    sys.stdout.write(result)


if __name__ == "__main__":
    main()
#!/bin/bash
find . -type f -iname '*.rtf' -print0 |
while IFS= read -r -d  file; do
    rtf2txt < "$file" > "${file%.*}.txt"
done
Posted in Uncategorized | Leave a comment

Quadratic

#!/usr/bin/env python3
import math,sys
a,b,c=map(float,sys.argv[1:])
d=b*b-4*a*c
if d>=0:x1=(-b+math.sqrt(d))/(2*a);x2=(-b-math.sqrt(d))/(2*a)
else:r=-b/(2*a);i=math.sqrt(-d)/(2*a);x1,x2=complex(r,i),complex(r,-i)
print("The function has","two real roots: {} and {}".format(x1,x2)if d>0 else
"one double root: {}".format(x1)if d==0 else
"two complex roots: {} and {}".format(x1,x2))
Posted in Uncategorized | Leave a comment

Trig

Trig functions

#! /usr/bin/bc -lq
define t(x) {
        return s(x) / c(x)
}
define y(y) {
        if (y == -1) return -2 * a(1)  /* -pi/2 */
        if (y == 1) return 2 * a(1)    /* pi/2 */
        return a(y / sqrt(1 - y * y))
}
define x(x) {
        auto angle
        if (x == 0) return 2 * a(1)    /* pi/2 */
        angle = a(sqrt(1 - x * x) / x)
        if (x < 0) return angle + 4 * a(1)
        return angle
}
p = 4 * a(1)  /* pi */
d = p / 180   /* one degree in radians */

print "Using radians:\n"
"sin(-pi / 6) = "; s(-p / 6)
"cos(3 * pi / 4) = "; c(3 * p / 4)
"tan(pi / 3) = "; t(p / 3)
"asin(-1 / 2) = "; y(-1 / 2)
"acos(-sqrt(2) / 2) = "; x(-sqrt(2) / 2)
"atan(sqrt(3)) = "; a(sqrt(3))
print "\n\nUsing degrees:\n"
"sin(-30) = "; s(-30 * d)
"cos(135) = "; c(135 * d)
"tan(60) = "; t(60 * d)
"asin(-1 / 2) = "; y(-1 / 2) / d
"acos(-sqrt(2) / 2) = "; x(-sqrt(2) / 2) / d
"atan(sqrt(3)) = "; a(sqrt(3)) / d
quit

Posted in Uncategorized | Leave a comment

Pay

#!/usr/bin/env python3
import sys
from num2words import num2words
def spell_number(my_number):
    my_number = my_number.strip()
    if not my_number:
        return ""
    result = num2words(
        float(my_number),
        to="currency",
        currency="USD"
    )
    result = result.replace(",", "")
    result = result.replace(" and ", " ")
    result = result.replace("-", " ")
    result = result.title()
    result = result.replace(" Dollars ", " Dollars And ")
    result = result.replace(" Dollar ", " Dollar And ")
    return result
def main():
    for line in sys.stdin:
        result = spell_number(line)
        if result:
            print(result)

if __name__ == "__main__":
    main()

Posted in Uncategorized | Leave a comment

Ac

Report statistics of uptime

ac -dp –print-year

 

Posted in Uncategorized | Leave a comment

Abundant

#!/usr/bin/python3
import sys; beg,end=int(sys.argv[1]),int(sys.argv[2]);[print(f"{n} is "+("perfect" if (s:=sum(x for x in range(1,1+n//2) if n%x==0))==n else "abundant" if s>n else "deficient")) for n in range(beg,end+1)]

Posted in Uncategorized | Leave a comment

abcde

abcde for Linux in the off-hand chance you still need to rip a CD.

 

Posted in Uncategorized | Leave a comment

Palin

Find all palindromic words in a file

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

Posted in Uncategorized | Leave a comment