RSSAmplifier

Blog

Karl Tarvas

adb685c6.karltarvascom.pages.devRSS feed ↗73 posts

Latest posts

Discord bot text to speech with Piper

Piper is a fast TTS engine that’s performant enough to run on the cheapest Hetzner VPS.
It comes with a wide array of available voices offering a good selection of size and speed tradeoffs. 
 Conveniently, it also ships with a web server, so you can load the model once and then get TTS responses with low latency. This makes it perfect for using it as a TTS server for Discord bots.

macOS: Hide users list when the screen is locked

By default, macOS shows a list of local users when you lock the screen, even if the boot login screen is set to name and password only (System Preferences → Lock Screen → Login window shows: Name and password). To hide the list of users and only show the currently logged in user, you can: 
 sudo defaults write /Library/Preferences/com.apple.loginwindow HideLocalUsers -bool TRUE
 To revert,…

macOS: Remap a key

You can use hidutil to remap keys in macOS without using a third party application. 
 List current mappings, will return (null) if no mappings are present: 
 $ hidutil property --get 'UserKeyMapping' 
 ( null ) 
 Set a mapping, in this case, make Caps Lock ( 0x39 ) work as F24 ( 0x73 ) instead: 
 $ hidutil property --set '{'UserKeyMapping':
…

Typescript: Convert snake_case string type to PascalCase string type

Even though the string type manipulation utilities you get out of the box with Typescript are rather limited, using Typescript’s most confusing feature, the infer keyword , you can push conversions between string types quite a lot further. 
 The below snippet converts string_case string types to PascalCase string types. 
 type InputType = 'foo_bar_tea' ; 
 
 type…

How to call a C/C++ function from Node

A straightforward way to call C/C++ code from Node is to use node-gyp to build a Node addon . Node kindly provides a hello world addon demo which we’ll roughly follow below. 
 Firstly you’ll need to install node-gyp . When doing the initial setup, make sure you have a compatible version of Python configured . Next you’ll need to provide a binding.gyp , this file tells…

Git: Be very verbose about cloning

If you’re ever struggling to figure out why cloning a repository fails beyond the usual suspects, the following setup may be handy for you. GIT_TRACE turns general tracing on, GIT_TRACE_PACKET enables packet-level tracing for network operations, GIT_CURL_VERBOSE is equivalent to doing curl -v , and GIT_SSH_COMMAND with -vvv is pretty self explanatory. 
 export GIT_TRACE = 1 
 export…

Protecting your iPhone against shoulder surfing password theft

Edited {{ “2023-04-19” | date_to_long_string: “ordinal” }} : There is currently no known way to defend against this attack. 
 The Wall Street Journal recently covered a low-tech theft scheme for stealing money from iPhone users that’s quickly gaining popularity. 
 The basic premise of the theft works like this: 
 
 The victim’s iPhone passcode is…

Git: Get local branches with no remote

If you often jump between branches and sometimes lose track of which you have and haven’t pushed to the remote yet, it might be handy to get all local branches with no remote : 
 git branch --format '%(refname:short) %(upstream)' | awk '{if (!$2) print $1;}' 
 To sort the whole shebang recently modified branches first, you can add --sort=-committerdate 
 git branch --format…

Allen Pike: Humans Need Play

Recommended reading: “Humans Need Play” by Allen Pike

Cipollino salad

This is a salad my mom used to make when I was young and to date I still love it to bits. I’d wager it isn’t widely known by that name, but the name is pretty self explanatory. 
 For roughly four people, you’ll need: 
 
 three large onions, the sharper the better 
 500g of Chinese cabbage 
 400g of mayo 
 200g of sour cream, watery varieties work better…

Formik custom input not submitting on enter

When using custom components with Formik , a common problem to run into is some native form events breaking. One obvious symptom is the form not triggering a submit when you press enter in an input field, but there are others. 
 The problem will arise if you incorrectly pass all props straight through to the custom component. As demonstrated in the docs above, you must remove the form props…

<code>react-router</code>: Persist location state

Out of the box, single-page applications built with react-router don&rsquo;t persist data when navigating back and forward in the browser history. While this may be desirable at times, most of the time it greatly hurts the usability of the application and makes it feel clunky compared to regular web pages. &#xA; To make your application persists its state when navigating back and forward, you can…

macOS: Disable charger plug in sound

By default, macOS does a small chiming sound whenever you plug the charger in. If you often have to use your laptop in environments that call for silence, you may want to turn it off. &#xA; defaults write com.apple.PowerChime ChimeOnNoHardware -bool true && killall PowerChime&#xA; To reenable it, you can flip the boolean value and run the same snippet.

Git: Get a patch between two branches

Get a patch from the diff between master and foo : &#xA; git diff --no-color --binary master foo > /tmp/patch&#xA; --no-color ensures the diff is valid to apply if you have automatic coloring on, --binary ensures binary files are handled correctly as well. &#xA; To later apply the patch: &#xA; git apply /tmp/patch&#xA;

What is Babel?

Note: This is a response to this blog post by Julia Evans . &#xA; Babel is a common part of many frontend build pipelines. But what is it, and what would you use it for? To answer that question, let&rsquo;s first take a step back and talk about web browsers and Javascript. &#xA; Modern Javascript has learned many tricks in the recent years (such as nullish coalescing , template literals , default…

Git: Use <code>--color-words</code> for diff by default

Git supports showing colored diffs inline by the --color-words flag: &#xA; $ git diff --color-words&#xA; This is often easier to follow than the standard plus-minus format. To make this the default you can: &#xA; $ git config --global color.diff always&#xA; Which will result in the following in your gitconfig: &#xA; [ color] &#xA; &#x9; diff = always &#xA;

AppleScript: Get connected VPN names from Tunnelblick

Tunnelblick is the de facto OpenVPN client for macOS. Amongst other things, it conveniently supports AppleScript which means you can easily use it with Xbar : &#xA; #!/usr/bin/env osascript&#xA; &#xA; tell application 'Tunnelblick' &#xA; get name of configurations where state = 'CONNECTED' &#xA; end tell&#xA;

Bash: Using <code>flock</code> to ensure parallel scripts perform an action only once

Consider two or more shell scripts that may be run either by themselves or in parallel, but all rely on a specific setup step that isn&rsquo;t parallelizable. This may be a network request, a non-idempotent database write, or something else similar. &#xA; One easy way to ensure that this action is performed only once in the above setup is to use flock , a simple lock management utility for shell…

<code>browserslist</code> default values

If you use @babel/preset-env or simply browserslist by itself without configuration it falls back to the default configuration : &#xA; > 0.5%, last 2 versions, Firefox ESR, not dead&#xA; To see what this evaluates to you can run npx browserslist defaults , as of writing it evaluates to the following list: &#xA; and_chr 78&#xA; and_ff 68&#xA; and_qq 1.2&#xA; and_uc 12.12&#xA; android 76&#xA; baidu…

Japt: Playing with primes

Unlike some golfing languages, Japt doesn&rsquo;t have too many tools to play around with prime numbers. The below patterns come up fairly frequently and may be of help. &#xA; Get the first A prime numbers: &#xA; È j } jA &#xA; jA // Get the first A positive integers that return true&#xA; È } // when run through a function that&#xA; j // checks whether the number is prime.&#xA; Similarly, get the…

Typescript <code>Array.filter(Boolean)</code>

Out of the box, Typescript doesn&rsquo;t play well with Array.filter(Boolean) . There&rsquo;s a lot of history to this issue and it hasn&rsquo;t fully been fixed yet. In the below snippet, the returned type from the filter should be string[] , but instead it&rsquo;s (string | null | undefined)[] . &#xA; const foo : ( string | null | undefined )[] = []; &#xA; const bar : string [] = foo . filter (…

<code>eslint-plugin-flowtype-errors</code> keeps spawning and killing <code>flow</code> processes

Running into this problem, you may notice one of two possible symptoms when running lint: either numerous flow processes are spawned and killed constantly, or the lint fails with the below error. &#xA; Flow returned an error: Out of retries, exiting! (code: 7)&#xA; To debug the issue you may run flow check by itself, but the same problem appears: the server is spawned, then killed and respawn over…

<code>@testing-library/user-event</code>&#39;s <code>type()</code> is slow

Testing Library is the current recommended way to unit test React code. By itself it works great and does a lot of the heavy lifting for you. Its sibling library @testing-library/user-event which can be used to trigger click events, typing etc is still a bit green though. &#xA; The type() command is great for simulating user input letter-by-letter, however it has some issues: without a delay, it…

Typescript: Allow any type except specific values

Typescript doesn&rsquo;t have a simple type to describe the relation &ldquo;allow any type except the string literals "foo" and "bar" &rdquo;. However, a small generic interjeciton type will enable Typescript to understand what you mean: &#xA; type Disallowed = 'foo' | 'bar' ; &#xA; type Input < T > = T & ( T extends Disallowed ? never : T ); &#xA; &#xA; // Any input is valid except for the string…

Japt: Count overlapping substrings

Finding the number of overlapping needles in a haystack in Japt is slightly verbose, clocking in at 12 bytes , but still a fun fiddling exercise for a change. &#xA; ðV // Get all indices of needle in the input.&#xA; äÏ - X < Vl &#xA; ä // For every consecutive pair of indices&#xA; Ï - X // check whether their distance&#xA; < Vl // is smaller than the needle length, e.g. whether they overlap.&#xA;…

Annotating legacy jQuery plugins with Typescript

Annotating legacy jQuery with Typescript can be a pain. Many old plugins don&rsquo;t have type definitions available, and the official types only get you so far on their own. &#xA; Instead of littering your code base with separate .d.ts definition files, it can be very convenient to annotate the types inline in the component file itself. &#xA;The following examples cover most common use cases:…

Typescript generics in JSX

Passing type variables to Typescript generics is somewhat clunky in JSX, but still handy in certain cases. &#xA; Given a generic component: &#xA; export default function GenericComponent < T >() { ... } &#xA; You can annotate the type in JSX as follows: &#xA; < GenericComponent < Type > ...props /> &#xA;

Typescript 4.1: Template literal types, computed property names, and more

Typescript 4.1 adds support for template literal types . This, along with the new utility types, unlocks computed property names, simple getter-setter interfaces and more. &#xA; type Foo = 'a' | 'b' | 'c' ; &#xA; // Bar = 'a-template' | 'b-template' | 'c-template'&#xA; type Bar = ` ${ Foo } -template` ; &#xA; In addition, a number of new utility types have been introduced: &#xA; type A = Uppercase…

Javascript: case sensitive string compare

Getting case sensitive string compare in Javascript isn&rsquo;t as trivial as it may seem at first : &#xA; // Returns ['Action', 'activity', 'alpha'],&#xA; // although ['activity', 'alpha', 'Action'] is expected instead&#xA; [ 'alpha' , 'Action' , 'activity' ]. sort (( a , b ) => { &#xA; return a . localeCompare ( b , { sensitivity : 'case' }); &#xA; }); &#xA; The jury is still out on wheter this…

React & Typescript: Using <code>React.Children.toArray()</code> with <code>React.cloneElement()</code>

Trying to clone props children when using React with Typescript, you may run into the following type error: Type 'string' is not assignable to type ReactElement... . &#xA; React . Children . toArray ( props . children ) &#xA; . map ( child => React . cloneElement ( child )); &#xA; The problem is that ReactChild includes string | number , which is not a valid clone target. &#xA; To solve the issue,…

Bash: Using a default value with <abbr title=&#34;dollar sign asterisk&#34;><code>$*</code></abbr>

In Bash, $* gives you the IFS expansion of all positional parameters , such as $1 $2 $3 etc.&#xA;This can be super handy when dealing with inline helper functions , but the use cases are too many to count. &#xA; Assigning a fallback default value uses the same syntax as regular variables do , but the syntax would make you look twice the first time you saw it: &#xA; # Use $1 $2 $3 etc, or 'foo' if…

Javascript <code>Boolean.compare()</code>

Javascript doesn&rsquo;t have a builtin that&rsquo;s comparable to Java&rsquo;s Boolean.compare() . In fact, the Boolean class has nearly nothing in it, save the constructor, toString() and valueOf() . &#xA; The functionality can be replicated using the Number constructor . &#xA; function booleanCompare ( a : boolean , b : boolean ) { &#xA; return Number ( a ) - Number ( b ); &#xA; } &#xA;

Github Actions: cache <code>yarn install</code>

Edited 2021-03-04 : Upgraded actions/setup-node to version 2. &#xA; Caching dependencies installed by Yarn in Github Actions is fairly straightforward, but there are a few small gotchas to get right: &#xA; &#xA; Caching node_modules directly isn&rsquo;t efficient, using Yarn&rsquo;s built-in cache system is both faster and takes up less space. &#xA; Using --prefer-offline ensures your cache is…

<code>osc</code> cheatsheet for OBS

Open Build Service , OBS for short, uses osc as its CLI interface. osc is an SVN-like version control system with a good overview and a starter configuration guide on the openSUSE wiki . &#xA;On macOS you can install it via Homebrew . &#xA; $ brew install osc&#xA; To create a branch of a package, similar to a feature branch in Git: &#xA; $ osc branch < source project> <package>&#xA; Check out your…

Using AMD modules in Stack Overflow snippets

If you&rsquo;re answering a question on Stack Overflow and want to use a library in the code snippet that only supports AMD, the following small jig may be useful. Exports are added to the global scope so you can use them directly in the sample code. &#xA; < script > &#xA; const define = ( _ , module ) => module (); &#xA; define . amd = true ; &#xA; </ script > &#xA; < script src =…

VirtualBox network modes

As covered in the VirtualBox networking docs , the quickest overview into different networking modes is the following table: &#xA; &#xA; &#xA; &#xA; &#xA; &#xA; VM ↔ VM &#xA; VM → Host &#xA; Host → VM &#xA; VM → Net/LAN &#xA; Net/LAN → VM &#xA; &#xA; &#xA; &#xA; &#xA; Not attached &#xA; - &#xA; - &#xA; - &#xA; - &#xA; - &#xA; &#xA; &#xA; Internal Network &#xA; + &#xA; - &#xA; - &#xA; - &#xA; -…

macOS: App sandboxing via <code>sandbox-exec</code>

It isn&rsquo;t widely advertised, but macOS ships with a standalone sandboxing utility out of the box: sandbox-exec . While the very short manpage says the utility has been marked deprecated, and for quite a few major releases now, it&rsquo;s used heavily by internal systems so it&rsquo;s unlikely go away anytime soon. &#xA; Sandbox configurations are writen in a subset of Scheme. A minimal useful…

Cypress: <code>cy.readFile()</code> vs <code>cy.fixture()</code>

At first glance, cy.readFile() and cy.fixture() seem fairly similar, both read files asynchronously and wrap them as Cypress usually does. &#xA;The main difference is conceptual, but there are some practical considerations as well. &#xA; Fixtures are meant for files that are used only for your tests, e.g. placeholder test data, sample responses and so forth. In other terms, fixtures are files that…

macOS: Safely installing Microsoft Intune

Microsoft Intune is a remote device management and supervision solution employed by some corporations. &#xA;The below instructions are written assuming macOS Catalina and APFS , the process is fairly similar for other setups. &#xA; &#xA; If your daily driver disk isn&rsquo;t encrypted, go to System Preferences → Security & Privacy → FileVault and turn it on &#xA; Boot into Recovery Mode by holding…

macOS: pip install M2Crypto

Out of the box, trying to install M2Crypto on macOS will fail with one of two common scenarios on building. &#xA;Either you&rsquo;ll get OpenSSL errors , in case you haven&rsquo;t set up a newer version than the system one: &#xA; Error: Unable to find 'openssl/opensslv.h'&#xA; Or you&rsquo;ll get a bunch of clang errors : &#xA; Error: invalid argument type 'void' to unary expression&#xA; All of…

macOS: <code>bsdcpio</code> vs GNU <code>cpio</code>

MacOS ships with cpio out of the box, however it&rsquo;s worth noting it&rsquo;s bsdcpio , not the GNU cpio . &#xA;While most of the functionality is identical, the set of available flags is inconsistent between the two. &#xA; If you need GNU cpio on macOS, you can install it via Homebrew : &#xA; $ brew install cpio&#xA; You&rsquo;ll need to add it to your $PATH in .bashrc or similar to use it:…

Bash: Pipe command output to stdout and file

If you need both stdout and stderr in a file for logging or debugging purposes, while also wanting to monitor the output of a command, you can use a pipe control operator along with tee : &#xA; $ foo |& tee out.log&#xA;

VBoxManage: Start and stop headless VMs

Start a virtual machine in headless mode: &#xA; $ VBoxManage startvm <VM name or GUID> --type headless&#xA; Save the machine state and then stop it: &#xA; VBoxManage controlvm <VM name or GUID> savestate&#xA; See the VBoxManage manual for more examples.

Echo into a file with root permissions

Simply prepending sudo to echo will fail since the redirection is executed by the shell, not the command you run. &#xA; $ sudo echo 'foo' >> /etc/bar&#xA; bash: /etc/bar: Permission denied&#xA; Shortly, the above is running echo as root, but >> will be run by the surrounding shell. &#xA;To overcome this, you can use tee : &#xA; $ echo 'foo' | sudo tee -a /etc/bar/&#xA; To overwrite the file,…

macOS Catalina: VirtualBox crashes on Linux VM boot

Whether you&rsquo;re setting up a fresh Linux VM in VirtualBox on macOS Catalina (10.15.6), or migrating a VM over from an older macOS version, you can be in for a nasty surprise — once the VM boots, VirtualBox crashes with a mere stack trace. &#xA;Personally I tested this with openSUSE, but since there&rsquo;s similar reports from Ubuntu , this seems a fairly common problem. &#xA; The error and…

Git: Revert file to master

The same approach applies to any branch, but reverting a file to its state in master seems to come up most often. &#xA;Firstly, in case you need to list which files have changed between your active branch and master: &#xA; git diff --name-status master&#xA; Then to revert the file to its state in master: &#xA; git checkout master path/to/file&#xA; At this point, the file will already be staged, so…

macOS: Run script on startup

MacOS uses launchd as the daemon for running services and other daemons. &#xA; To run a script or a few on startup, you can interface with launchd by writing a corresponding plist file . In my case, I want to run networksetup to connect to a specific VPN on startup, but to only run it once so that I can switch to other ones later. &#xA; Essentially, whenever my computer starts up, I want to run

Git: Autosign commits

After generating a GPG key and adding it to your Github account , automatically signing your commits is very straightforward. &#xA; &#xA; First, find your key ID via &#xA; &#xA; gpg --list-secret-keys --keyid-format LONG&#xA; &#xA; Then, configure Git use the said key globally &#xA; &#xA; git config --global user.signingkey KEY_ID&#xA; &#xA; Check that user.email matches the one in your GPG key,…

macOS: Switching between OpenVPN and NextDNS automatically

Since macOS doesn&rsquo;t support OpenVPN out of the box, the easiest solution is to use Tunnelblick as your client. Alternatively, there&rsquo;s CLI builds for OpenVPN available on Homebrew as well. &#xA; Regardless of your client of choice though, OpenVPN and NextDNS don&rsquo;t play well together without a little help. A generic setup that supports both is as follows: &#xA; &#xA; Install the…

App recommendation: Next Meeting

Next Meeting is a handy macOS utilty that puts your next calendar event in the menubar. &#xA; &#xA; It uses native calendar integration so whatever you&rsquo;ve already set up in the Calendar app will be available out of the box. &#xA; For those looking for more customization, BitBar is a good alternative, but for ease-of-use out of the box, Next Meeting is hard to beat.