Perl: Add an element to the middle of an array

If you want to add an element to the middle of an existing array you can use the splice() function. Splice modifies arrays in place. Splice takes four arguments for this: the array to modify, the index of where you want to modify, the number of items you want to remove, and an array of the elements to add.

my @x = qw(one three);

# At the 2nd index, add (replace zero elements) a one element array
splice(@x, 1, 0, ('two'));

print join(" ", @x); # "one two three"
Leave A Reply

Perl: Get certain elements of an array the lazy way

I learned that you can extract various elements from a Perl array in a very creative/simple way. Using this syntax may simplify some of your code and save you a lot of time.

my @colors = ("red", "blue", "green", "yellow", "orange", "purple");

my @w = @colors[(0, 3)];    # ("red", "yellow");
my @x = @colors[(0, 2, 4)]; # ("red", "green", "orange");

# First and last element
my @y = @colors[(0, -1)];   # ("red", "purple");

# First ten items
my @z = @array[0 .. 10];    # Using the `..` range operator

Basically any call to an array where the payload is an array of indexes will return a new array with those items extracted.

my @colors = ("red", "blue", "green", "yellow", "orange", "purple");

# You can also use an array variable to specify the elements to extract
my @ids = (1,3,5);
my @x   = @colors[@ids]; # ("blue", "yellow", "purple")

Note: Since you are referencing the whole array (not one element) you use the @ sigil instead of $.

Leave A Reply

Nagios: Check free memory on a Linux server

I had a Linux server run low on free memory which caused some processes to stop responding. Surprisingly there isn't a good modern Nagios plugin to check free memory so I wrote my own to watch for this in the future. Pretty basic, but it works well.

Leave A Reply

PHP: Stopwatch function to time pieces of code

I need to time how long a certain piece of code takes to complete. I wrote a simple PHP stopwatch function to accomplish this:

sw(); // Start the stopwatch
$x  = some_slow_code();
$ms = sw(); // Return milliseconds since start
// Stopwatch function: returns milliseconds
function sw() {
    static $start = null;

    if (!$start) {
        $start = hrtime(1);
    } else {
        $ret   = (hrtime(1) - $start) / 1000000;
        $start = null; // Reset the start time
        return $ret;
    }
}
Leave A Reply

Lumens per watt as required by the government

New laws have gone in to place that govern the amount of energy used to generate light:

The rule passed by President Joe Biden’s Department of Energy in April 2022 states that light bulbs must emit a minimum of 45 lumens per watt. A lumen is a measure of brightness.

That effectively outlaws the manufacture and sale of common incandescent bulbs, the kind you screw into the vast majority of light sockets in your home. That’s because traditional incandescent bulbs provide just 15 lumens per watt, according to light bulb manufacturer Philips.

By contrast, most LED bulbs will get you 75 lumens per watt, or more.

Further restrictions will take place in 2024 as well:

In December 2022, the Department of Energy proposed a rule that would more than double the current minimum light bulb efficiency level, to over 120 lumens per watt for the most common bulbs. That would go into effect by the end of 2024 and effectively ban CFL bulbs.

Leave A Reply

Python: Null coallesce on an array

I have a small array in Python, and I need to get the 2nd element of that array, or a default value if it's not present. All the other languages (PHP, Perl, Javascript) I use have a simple null coallescing operator that makes it simple, but not Python. I got tired of writing it out every time to so I wrote a simple wrapper function:

x = [2,4,6]

# Get the 3rd item from x
y = arrayItem(2, x, -1) # 6
# Get the 8th (non-existent) item from x
y = arrayItem(7, x, -1) # -1
# Get an item from an array, or a default value if the array isn't big enough
def arrayItem(needle, haystack, default = None):
    if needle > (len(haystack) - 1):
        return default
    else:
        return haystack[needle]

If there is a better, simpler, built-in way I'm open to hearing it.

Leave A Reply - 1 Reply

Linux: fd is a much better file search

Linux has had the find command since the 1970s. It was probably great in it's day, but it's not very modern and isn't the most intuitive tool. I found fd (sometimes called fd-find) which is infinitely better and easier to use. If you're looking for a simple way to search your filesystem, it's the way to go.

fd-find is hosted on Github.

Leave A Reply

Arduino: Get IP and MAC address

Here is a quick way to get the IP address and/or MAC address from your Arduino device as a String.

String get_mac_addr() {
    uint8_t mac[6];
    WiFi.macAddress(mac); // Put the addr in mac

    char buf[18] = "";
    snprintf(buf, sizeof(buf), "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);

    return (String)buf;
}
String get_ip_addr() {
    IPAddress ip = WiFi.localIP();

    char buf[16];
    snprintf(buf, sizeof(buf), "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);

    return (String)buf;
}
Leave A Reply

Arduino: Connect to WiFi

Quicky helper function to connect to WiFi on Arduino so I don't have to re-invent the wheel every time I start a new project.

void init_wifi(const char *ssid, const char *password) {
    WiFi.mode(WIFI_STA); WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        delay(500); Serial.print(".");
    }

    Serial.printf("\r\nConnected to: \"%s\"\r\n",ssid);
    Serial.print("IP address  : "); Serial.println(WiFi.localIP());
    Serial.print("MAC address : "); Serial.println(WiFi.macAddress().c_str());
}
Leave A Reply

Arduino: ESP32-S2 USB modes

I picked up some new ESP32-S2 boards to play around with. These newer boards come with native USB on board, instead of a separate USB to serial chip to handle communications. With this new chip, there are some new USB acronyms in the Arduino menus. I kept getting them confused so I looked them all up and am committing them here for future reference.

Mode Explanation
USB DFU Device Firmware Upgrade: Upload mode
USB CDC Communication and Data Control: UART/Serial mode
USB MSC Mass storage device class
USB HID Human Interface Device: Mouse/Keyboard emulation
Leave A Reply

Comparison table for ESP boards

Simplified table of ESP boards with components I care about.

ESP8266 ESP32 ESP32-S2 ESP32-S3 ESP32-C3
GPIO 17 34 43 45 22
CPU 1x @ 160Mhz 2x @ 240Mhz 1x @ 240Mhz 2x @ 240Mhz 1x @ 160Mhz
Architecture Tensilica Tensilica Tensilica Tensilica RISC-V
RAM 160K 520K 320K 512K 400K
Touch Pins 0 10 14 14 0
Bluetooth No 4.2 No 5.0 5.0
USB OTG No No Yes Yes No

More details and Espressif product comparison

Note: Assume about eight pins are used internally to connect flash and other peripherals.

Leave A Reply

Force SSH to ask for a password and skip keys

Normally I use SSH keys (with a password) to login to remote machines. Today I needed to force SSH to use a password to verify a change. Here is the command:

ssh -o PubkeyAuthentication=no user@server.domain.com

Leave A Reply

Books of 2023

List of books I read in 2023. Also see the list of 2022. The date indicated denotes the date I started reading the book.

2023-01-04 - The Twisted Ones by T. Kingfisher - 385 pages by
2023-01-29 - A Psalm For The Wild-built by Becky Chambers - 147 pages
2023-01-31 - 1984 by George Orwell - 298 pages
2023-02-08 - The House In The Cerulean Sea by T. J. Klune - 385 pages
2023-02-27 - A Court Of Thorns And Roses by Sarah J. Maas - 416 pages
2023-03-31 - The Cat Who Saw Red by Lilian Jackson Braun - 249 pages
2023-04-02 - Parable Of The Sower by Octavia E. Butler - 329 pages
2023-05-27 - Chapterhouse Dune by Frank Herbert - 493 pages
2023-06-05 - American Psycho by Bret Easton Ellis - 399 pages
2023-06-20 - Star Wars: Legacy of the Force - Betrayal by Aaron Allston - 387 pages
2023-06-27 - The Anthropocene Reviewed by John Green - 274 pages
2023-07-17 - Star Wars: Legacy of the Force - Bloodlines by Karen Traviss - 380 pages
2023-07-30 - Light From Uncommon Stars by Ryka Aoki - 369 pages
2023-08-05 - Prayer For The Crown-Shy by Becky Chambers - 149 pages
2023-08-07 - Dune House Atreides by Brian Herbert - 604 pages
2023-08-28 - The Cat Who Played Brahms by Lilian Jackson Braun - 245 pages
2023-08-31 - Star Wars: Tempest by Troy Denning - 392 pages
2023-09-05 - Slaughterhouse-Five by Kurt Vonnegut - 275 pages
2023-09-14 - Unsub by Meg Gardiner - 366 pages
2023-09-20 - The Tommyknockers by Stephen King - 558 pages

Xanth

2023-01-10 - Isle Of View - Xanth #13 by Piers Anthony - 344 pages
2023-02-15 - Question Quest - Xanth #14 by Piers Anthony - 338 pages
2023-03-06 - The Color Of Her Panties - Xanth #15 by Piers Anthony - 342 pages
2023-04-18 - Demons Don't Dream - Xanth #16 by Piers Anthony - 340 pages
2023-05-12 - Harpy Thyme - Xanth #17 by Piers Anthony - 342 pages
2023-06-26 - Geis Of The Gargoyle - Xanth #18 by Piers Anthony - 342 pages
2023-08-16 - Roc And A Hardplace - Xanth #19 by Piers Anthony - 344 pages
2023-08-22 - Yon Ill Wind - Xanth #20 by Piers Anthony - 340 pages
2023-09-09 - Faun & Games - Xanth #21 by Piers Anthony - 340 pages

Harry Potter

2023-01-15 - Harry Potter And The Sorcerer's Stone by J. K. Rowling - 309 pages
2023-02-04 - Harry Potter And The Chamber Of Secrets by J. K. Rowling - 341 pages
2023-03-10 - Harry Potter And The Prisoner Of Azkaban by J. K. Rowling - 435 pages
2023-04-07 - Harry Potter And The Goblet Of Fire by J. K. Rowling - 734 pages
2023-05-02 - Harry Potter And The Order Of The Phoenix by J. K. Rowling - 870 pages
2023-06-10 - Harry Potter And The Half-blood Prince by J. K. Rowling - 652 pages
2023-07-05 - Harry Potter And The Deathly Hallows by J. K. Rowling - 759 pages

Dresden Files

2023-01-20 - Cold Days - Dresden Files #13 by Jim Butcher - 614 pages
2023-02-18 - Skin Game - Dresden Files #14 by Jim Butcher - 600 pages
2023-03-16 - Ghost Story - Dresden Files #15 by Jim Butcher - 578 pages
2023-04-23 - Peace Talks - Dresden Files #16 by Jim Butcher - 496 pages
2023-05-17 - Battle Ground - Dresden Files #17 by Jim Butcher - 565 pages

Leave A Reply

PHP: Find the second (or third) occurrence of a substr in a string

I needed to find the second occurrence of a substring inside of a larger string. PHP has strpos() which gets you the first occurrence, but nothing beyond that. I wrote a wrapper function around strpos() to let you specify the number you want to find. Returns false if nothing is found.

function strpos_num(string $haystack, string $needle, int $num) {
    $offset = 0;
    $length = strlen($needle);
    $pos    = null;

    for ($i = 0; $i < $num; $i++) {
        $pos = strpos($haystack, $needle, $offset);

        // Short circuit continued lookups if we don't find anything
        if ($pos === false) { return false; }

        $offset = $pos + $length;
    }

    return $pos;
}
Leave A Reply

Perl: Human size in color

I use human_size() a lot in Perl, and sometimes it's nice to have a colored version. Here is a quick colorized version:

sub human_size_c {
    my $size = shift();
    if (!$size) { return undef; }

    if    ($size >= (1024**5) * 0.98) { $size = sprintf("\e[38;5;167m%.1fP\e[0m", $size / 1024**5); }
    elsif ($size >= (1024**4) * 0.98) { $size = sprintf("\e[38;5;105m%.1fT\e[0m", $size / 1024**4); }
    elsif ($size >= (1024**3) * 0.98) { $size = sprintf("\e[38;5;45m%.1fG\e[0m" , $size / 1024**3); }
    elsif ($size >= (1024**2) * 0.98) { $size = sprintf("\e[38;5;47m%.1fM\e[0m" , $size / 1024**2); }
    elsif ($size >= 1024)             { $size = sprintf("\e[38;5;226m%.1fK\e[0m", $size / 1024);    }
    elsif ($size >= 0)                { $size = sprintf("\e[38;5;160m%dB\e[0m"  , $size);           }

    return $size;
}

See also: Original human_size()

Leave A Reply