Disable Caps Lock and Num Lock

The only time I ever hit the Caps Lock key is by accident. When I do it messes up everything that I'm working on and I have to go back and fix things. Same thing with Num Lock! If you use these quick xmodmap commands you can disable those keys and avoid some headaches.

# Disable: Capslock, Numlock
xmodmap -e "keycode 66 ="
xmodmap -e "keycode 77 ="
Leave A Reply

Winamp: Opus plugin for Winamp

Winamp will always have a special place in my heart. Luckily it's still semi-maintained and runs great on Windows 10. It plays a bunch of audio files types out of the box, but lacks .opus support. Luckily someone wrote a plug-in to read opus files.

I've mirrored it here just in case.

Leave A Reply

Perl: Parse Linux log time strings

Linux has a common date/time format used in logs that looks like May 4 01:04:16. Often I will need to parse that into a unixtime so I wrote a function to do it so I won't have to reinvent the wheel next time:

use Time::Piece;

my $epoch = linux_timestr("May  4 01:04:16");

sub linux_timestr {
    my $time_str = shift();
    # Since this string type doesn't include the year we append the current
    # year to make the calculations correct. Otherwise we get 1970
    my $year     = (localtime())[5] + 1900;
    $time_str   .= " $year";

    my $format = "%b %d %H:%M:%S %Y";
    my $x      = localtime->strptime($time_str, $format);

    return $x->epoch();

Other common formats are cdate and ISO 8601

# cdate
my $x = localtime->strptime("Sat May  8 21:24:31 2021", "%a %b %d %H:%M:%S %Y");
# ISO 8601
my $y = localtime->strptime("2000-02-29T12:34:56", "%Y-%m-%dT%H:%M:%S");
Leave A Reply

PHP: Either function because PHP lacks a good "or"

PHP lacks a good "or" comparison operator. Neither the or operator, nor the || return a value. I wrote a function that will take two (or more) variables and return the first one that has a non-zero value.

$limit = $array_count || 15;       // true (bad!)
$limit = either($array_count, 15); // 15 (good!)

function either() {
    $items = func_get_args();

    // Return the first non-empty item
    foreach ($items as $x) {
        if (!empty($x)) {
            return $x;

    return null;
Leave A Reply

Perl: Rounding a number

If you need to round a number in Perl you can use the POSIX method round(). If for some reason you don't want to use the POSIX method I wrote a pure Perl version of round() that is pretty fast.

use POSIX;

my $num = 3.14156;

print(POSIX::round($num)); # 3
print(round($num));        # 3

sub round {
    my $num = shift();

    if ($num < 0) {
        $ret = int($num - 0.5);
    } else {
        $ret = int($num + 0.5);

    return $ret;

Along with round, sometimes you want "round to the nearest X", which I also implemented:

sub nearest {
    my ($num, $nearest) = @_;

    my $div = $num / $nearest;
    my $ret = round($div) * $nearest;

    return $ret;
Leave A Reply

PHP: Increment a hash variable in an E_NOTICE friendly way

I have a hash that contains counts for a bunch of stats. Unfortunately you can't just increment a hash like: $hash['key']++ and have it be E_NOTICE compliant. If that key does not exist in the array and you try and increment it you will trigger an E_NOTICE alert. I wrote this quick increment implementation that will allow you to increment a non-existing key.

$hash = [];

incr($hash['key']); // Inits to 1
incr($hash['key']); // Sets to 2

// Increment a variable (E_NOTICE compatible)
function incr(&$i, $value = 1) {
    // If the value is already there add to it
    if (isset($i)) {
        $i += $value;
    // If the value isn't there, just set it initially
    } else {
        $i = $value;
Leave A Reply

Perl: Calculate ellapsed milliseconds

In Perl if you want to calculate time in milliseconds (thousandths of a second) you can use Time::HiRes and the time() function.

use Time::HiRes qw(time);

my $start = time();

# Stuff you want to time here

my $elapsed = time() - $start;

printf("%0.2f seconds\n", $elapsed);
printf("%0.1f milliseconds\n", $elapsed * 1000);
printf("%d microseconds\n", $elapsed * 1000 * 1000);
printf("%d nanoseconds\n", $elapsed * 1000 * 1000 * 1000);
Leave A Reply

PHP: Set a threshold to limit API access

I have an API that I want to allow outside access to, but it needs to be protected from abuse. I wanted to limit the number of hits from a given source in a way that does not require tracking every single hit in database. Specifically I wanted a method to track millions of sources without requiring insane amounts of disk or memory.

I ended up with the concept of a "bucket" of hits in a given time window. This groups all the hits for a source into a bucket of time which makes it easier to track. My back of the envelope math means that each source should require between 40 and 50 bytes of memory to track. This makes it feasible to track and limit a million clients using about ~50MB of memory. Some type of caching system is required. Memcached, Redis, or a simple in-memory key/value cache would work perfectly.

You can view my proof-of-concept code, and view the raw PHP. This example uses Memcached.

Leave A Reply

Bash: History size and timestamp

Bash defaults to logging 1000 entries to the history. I increased that limit by adding the following line to my ~/.bashrc

export HISTSIZE=5000           # the bash history should save 5000 commands
export HISTTIMEFORMAT="%F %T " # Store the timestamps of each command also


Leave A Reply

Perl: A script that contains valid Perl and Python code

Perl has a cool runtime option named -x that causes Perl to scan a file for the first shebang line with "perl" in it, and start executing there. This allows you to embed Perl in other files, like text files, or email files.

This got me thinking about embedding a working Perl script in another file. Python allows you to have large multi-line comment blocks using triple quotes """ blocks around your text. Using these comment blocks I was able to embed Perl code inside of a Python script. Effectively you can have a single file that is executable by Perl (with -x) and Python. I wrote up a quick proof-of-concept dual language script.

python dual-perl-python.py
perl -x dual-perl-python.py

Gives varying output:

Hello world from Python v3.8.7
Hello world from Perl v5.30.3
Leave A Reply

Perl: Simple file cache

I need a simple disk based object cache and Cache::File was overkill. I wrote my own dependency free (only core modules) version:

cache($key);                     # Get
cache($key, $val);               # Set expires is 1 hour (default)
cache($key, $val, time() + 900); # Set expires in 15 minutes
cache($key, undef)               # Delete

I purposely wrote it small so it can be copy/pasted in to other scripts simply. I wrote a more robust implementation with some basic tests as well. When an entry is fetched that is expired it will be removed from disk. Abandoned cache entries will persist on disk until cache_clean() is called.

sub cache {
    use JSON::PP; use Tie::File; use File::Path; use Digest::SHA qw(sha256_hex);

    my ($key, $val, $expire, $ret, @data) = @_;

    my $hash = sha256_hex($key || "");
    my $dir  = "/dev/shm/perl-cache/" . substr($hash, 0, 3);
    my $file = "$dir/$hash.json";

    tie @data, 'Tie::File', $file or die("Unable to write $file"); # to r/w file

    if (@_ > 1) { # Set
        $data[0] = encode_json({ expires => int($expire || 3600), data => $val, key => $key });
    } elsif ($key && -r $file) { # Get
        eval { $ret = decode_json($data[0]); };
        if ($ret->{expires} && $ret->{expires} > time()) {
            $ret = $ret->{data};
        } else {
            $ret = undef;

    return $ret;
Leave A Reply

Perl: Create a variable pointer to a built-in filehandle

I have a function that takes a filehandle for an argument. This is easy for filehandles that you create with open() but gets more complex if you try to use one of the automatic filehandles. Using the * syntax you can create a pointer to the symbol table for that entry.

$fh = \*STDIN;
$fh = \*STDOUT;
$fh = \*DATA;

Once it's a standard scalar variable it can easily be passed to a function.

Leave A Reply

Perl: Run a shell command and capture STDOUT and STDERR separately

Often I'll want to run a shell command and capture STDOUT and STDERR separately. I wrote a function to simplify this process:

my $x    = shell_cmd($cmd);
my $exit = $x->{exit};
my $err  = $x->{stderr};
my $out  = $x->{stdout};
# Run a command and return STDOUT/STDERR/Exit
sub shell_cmd {
    use IPC::Open3;
    my ($cmd) = @_;
    my ($STDIN, $STDOUT, $STDERR, $pid, $ret) = (1,2,3,undef,{});

    # If it's an arrayref run it directly (no shell)
    if (ref($cmd) eq 'ARRAY') {
        $pid = IPC::Open3::open3($STDIN, $STDOUT, $STDERR, @$cmd);
    } else {
        $pid = IPC::Open3::open3($STDIN, $STDOUT, $STDERR, $cmd);
    waitpid($pid, 0);

    # Set FH slurp mode
    local $/ = undef;

    $ret->{exit}   = int($? >> 8);
    $ret->{stderr} = readline($STDERR);
    $ret->{stdout} = readline($STDOUT);
    $ret->{cmd}    = $cmd;

    return $ret;
Leave A Reply

HTML5: Text to speech

HTML5 includes some text-to-speech processing that can be invoked via JavaScript. I wrote a quicky script to allow you to paste text and have it read for you. It's great to proofread emails before you send them.

Leave A Reply

Web based bandwidth converting tool

I was ripping DVDs and needed to calculate the final output size given a specific bitrate. I got tired of doing the math over and over so I wrote a tool to do it for me.

Bandwidth converter

Update: Apparently I wrote something similar in 2015 also.

Leave A Reply