Skip to content

Instantly share code, notes, and snippets.

@CTimmerman
Last active April 4, 2024 07:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CTimmerman/ff53a6b72adc2a86382d to your computer and use it in GitHub Desktop.
Save CTimmerman/ff53a6b72adc2a86382d to your computer and use it in GitHub Desktop.
Oneliners, single line scripts.
echo Random maze:
python -c 'exec("""import random\nwhile 1:print(random.choice("\/"),end="")""")'
echo Find recent file changes with Bash. Optional arguments: [path] [max age in minutes] changed
sudo find ${1} -cmin -${2-1} 2>&1 |grep -v /proc/
// Turn table content such as https://meta.wikimedia.org/wiki/Template:List_of_language_names_ordered_by_code into JSON.
let rows = document.querySelectorAll("tr"); let h = {}; for(let row of rows) { let cols = row.innerText.split('\t'); h[cols[0]] = cols[1] }; JSON.stringify(h)
// Get total time of a LinkedIn Learning session, as the many "4m 15s" bits are deceptively short.
let lens = []; for(let slen of document.querySelectorAll('.classroom-toc-item__content>div:nth-child(2)>span')) { let match = slen.innerText.match(/(\d+)?m?\s?(\d+)s/); lens.push(60*match[1] + 1*match[2]) } let total = lens.reduce((a, b) => a + b, 0); let h = Math.floor(total / 3600); total %= 3600; let m = Math.floor(total / 60); let secs = total %= 60; `${h}h ${m}m ${secs}s`
// "1h 17m 26s"
// compound interest calculator inspired by https://www.youtube.com/watch?v=2y3CkSYh5Vg
monthly=653;interest=1.08;raise=1.03;inflation=0.98;years=40;total=0;for(year=0;year<years;++year){total = total * interest + (monthly*12)*(raise*inflation)**year}; total.toLocaleString(navigator.userLanguage, {maximumFractionDigits:2});
// '2,249,867.65'
// Just get a list of coordinate pairs from a string. Needlessly arcane, JS!
const matches = [...line.matchAll(/(\d+),(\d+)/g)].map(e=>e.slice(1))
// ANSI escape color codes. https://developer.chrome.com/docs/devtools/console/format-style/
let h = ''; for (let bg of [40, 41, 42, 43, 44, 45, 46, 47, '48;2;255;155;0', 49, 100, 101, 102, 103, 104, 105, 106, 107]) for (let fg of [30, 31, 32, 33, 34, 35, 36, 37, '38;2;255;155;0', 39, 90, 91, 92, 93, 94, 95, 96, 97]) h += `\x1b[${bg};${fg};1;3m b${bg}f${fg} `; console.log(h)
// Don't be tricked by number (former) vs BigInt (latter)!
0b11111111_11111111_11111111_11111111_11111111_11111111_11111100_00000000.toString(2)
"10000000000000000000000000000000000000000000000000000000000000000"
0b11111111_11111111_11111111_11111111_11111111_11111111_11111100_00000000n.toString(2)
"1111111111111111111111111111111111111111111111111111110000000000"
// For bookmarklets/favelets, see https://gist.github.com/CTimmerman/cb304d55e436dab093aad882e10d4494
# Portscanner for the Python shell. Checks for TightVNC: Returns [5800, 5900] if its default ports responded in time.
from socket import *; setdefaulttimeout(0.05); [p for p in range(5800, 6000) if socket().connect_ex(('127.0.0.1', p)) & 35 != 35]
# Timeout code 35 EAGAIN on Mac https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/intro.2.html
# or 10035 WSAEWOULDBLOCK on Windows https://learn.microsoft.com/en-us/windows/win32/winsock/windows-sockets-error-codes-2
# Windows 11 ports up to 6000:
# 0 Reserved https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
# 135 Microsoft EPMAP (End Point Mapper)
# 137 NetBIOS Name Service
# 445 - Microsoft Directory Services
# 1024 - Trojan? https://www.adminsub.net/tcp-udp-port-finder/1024
# 5040 Windows Deployment Services https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/mt670791(v=ws.11)
# 5357 Network Discovery https://www.speedguide.net/port.php?port=5357
# Replace all braces:
>>> import re; re.sub(r'\((.*?)\)', r'[\1]', '12(34\n567)8(9)', flags=re.DOTALL)
'12[34\n567]8[9]'
# Full Unicode chart in Python 3.8.6 (tags/v3.8.6:db45529, Sep 23 2020, 15:52:53) [MSC v.1927 64 bit (AMD64)] on win32.
>>> with open('unicode.txt', 'wb') as fp: sum(fp.write(bytes(f'{i} {chr(i)} ', 'utf8')) for i in range(int(55296)))
...
539674
# Windows doesn't like 4-digit decimal Unicode entry, so type Alt+NumPlus+hexcode instead of Alt+NumDigits.
>>> with open('unicode_hexcodes.txt', 'wb') as fp: sum(fp.write(bytes(f'{hex(i)[2:]} {chr(i)} ', 'utf8')) for i in range(int(55296)))
...
491120
# Screenshot all screens after 3 seconds to capture tooltip, requires python -m pip install mss
>>> import mss, time; time.sleep(3); mss.mss().shot(mon=-1, output=f'{time.time()}.png')
'1611564586.5624912.png'
# Print ordinal multipliers for a given base and demonstrate that anything can be a oneliner.
>>> base=2; for i in range(3,-4,-1): print(f"{base**i},", end='')
File "<stdin>", line 1
base=2; for i in range(3,-4,-1): print(f"{base**i},", end='')
^
SyntaxError: invalid syntax
>>> base=2; exec("""for i in range(3,-4,-1): print(f"{base**i},", end='')""")
8,4,2,1,0.5,0.25,0.125,>>>
# Show an RGB image for 10 seconds or until keypress. WM input is ignored: https://answers.opencv.org/question/213627/detect-when-the-imshow-window-is-closed-using-x-by-user/
>>> cv2.imshow('test', numpy.ndarray((150, 500, 3), dtype=int).astype(numpy.uint8)); cv2.waitKey(10000); cv2.destroyAllWindows()
rem Show WiFi password
netsh wlan show profile name="MyNetwork" key=clear
rem Fix software BSOD as Administrator. Problems not already fixed by DISM SFC will log in %windir%\logs\cbs\cbs.log
dism /Online /Cleanup-Image /RestoreHealth
sfc /scannow
rem Fix hardware sectors as Administrator (takes hours so run overnight)
chkdsk C: /r
rem End/stop/close buggy program window that covers task manager window and doesn't respond to close from task bar menu.
taskkill /F /IM killingfloor.exe
@CTimmerman
Copy link
Author

CTimmerman commented Mar 27, 2017

Odd, now it returns 35 on timeouts. Probably a Mac thing. Anyway, connect_ex returns 0 on success (port open), 61 on connection refused (port closed), and 49 for invalid port or such (EADDRNOTAVAIL).

@CTimmerman
Copy link
Author

See also bookmarklets.

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