Friday, 29 November 2024

Using grep --exclude/--include Syntax to Skip Certain Files

 When you need to search for a specific string across files in a directory structure, but wish to exclude or include certain types of files (such as excluding binary files or including only certain file types), you can leverage grep's --exclude and --include options.

Scenario: Searching for foo= in Text Files While Excluding Binary Files

Consider the task of searching for foo= in text files but excluding binary files such as images (JPEG, PNG) to speed up the search and avoid irrelevant results. You can use the following command to achieve this:

Read more »

Labels:

Thursday, 28 November 2024

How to Find the First Key in a Dictionary in Python

In Python, dictionaries store key-value pairs, and you may sometimes need to retrieve the first key. The approach depends on the Python version you are using. Here’s how you can do it efficiently.

Python Dictionary Basics

Consider the following dictionary for demonstration:

prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
}
Read more »

Labels:

Wednesday, 27 November 2024

How to Safely Encode URLs in JavaScript: A Guide to encodeURIComponent and Related Methods

 When working with URLs in JavaScript, encoding is essential to ensure that data is transmitted safely and interpreted correctly by web servers. This post will guide you through the key methods for encoding URLs, their use cases, and best practices.

Why Encode URLs?

Encoding ensures that special characters in a URL—such as &, ?, or =—are not misinterpreted as part of the URL’s syntax. For example, when adding query parameters to a URL, failing to encode them may lead to unexpected behavior or errors.

Read more »

Labels:

Tuesday, 26 November 2024

Understanding the likely and unlikely Macros in the Linux Kernel: How They Work and Their Benefits

 The Linux kernel’s likely and unlikely macros help optimize code execution by hinting to the compiler about the expected outcome of conditional statements. These macros use GCC’s __builtin_expect function, which influences branch prediction and instruction layout. Here’s a detailed breakdown of how they work and their benefits:

Definition and Functionality

The macros are defined as:

#define likely(x)   __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
Read more »

Labels:

Monday, 25 November 2024

How to Get a File’s Extension in PHP

When working with files in PHP, extracting the file extension is a common task. There are multiple ways to achieve this, ranging from basic string manipulation to built-in functions. Let’s dive into the best practices and alternatives for getting a file’s extension in PHP.

Using pathinfo()

PHP provides a built-in function, pathinfo(), that is both efficient and easy to use. It extracts various components of a file path, including the extension:

Read more »

Labels:

Sunday, 24 November 2024

Mastering String Repetition in Perl

 In programming, you often need to repeat strings. For example, in Python, multiplying a string by a number repeats it:

print("4" * 4)
# Output: 4444

However, if you try a similar expression in Perl like print "4" * 4;, you get 16 instead of 4444. This is because Perl’s * operator is strictly for numerical multiplication. To repeat a string, Perl uses the x operator. Let’s explore how to achieve string repetition in Perl with some fresh examples to deepen your understanding.

Read more »

Labels:

Friday, 22 November 2024

Converting Arrays to ArrayLists in Java: A Comprehensive Guide

 Converting an array to an ArrayList is a common task for Java developers, but it comes with some nuances that are important to understand. Here are several ways to achieve this, along with their benefits and potential drawbacks.

The quickest and simplest way to convert an array to a list is by using the Arrays.asList() method. For example:

Read more »

Labels:

Thursday, 21 November 2024

How to Concisely Check Environment Variables in a Unix Shell Script?

 When writing shell scripts, you often need to ensure specific environment variables are set. This avoids unexpected behavior or errors during script execution. Here are some concise and elegant ways to perform such checks.

Read more »

Labels:

Wednesday, 20 November 2024

Why Doesn’t Python Print Output in a Detached Docker Container?

 When running a Python application in a detached Docker container (-d flag), it’s common to encounter issues where the application’s output doesn’t appear in the logs. This happens due to how Python handles buffering for standard output (stdout) and standard error (stderr). Let’s explore the problem and solutions.

The Problem: Buffered Output

By default, Python uses buffered output for stdout and stderr. This means data isn’t written to the output stream immediately but is instead stored in a buffer until it reaches a certain size or the program terminates. When a Docker container runs in detached mode, this buffered output might not appear in the logs promptly.

Read more »

Labels:

Tuesday, 19 November 2024

Merging JavaScript Objects: Techniques and Examples

 Merging properties of JavaScript objects is a common task when dealing with dynamic data structures. In this post, we’ll explore different ways to merge objects in JavaScript, showcasing various examples and techniques suitable for flat objects without recursion or functions.

1. Using the Spread Operator

The spread operator (...) is a modern and concise way to merge objects introduced in ECMAScript 2018. It creates a new object containing the properties of both input objects. If there are duplicate keys, the values from the second object overwrite those in the first.

Read more »

Labels:

Monday, 18 November 2024

Exploring Network Monitoring Tools in Linux: Alternatives to htop for Network Usage

 Network monitoring is essential for diagnosing performance issues or identifying processes consuming excessive bandwidth. While htop and top are excellent tools for system monitoring, they don’t directly offer the ability to sort processes by network usage. Below, we’ll discuss popular alternatives tailored for this purpose.

1. NetHogs

NetHogs is a lightweight tool designed for monitoring network bandwidth usage by processes. Unlike tools that group traffic by protocol or subnet, NetHogs tracks it by process.

Read more »

Labels:

Sunday, 17 November 2024

Best MySQL Collation to Use with PHP: A Practical Guide

Choosing the right collation in MySQL for PHP applications depends on your use case, language requirements, and compatibility needs. Here’s a breakdown of the best practices and commonly recommended options.

Understanding MySQL Collations and Encodings

  1. Encoding defines how characters are stored (e.g., UTF-8, UTF-16).
  2. Collation determines how characters are compared and sorted.

For PHP applications, ensuring consistent encoding and collation across the database, PHP scripts, and web pages is critical to prevent data corruption or unexpected behavior.

Read more »

Labels:

Saturday, 16 November 2024

Safest Ways to Iterate Through Perl Hash Keys

When working with Perl hashes, choosing the right way to iterate through keys is essential for avoiding unexpected behavior and ensuring efficient memory usage. Here are the most common methods, their advantages, and the potential pitfalls associated with each.

Iterating with each

The each function retrieves one key-value pair at a time. This is memory-efficient and works well for large hashes or tied hashes.

Read more »

Labels:

Friday, 15 November 2024

Exploring the Java “for-each” Loop: How It Works and Its Equivalents

Java’s for-each loop, introduced in Java 5, simplifies iterating through collections and arrays. While it’s concise and readable, understanding its mechanics and limitations is key for writing robust code. Here’s a detailed look at how it works, its equivalents, and its practical uses.

Basics of the for-each Loop

The for-each loop iterates over elements of a collection or array. Consider this example:

Read more »

Labels:

Thursday, 14 November 2024

Exiting a Shell Script Based on Process Exit Codes

In shell scripting, handling errors efficiently is crucial to ensure scripts behave as expected. One common scenario is wanting the script to stop execution when any command fails. Here’s a breakdown of several methods to manage exit codes and halt your script on errors.

Understanding $? and Exit Codes

Every command in a shell script returns an exit code, with 0 indicating success and any non-zero value indicating an error. You can access the exit code of the last executed command using $?.

Read more »

Labels:

Wednesday, 13 November 2024

Troubleshooting Pyenv: How to Switch Python Versions Effectively

If you’re using pyenv to switch between Python versions but find that it’s not working as expected, you’re not alone. This is a common issue, especially for macOS and Linux users. In this guide, we’ll go through common problems with pyenv, and how to set it up correctly to ensure you can switch between Python versions seamlessly.

Why Pyenv Isn’t Switching Python Versions

When you try to change Python versions using pyenv, you might notice that even after switching, running python --version still points to the previous version. This typically happens due to shell configuration issues or missing environment variables that prevent pyenv from properly overriding the system’s default Python path.

Read more »

Labels:

Tuesday, 12 November 2024

How to Generate a GUID/UUID in JavaScript: Modern Solutions for Unique Identifiers

 GUIDs (Globally Unique Identifiers), also called UUIDs (Universally Unique Identifiers), are a standard way to generate unique identifiers in software applications. In JavaScript, you can generate GUIDs to uniquely identify objects, store them in databases, or share them across different systems.

This post will explore methods for generating UUIDs, focusing on various approaches, especially ones that don’t rely on Math.random() due to its limitations in randomness and uniqueness.

What is a GUID/UUID?

A UUID is a 128-bit identifier formatted as "xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx", where:

  • x represents a hexadecimal digit (0-9, a-f).
  • M indicates the UUID version (e.g., 4 for randomly generated UUIDs).
  • N is a variant, usually one of 8, 9, a, or b.

Read more »

Labels:

Monday, 11 November 2024

How to Kill a Process by Name in Linux: A Quick Guide

In Linux, it’s common to run into situations where you need to stop a process that’s stuck or causing issues, like when Firefox doesn’t close properly. Rather than searching for the process ID (PID), which changes every time, killing a process by name is often quicker and easier. In this post, we’ll explore different ways to accomplish this using various commands and options.

1. Using pkill to Kill Processes by Name

The pkill command allows you to terminate processes by name directly, without needing the PID. Here’s how:

pkill firefox

This command will find all processes named “firefox” and terminate them.

Read more »

Labels:

Sunday, 10 November 2024

Mastering PHP: Converting Variables to Strings Like a Pro

When working in PHP, you may need a way to convert various data types into strings, similar to Java or .NET’s toString() method. In PHP, there isn’t a direct toString() method, but PHP provides several ways to achieve similar functionality. Let’s explore a few approaches, including examples for different data types and complex objects.

1. Type Casting: Converting Variables to Strings

The simplest way to convert a variable to a string is by type casting. This method works effectively for scalar values (integers, booleans, floats).

Read more »

Labels:

Saturday, 9 November 2024

Easiest Ways to Install Missing Perl Modules

When you encounter an error like Can't locate Foo.pm in @INC, it means Perl couldn’t find a required module. Fortunately, there are various ways to install Perl modules, each suited to different needs and environments. Here’s a guide to some of the most convenient ways to install missing Perl modules.

1. Installing Modules with CPAN

CPAN (Comprehensive Perl Archive Network) is Perl’s standard tool for installing modules. Here’s how to use it from the command line.

Read more »

Labels:

Friday, 8 November 2024

Reading a File into a Java String: Modern Techniques

Java provides multiple ways to read the entire contents of a file into a single String. From traditional methods using BufferedReader to modern approaches with NIO utilities, there’s a technique to suit different Java versions and project requirements. Here’s a guide to some of the most popular methods, including options for Java 7 and newer, as well as some third-party alternatives.

1. Using Files.readString() in Java 11+

For Java 11 and later, the Files.readString() method offers a simple and efficient way to read the entire content of a file into a String. This method preserves line terminators.

Read more »

Labels:

Thursday, 7 November 2024

How to Measure Program Execution Time in the Linux Shell

When running commands or scripts in the Linux shell, it’s often useful to know how long they take to execute, especially when optimizing or testing under different conditions. Here are several ways to measure execution time in Bash, from basic to more advanced methods.

1. Using the time Command

The simplest way to measure execution time is with the built-in time command, which outputs real, user, and system time taken by a command.

time sleep 2
Read more »

Labels:

Wednesday, 6 November 2024

When to Use Classes in Python: A Guide for Data and Automation Developers

If you’ve been working with Python primarily for data processing, automation scripts, or small web applications, you may wonder when, if ever, you should use classes. Python supports multiple programming paradigms, and while classes are central to Object-Oriented Programming (OOP), not every Python script needs them. Here’s a guide on when classes can be useful in Python, especially for tasks involving automation, data handling, and small web projects.

Why Use Classes?

Classes provide a way to organize code that models complex data and behavior. They can make your scripts more modular, maintainable, and reusable. Here are some scenarios where classes might improve your code:

Read more »

Labels:

Tuesday, 5 November 2024

How to Get the Length of a JavaScript Object

 When working with JavaScript objects, there may be times when you want to determine how many properties an object contains. Unlike arrays, objects don’t have a built-in length property, so getting the count of an object’s properties requires a bit more work. Here are several methods to determine the length of a JavaScript object, including modern solutions and alternatives for older environments.

1. Using Object.keys()

The Object.keys() method is the most straightforward and widely-used approach. It returns an array of an object’s enumerable property names, making it easy to determine the length by checking the array’s length property.

Read more »

Labels:

Monday, 4 November 2024

Changing an Element’s Class with JavaScript: Simple and Modern Techniques

In JavaScript, modifying the CSS classes of HTML elements allows for dynamic styling changes based on user interactions or other events. Changing classes is especially useful for toggling visibility, updating themes, or applying specific effects. Here’s a look at different ways to change an element’s class with JavaScript, from basic to more advanced techniques.

1. Directly Setting the className Property

The simplest way to change an element’s class is to use the className property. This approach overrides any existing classes, so it’s best used when you want to replace the current class entirely.

document.getElementById("myElement").className = "newClass";

This method sets the class to "newClass" on the specified element. For multiple classes, you can provide a space-separated list:

document.getElementById("myElement").className = "class1 class2";
Read more »

Labels:

Sunday, 3 November 2024

Converting DOS/Windows Line Endings to Linux Line Endings in Vim

When working across multiple operating systems, you might encounter unwanted characters in your text files, especially if you’ve edited them on Windows and then opened them on Linux. Windows uses a combination of carriage return (\r) and newline (\n) characters for line endings, while Linux only uses newline (\n). In Vim, Windows-style line endings appear as ^M at the end of each line, which can be distracting and problematic in Linux-based environments.

If you want to convert these Windows line endings to Linux line endings within Vim, here are some methods to do so.

1. Quick Fix Using a Simple Substitution Command

You can quickly remove the ^M characters (which represent the carriage return, \r) by running the following substitution command:

Read more »

Labels:

Saturday, 2 November 2024

UTF-8 All the Way Through: Ensuring Full UTF-8 Support in Your Web Application

 Setting up full UTF-8 support in a web application is essential for handling multilingual content reliably. This guide covers all the key areas—MySQL, PHP, Apache, and HTML—to help you achieve a seamless UTF-8 experience across your stack. Here’s a checklist to ensure UTF-8 is correctly set up at every layer of your web application.

1. Configuring MySQL for UTF-8

To support a full range of Unicode characters, including emojis, configure MySQL to use utf8mb4 rather than utf8, as MySQL’s utf8 only supports up to three bytes (limited to basic multilingual characters).

  • Database and Table Configuration:

    CREATE DATABASE your_database CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
    ALTER TABLE your_table CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
    
  • Column Configuration:
    Set each text column to utf8mb4 to ensure character data is stored correctly:

    ALTER TABLE your_table MODIFY column_name VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
    
  • Connection Settings:
    Set the character set for connections to utf8mb4. This way, data exchanged between MySQL and your application retains its UTF-8 encoding. Use the following configuration depending on your PHP extension:

Read more »

Labels:

Friday, 1 November 2024

Why Are Perl 5’s Function Prototypes Often Considered Bad?

In Perl, function prototypes allow you to define subroutines that resemble Perl’s built-in functions. While prototypes have their niche uses, many Perl developers advise caution—or even avoidance—when using them. This guide will walk through why Perl’s prototypes are often seen as problematic and discuss scenarios where they can still be useful.

What Are Perl Prototypes Supposed to Do?

Unlike prototypes in many other languages, Perl’s function prototypes don’t perform compile-time argument checking. Instead, their main purpose is to allow user-defined functions to mimic built-in functions in terms of syntax and behavior. This means that prototypes primarily:

  • Allow you to omit parentheses when calling the function.
  • Impose specific contexts (e.g., scalar or list) on the arguments.

Here’s a simple example:

sub mypush(\@@) {
    my ($array_ref, @items) = @_;
    push @$array_ref, @items;
}

my @array;
mypush @array, 1, 2, 3;  # Works without requiring parentheses

In this example, mypush is defined with a prototype (\@@), allowing it to be called like a built-in push, without explicitly referencing the array with \.

Read more »

Labels: