Skip to content

Instantly share code, notes, and snippets.

@ericpardee
Forked from varenc/pet-snippet.toml
Created June 22, 2022 20:35
Show Gist options
  • Save ericpardee/b68b67fc1f245bb89d657e3c43fe18b2 to your computer and use it in GitHub Desktop.
Save ericpardee/b68b67fc1f245bb89d657e3c43fe18b2 to your computer and use it in GitHub Desktop.
description
[[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 [email protected]:/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 = "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 [email protected] '/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.17-18\""
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"
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 [email protected] \"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\": [ \"[email protected]\", \"[email protected]\", \"[email protected]\", \"[email protected]\" ] }, \"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:[email protected][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"
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 [email protected] -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. 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 [email protected] '/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][email protected]: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 | guniq --repeated -c --check-chars=10 | less"
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 closed caption subtitles for a .ts stream/hls stream. 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; # 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/[email protected]/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,[email protected]: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,[email protected]: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/ [email protected]:~/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 --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 --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 = "echo video: $(( ($(ffmpeg -i tmp.mkv -c copy -t 60 -f null - 2>&1 | grep --color=no \"muxing overhead\" | hck -d \"(:|kB)\" -f 2) / 60))) kB/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][email protected]: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 = "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/k_dz3dy75c/${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/k_dz3dy75c/${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 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/[email protected]/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=\"[email protected]\"; ccs=(\"[email protected]\" \"[email protected]\"); 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 = ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment