megacolorboy

Abdush Shakoor's Weblog

Writings, experiments & ideas.

Looping infinitely around an array

Sometimes, I find myself in a situation where I might have a fixed array of colors, text, numbers or something like that but I want to loop around infinitely like a carousel.

Let's say we have an array like this:

var colors = ["#111", "#222", "#333"];

The code is an array of three colors that we want to apply to, hmmm, say a list of HTML DOM elements like <div> containers or any element that you prefer. In this example, we'll add some colors to a bunch of <div> elements that has the classname .card or we'll just call them "cards".

Behold, the Modulus operator!

You may think of writing different conditions or loops to achieve a solution but a more elegant one is by using the Modulus operator a.k.a the Remainder operator (%). Using this operator gives you the remainder after the division of a number.

Hmm, confused? Okay, here's a simple example of how a Modulus operator would be like:

In plain english, if you have 10 apples and you divide them by 4 and by doing so, you'll end up with 2 sets of 4 apples and the remaining set would be 2 apples. Thus, the remainder is 2.

Did that make sense? If not, then try the following code in your browser:

var x = 10 % 4;
console.log(x); // output will be 2

Let's say we have 10 "cards" and we want every 3 three cards to have 3 different colors, we must just define a way to determine the index of each color while iterating through a loop of cards. So, we can easily get the index by doing so:

var currentColor = colors[i % colors.length-1];

Here's the full code:

var elements = document.querySelectorAll('.card');
for(var i=0; i<elements.length; i++){
    var currentColor = colors[i % colors.length-1];
    elements[i].style.backgroundColor = currentColor;
}

The following code will apply the colors to each "card" with respect to it's order and will reset back to the first color once it's reached it's last color based on the remainder of the next iteration in the loop.

Read about Modulus Operation to know more about it.

Enable HTTP Strict Transport Security (HSTS)

As part of a project that I was working on, I learnt about HTTP Strict Transport Security protocol which tells the browser about making future web requests over HTTPS only. So, even if you attempt to use http://, the browser will force you to use https:// URLs in the future.

You can enable it by writing this header in your .htaccess file in your public directory:

Header always set Strict-Transport-Security "max-age=31536000" env=HTTPS

Please note that once you enable this protocol, your web application is committed to using SSL i.e. you won't be able to use insecure HTTP for your web application.

Forcing HTTP to HTTPS redirect after enabling SSL

You can manually force HTTP to HTTPS after enabling your SSL certificate by adding the following condition at the beginning of your .htaccess file in your public directory:

RewriteCond %{HTTP:X-Forward-Proto} !=https
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Save your file and restart your Apache server and now, your web application will redirect all your users to https:// instead of http:// URLs in the future.

Enable copy-paste clipboard in URxvt Terminal Emulator

In my current Arch Linux installation, I decided to use a window manager called i3. It's really awesome and it comes with a really lightweight terminal emulator called urxvt. It's very minimal and I lked it but when I tried to copy-paste text from one terminal to another, I wasn't able to.

However, thanks to the internet, I did some research and figured a way out.

1. Install xClip

First, you need to ensure that you have installed the xclip package, which will be used to copy-paste text in the emulator.

Type the following command to install the package:

pacman -S xclip

2. Activate Clipboard using Perl

Now, you have to paste these custom commands into your clipboard file, which is found in /usr/lib/urxvt/perl directory:

# paste selection from clipboard
sub paste {
     my ($self) = @_;
     my $content = `/usr/bin/xclip -loop 1 -out -selection clipboard` ;
     $self->tt_write ($content);
}

# copy text to clipbard on selection
sub on_sel_grab {
     my $query = $_[0]->selection;
     open (my $pipe, '| /usr/bin/xclip -in -selection clipboard') or die;
     print $pipe $query;
     close $pipe;
 }

3. Modify your .Xresources

Add these keybindings to your .Xresources file:

URxvt.keysym.Shift-Control-V: perl:clipboard:paste
URxvt.iso14755: False
URxvt.perl-ext-common: default,clipboard

After adding it, refresh your .Xresources settings:

xrdb -merge .Xresources

Reboot your terminal and try selecting some text from your terminal using your mouse and paste it using Ctrl+Shift+V and it should work!

That's it! Enjoy 😃

Configuring audio drivers in Arch Linux

Yesterday, I thought of testing my Arch Linux system's audio and turns out, I didn't even install it yet! 😒

Well, thanks to ArchWiki, it was simple enough to install to make the audio work on my old laptop. Just install the following packages:

pacman -S alsa-firmware alsa-lib alsa-utils

Reboot the system once you're done installing the packages. Depending on your window manager, you should be able to see your sound icon being active.

Bonus: Bash script to control your volume from the terminal

In my current laptop, I still haven't mapped out the keys to control the audio volume, so I thought of writing a small method in my .bashrc file, so that I can control it from my terminal.

Open your favorite text editor and Add this method in your .bashrc file:

# simple volume control
volume(){
    x=5
    if [ $1 == 'up' ]
    then
        amixer set Master $x%+ &> /dev/null
    elif [ $1 == 'down' ]
    then
        amixer set Master $x%- &> /dev/null
    elif [ $1 == 'toggle' ]
    then
        amixer set Master toggle &> /dev/null
    fi
}

Save the file, close your edit and refresh your file by typing:

source .bashrc

Now, it should work when you type any of these commands:

volume up
volume down
volume toggle

Hope this tiny script helps you out!

Troubleshoot time-related SSL errors on secure websites

As I was configuring Arch Linux setup on my old HP 8460p laptop, I noticed that I wasn't able to access any site using Chrome or Firefox as I was faced with a weird error:

I was quite confused and thought it might be an issue with my WiFi card or probably some server issue but turns out it was neither of them.

On the side of my screen, I noticed my system time was displaying 4 hours ahead of the current local time, which is wrong. So, I did a little research and turns out my suspicions were correct, it's a time-related issue.

How is time related to secure websites?

Well, each website that uses SSL or that begins with https:// are only valid for a period of time before getting expired. If the website that you're trying to visit presents a certificate with a time and date that doesn't match with your system's clock, Firefox will prevent you from accessing the page.

How to fix it?

Actually, the fix is quite simple. All you have to is just set the correct date and time on your system and you're good to go!

If you're using Linux, just do the following:

1. Set up your timezone

You can look up for your timezones by executing the following:

timedatectl list-timezones | less

Once, you've found your timezone, execute the following by replacing Continent/Country with your timezone:

timedatectl set-timezone Continent/Country

2. Manually set your local time

Execute the following to set up your time, locally on your system:

timedatectl set-time "yyyy-MM-dd hh:mm:ss"

3. Set the hardware clock from the system clock

The following command sets the hardware clock from the system clock:

hwclock --systohc

Now, that you've executed them, you should be able to view the correct time on your system by executing timedatectl status and you should see something like this:

               Local time: Sun 2020-06-14 21:04:04 +04
           Universal time: Sun 2020-06-14 17:04:04 UTC
                 RTC time: Sun 2020-06-14 17:04:05    
                Time zone: Asia/Dubai (+04, +0400)    
System clock synchronized: no                         
              NTP service: inactive 

Although, this issue was time-related, you may face the same kind of error for various other reasons. Try reading more on how to troubleshoot errors like these from Mozilla's official documentation.

Transfer files remotely using SCP

Do you want to transfer files remotely from one UNIX-based system to another? Try using the scp tool, which is a shorthand for Secure Copy Protocol. It's based off the SSH protocol using it as a means to securely transfer files from a local machine to one or more remote machines.

Here's a code snippet that can help you out to transfer from computer A to computer B:

scp your_local_file user@ipaddress:/directory_to_store

And transfer from computer B to computer A:

scp user@ipaddress:/directory/file_name your_local_directory

Oh, before you transfer files to another computer, make sure that you have permissions to access it first. If you don't have one, then create a new account using useradd on your remote system.

How to manually configure your WiFi on Arch Linux?

Recently, I thought of playing around with Arch Linux to learn more about Linux under-the-hood and to see if it can become my new daily driver.

As I booted from live USB, I tried connecting to my WiFi using wifi-menu but it never worked after selecting my network name and entering the credentials.

So, I did a little bit of research in ArchWiki and forums and I figured a way to set it up manually using netctl by myself.

netctl is a network profile manager and it's apparently an Arch Linux project.

1. Select your interface

Before you begin to set up your WiFi connection from your computer, check if your network interface is being detected:

iwconfig

Since it's a WiFi connection, your interface most probably must be wlan0. If you see it, then set the interface up:

ip link set wlan0 up

2. Scan for networks

Now, that your interface, use it to scan for your WiFi network:

iwlist wlan0 scan | less

Once, you execute this command, you must be able to see your WiFi's SSID (or network name).

Now, put your interface down for a while:

ip link set wlan0 down

3. Create a network profile

Alright, go to /etc/netctl/examples/ directory and make a copy of the wireless-wpa file to the /etc/netctl directory:

cd /etc/netctl/examples
cp /etc/netctl/examples/wireless-wpa /etc/netctl/your-wifi-name

Now, go back to /etc/netctl/ directory and open the your-wifi-name file with your preferred text editor and edit the following only:

ESSID: your-wifi-name
key: your-wifi-password

After you're done editing, save the file.

4. Test network profile

To test if your profile is working, do the following:

netctl start your-wifi-name
ping -c 3 www.google.com

In case, you get an error, try doing this:

ip link set dev wlan0 down
netctl start your-wifi-name
ping -c 3 www.google.com

If you're able to ping, then it works. Else, edit your network profile and try connecting to it again.

5. Enable network profile

If you've reached this stage that means your network profile must be working fine. Just do the following to enable the network profile to run the internet throughout the setup:

netctl enable your-wifi-name

Try reading more about using netctl in Arch Linux's official wikipage.