Today I Learned

This project is a collection of short write-ups on the things that I learn on a day-to-day basis across a variety of fields such as Computer Science, Mathematics, Software Engineering and Digital Design.

I consider this to be a microblog of sorts that can help me accumulate and share my knowledge with everyone! So far, I've published 62 short articles.

Hope you enjoy learning along with me! 😄

Chrome DevTools

How to filter requests with errors on Chrome's DevTools

Published on September 19th, 2020


Tired of trying to look for errors in DevTools by scrolling a long list of HTTP responses?

Open up your Chrome DevTools and hit the Network tab and then try filtering the responses by typing the status-code property in the filter box.

It comes in handy when you want to narrow down to a specific list of HTTP responses. For instance, if you're looking for responses with error 404, you can filter it by typing like this: status-code:404.

Another trick is, you can filter out the responses that you don't want to see by just adding a hyphen like this: -status-code:200.

Hope this tip helps you out!



Are you facing the same error as this article's title? Then this article might help you out.

If you're developing applications using HTTP/SSL Protocols (regardless, you should!) on Laravel, by default, you'll be using Laravel's encrypter but in it's official documentation, it says:

Before using Laravel's encrypter, you must set a key option in your config/app.php configuration file. You should use the php artisan key:generate command to generate this key since this Artisan command will use PHP's secure random bytes generator to build your key. If this value is not properly set, all values encrypted by Laravel will be insecure.

Just execute the following command in your root directory:


php artisan key:generate

If the error still persists, try clearing the cache by doing the following:


php artisan config:cache
php artisan cache:clear
php artisan config:clear

Hope you found this article useful!


Apache + WAMP

Enable HTTPS/SSL on WAMP Server

Published on September 13th, 2020


Building a website with HTTPS/SSL in mind can help resolve a lot of problems when you're going to deploy it on production server.

So, here's a small tutorial on how to enable HTTPS mode and install SSL certificate on your local WAMP Server.

Note: This tutorial assumes that you have a Windows PC and have installed WAMP Server 3.2.0 in your local system, if not, download it from here.

Download OpenSSL

Based on your system's architecture, you can download either a 32 or 64-bit installer. You can find the latest version of OpenSSL from here. While installing, please make sure all the options selected are default.

Generate SSL Key and Certificate

Open your terminal or command-line prompt and navigate to the following folder:


cd "C:\Program Files\OpenSSL-Win64\bin"

Next, you need to create a private key. While generating a private key, you'll have to enter a passphrase, it can be anything but make sure that you can remember it for the next step 😂.

Execute the following command:


openssl genrsa -aes256 -out private.key 2048

Good, now let's generate our certificate and in this step, you'll be prompted with several questions. You can fill as per your wish or just hit "Enter" to leave it as default. The only thing that matters is Common Name and this should named as localhost

Execute the following command:


openssl req -new -x509 -nodes -sha1 -key private.key -out certificate.crt -days 36500

Move the certificate and key to Apache's directory

Create a folder named keys and move both private.key and certificate.crt to this directory: C:\wamp64\bin\apache\apache2.4.41\conf.

Modify your httpd.conf file

You have to uncomment 3 lines from C:/wamp64/bin/apache/apache2.4.41/conf/httpd.conf:


LoadModule ssl_module modules/mod_ssl.so
Include conf/extra/httpd-ssl.conf
LoadModule socache_shmcb_module modules/mod_socache_shmcb.so

Modify your httpd-ssl.conf file

Go to C:/wamp64/bin/apache/apache2.4.41/conf/extra/httpd-ssl.conf and modify the following parameters:


DocumentRoot "c:/wamp64/www"
ServerName localhost:443
ServerAdmin admin@youremail.com
ErrorLog "${SRVROOT}/logs/error.log"
TransferLog "${SRVROOT}/logs/access.log"
SSLSessionCache "shmcb:${SRVROOT}/logs/ssl_scache(512000)"
SSLCertificateFile "${SRVROOT}/conf/keys/certificate.crt"
SSLCertificateKeyFile "${SRVROOT}/conf/keys/private.key"
CustomLog "${SRVROOT}/logs/ssl_request.log"

DocumentRoot is the location of where your website files are located. ServerName can be anything but preferable to use localhost.

Restart your WAMP Server

Just restart your WAMP Server for the changes to take effect. If the WAMP icon turns green, you're good else, an typo or syntax error must have occurred.

Hope you found this tutorial useful! 😀


Apache + WAMP

Accessing WAMP Server from other computers on LAN

Published on September 13th, 2020


Whenever you develop a website using the LAMP or WAMP stack, you'll want to access the website, locally, via different systems and devices solely for testing purposes.

Modify your VirtualHosts configuration

Setting up your WAMP Server for LAN access only requires you to tweak your VirtualHosts configuration file found in C:\wamp64\bin\apache\apache2.4.41\conf\extra\httpd-vhost.conf


<VirtualHost *:80>
  ServerName example.test
  ServerAlias example.test
  DocumentRoot "c:/wamp64/www/yourprojectname"
  <Directory "c:/wamp64/www/yourprojectname/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
    AllowOverride All
    Require all granted
  </Directory>
</VirtualHost>

Oh, if you're using Linux, you'll find the file 000-default.conf in /etc/apache2/sites-available directory.

Update your hosts file

If you type the URL of the website that you want to visit, the computer will first refer to the hosts file and then it'll go out to fetch DNS information. So, if you want http:\\example.test url to point to your local system, you just have add it in your hosts file:

Open the hosts file(C:\Windows\System32\drivers\etc\hosts) using a text editor and add this line to your hosts file:


127.0.0.1   example.test

Once done, save the file and restart your WAMP Server and you're all set to go!

Hope you found this tip useful!


JavaScript

Prevent loading a webpage from Back-Forward cache

Published on August 30th, 2020


I'm working on an eCommerce project and I encountered a really weird problem, whenever I saved items into my cart and proceed to the checkout page and then go back to previous page, my cart isn't updated until I refresh the page.

Honestly, I thought this was a bug until I came around to learn about Back-Forward Caching a.k.a bfcache, which allows the user to navigate between pages faster. That's a good thing, though!

But that didn't help resolve my issue, so I thought of going around with a tiny hack:


window.onpageshow = function(event) {
    if (event.persisted) {
        window.location.reload() 
    }
};

The code above will look any persistence of the onpageshow event. Initially, it's set to false and if the page is loaded from bfcache, it'll set to true.

I wouldn't really consider this as a solution as it only worked on Safari instead of Chrome or Firefox.

But hey, it gets the job done! 😂


JavaScript

Refresh browser window without query parameters

Published on August 29th, 2020


If you want to reload the current page in your browser without any query string or parameters, here's how you can do it:


window.location = window.location.pathname;

By doing so, it'll preserve the HTTP/HTTPS protocols of the URL and also remove the fragments that start with a #.

If you want to preserve the fragments, you can try this:


var reloadURL = window.location.pathname;
var fragments = (window.location.part === undefined) ? "" : "#" + window.location.part;
window.location = reloadURL + fragments;

Hope you found this useful!


Python

Extract unique characters from a string

Published on August 23rd, 2020


I thought of getting back into competitive programming again and started practicing my python coding-chops on Codewars.

Here's a neat trick on how to extract unique characters from a string:


from collections import OrderedDict

word = "HelloWorld"
uniq = ''.join(OrderedDict.fromkeys(word).keys())

print(uniq) # prints HeloWrd

Using OrderedDict allows you to preserve the order in which the keys are inserted as a normal dict doesn't track the order.

Hope you found this useful!


PHP

Increase execution time in PHP

Published on August 23rd, 2020


Ever process a file that's larger than 2GB and got an error that said something like this:

Maximum execution time of 30 seconds exceeded

Though, PHP doesn't have an efficient way of processing files of large sizes, you can prevent your web application from timing out by adding this to your code:


<?php
// 300 seconds == 5 minutes
ini_set('max_execution_time', 300);
?>

Hopefully, some day, this might come in handy for you! 😜


PHP

Increase memory limit in PHP

Published on August 23rd, 2020


Last month, I was building a web application that collected a lot of data via form submissions. I wrote a method to export attachments and form data by zipping them all together.

It worked for a smaller archives but as the records grew larger, I got a fatal error which said that I've exhausted the PHP's memory limit.

So, I found an easy way to increase the memory limit to 1024MB (1GB) like this:


<?php
ini_set('memory_limit', '1024M');
?>

Before you write this stub in your script, make sure you have enough resources in your system or else, it'll go splat!


PHP

Input sanitization with PHP

Published on August 23rd, 2020


This can come in handy when you're dealing with user inputs during a form submission and in most cases, your web application will be using a database query to store the data.

Using filter_var()

This method uses a number of flags to validate and sanitize a string. Here are some examples I have tried:

Removing special characters

Want to strip out all tags and certain characters? Try this:


<?php
$str = "<h1>Hello World</h1>";
$filtered = filter_var($str, FILTER_SANITIZE_STRING);
echo $filtered;
?>

Integer validation

You can check if the input is an integer and if it's a value between 1 and 20:


<?php
$x = 10;
$min = 1;
$max = 20;
$options = [
    "min_range" => $min,
    "max_range" => $max
];

if(!filter_var($x, FILTER_VALIDATE_INT, $options)){
    echo "This input is invalid.";
}
else {
    echo "This input is valid.";
}
?>

URL validation

Want to check if the input is a valid URL? Try this out:


<?php
// Make sure the URL is sanitized
$url = filter_var("https://www.google.com", FILTER_SANITIZE_URL);
if(filter_var($url, FILTER_VALIDATE_URL)){
    echo "This URL is valid.";
}
else {
    echo "This URL is invalid.";
}
?>

Using these in-built features makes it easier for PHP developers to process data from external sources in a safer manner and also adds an extra layer of protection to your web application.

Read more about this method in PHP's official documentation.


Go

Hello, Go!

Published on August 1st, 2020


After reading a lot of articles about using Go as a programming language to write high-performing concurrent web applications and services yet maintain a clean codebase, I thought of starting to learn it to see what's it about and so far, it's been great!

This mini-tutorial will show you how to install Go on your system and write a simple "Hello, World" program.

Note: This tutorial will go through installing Go on Linux.

Install Go

Make sure you have the latest updates and upgrades on your Linux system before installing Go.

You need to download the binary file from their official package. Find the version that suits your OS and architecture.


cd /tmp
wget https://golang.org/dl/go1.14.6.linux-amd64.tar.gz

Extract the downloaded archive and install it in the /usr/local directory (as per the standards):


sudo tar -xvf go1.14.6.linux-amd64.tar.gz
sudo mv go /usr/local

Set up environment

Now, we need to set up three variables:

  • GOROOT: Location of where your Go package is installed.
  • GOPATH: Location of your work directory.'
  • PATH: Tells bash on where to look for programs that are being executed.

Open up your .bashrc file and add these lines at the end of the file:


export GOROOT=/usr/local/go
export GOPATH=$HOME/go
export PATH=$GOPATH/bin:$GOROOT/bin:$PATH

Save your .bashrc file and update the current shell session:


source ~/.bashrc

Verify your installation

Type the following command to ensure that your Go installation is successful:


go version go1.14.6 linux/amd64

Hello, world!

As per traditions, whenever you learn a programming language, you start off with a "Hello, world!" program, so here it is:


package main

import "fmt"

func main() {
    fmt.Printf("Hello, world!\n")
} 

Conclusion

I just started learning it today and at first, you might have the tendency to write code in Go the same way you write in any other language but beware, it doesn't work that way. It forces you to write good code including the way it formats the code using the gofmt tool.

Lots of cool things are coming!

Stay tuned for more.


Terminal

How to delete files inside a zip file?

Published on July 21st, 2020


Ever compressed your project directory but forgot to delete that useless file or folder and turns out the compresed file is larger than it's supposed to be?

Here's a quick solution you can try:

If you want to delete a file inside a .zip file, try this:


zip --delete file.zip "file.ext"

And if you want to delete a folder, try this:


zip --delete file.zip "folder/*"

Hope this helps you out!


Regular Expressions

Find the number of uppercase and lowercase letters in a string

Published on July 18th, 2020


The usual approach of counting the number of uppercase and lower letters in a string is done by using a counter and a loop:


var upperCount = 0;
var lowerCount = 0;
var str = "AbCdEfGhiJkL";
for(var i=0; i<str.length; i++){
    if(str[i] == str[i].toUpperCase()){
        upperCount++;
    }
    else{
        lowerCount++;
    }
}

That's nice but here's shorter and faster implementation:


var str = "AbCdEfGhiJkL";
var lowerCount = str.length - str.replace(/[A-Z]/g, '').length;
var upperCount = str.length - str.replace(/[a-z]/g, '').length;

The lowerCount variable is taking the difference of the lengths between the original string and the string with lowercase letters only because the .replace() method replaced the pattern of uppercase letters [A-Z] with empty spaces. The upperCount variable does the opposite of what the lowerCount variable does.

Hope you found this trick useful!


Regular Expressions

Replace all occurrences found on a string using Regular Expressions

Published on July 18th, 2020


Let's say you have the following string and you must replace all occurrences of "Hello" with "Bye":


var str = "Hello Hello Hello World";

You may think of using the .replace() method to solve this problem:


var newStr = str.replace("Hello", "Bye")

But unfortunately, it only replaces the first occurrence in the string:


console.log(newStr); // returns "Bye Hello Hello World" as the output.

Using the power of Regular Expressions, you can replace all occurrences in one go:


function replaceAll(str, search, replace){
    var re = new RegExp(search, "g");
    return str.replace(re, replace);
}    

Now, when you execute the following, you'll get a string that replaced all occurrences:


var newStr = replaceAll(str, "Hello", "Bye");
console.log(newStr); // returns "Bye Bye Bye World" as the output.

Until next time, then!



Let's say, you have a multidimensional array like this:


$cars = [
    [
        "id" => 1,
        "name" => "Mercedes Benz",
        "color" => "Black"
    ],
    [
        "id" => 2,
        "name" => "Toyota",
        "color" => "Red"
    ],
    [
        "id" => 3,
        "name" => "Toyota",
        "color" => "White"
    ],
    [
        "id" => 4,
        "name" => "Nissan",
        "color" => "Grey"
    ],
];

And say, you want to be able to return unique cars by name or color, use this method:


function multi_array_unique($array, $key) {
    $i = 0;
    $temp_array = [];
    $key_array = [];

    foreach($array as $val) {
        // insert only unique keys
        if (!in_array($val[$key], $key_array)) {
            $key_array[$i] = $val[$key];
            $temp_array[$i] = $val;
        }
        $i++;
    }
    return $temp_array;
}

Call this method from anywhere in your code like this:


$unique_cars = multi_array_unique($cars, "name");
dd($unique_cars);

And now, you'll get something like this:


[
    [
        "id" => 1,
        "name" => "Mercedes Benz",
        "color" => "Black"
    ],
    [
        "id" => 2,
        "name" => "Toyota",
        "color" => "Red"
    ],
    [
        "id" => 4,
        "name" => "Nissan",
        "color" => "Grey"
    ],
];

You might wonder why I tried this instead of PHP's array_unique() method and the reason I didn't use it is because it doesn't support multidimensional arrays.

Hope you found this useful!


MySQL

How to duplicate tables in MySQL?

Published on July 18th, 2020


This trick comes in handy whenever you wanted to reuse a table, perform data migrations or maybe even take a backup of the table before any of your experiments mess up your data.

Executing the following query will help you create a new table with the structure of the old table:


CREATE TABLE schema.new_table LIKE schema.old_table;

If you want the data as well, try this:


CREATE TABLE schema.new_table LIKE schema.old_table;
INSERT schema.new_table SELECT * FROM schema.old_table;

You can use this query to copy tables from one schema to another schema too. Hope this helps you out! 😄


JavaScript

Find the difference between two arrays

Published on July 18th, 2020


Finding the difference between two sets i.e. Set A and Set B is basically returning a new set that contains values of Set A that don't exist in Set B or vice-versa.

Here's an example:


var a = [1,2,3,4,5];
var b = [1,1,2,3,4];

I wrote a shorter implementation using JavaScript's .filter() method:


function array_diff(a,b){
    return a.filter(i => b.indexOf(i) === -1);
}    

Once you execute this method, you'll get the following as a result:


var c = array_diff(a,b);
console.log(c) // returns [5]

BONUS: What does the .filter() method do?

This method returns a new array with elements that pass the conditions provided by a callback function.

If the conditions aren't passed, you'll receive an empty array.

In this article, (i => b.indexOf(i) === -1) is considered as the callback function in which the i refers to the index of the current element of array A and is then used as a parameter to check if the element doesn't exist in array B.

The neat thing about this method is that it doesn't mutate on the array that it's being called from.

Read more about Array.prototype.filter() on Mozilla's developer documentation.


PHP

Extract YouTube Channel ID from URL

Published on July 13th, 2020


Using PHP's in-built function, parse_url, you can write a helper method to pull the channel ID off a YouTube URL especially if you're pulling videos using YouTube's Data API. Here's the code:


public function extractChannelID($url){
    // Parse the link and trim any whitespaces
    $parsed_link = parse_url(rtrim($url, '/'));

    // Return the channel ID if it matches the pattern
    if (isset($parsed_link['path']) && preg_match('/^\/channel\/(([^\/])+?)$/', $parsed_link['path'], $matches)) {
        return $matches[1];
    }

    throw new Exception("This {$url} is not a valid YouTube channel URL");
    return null;
}

Writing tiny methods like these can help save time and be reusable in more than one context.

Hope you find this tip useful! 😁


Linux

Using zipcloak to encrypt files within an archive

Published on July 7th, 2020


Whenever you're sending a bunch of files or an archive that contains sensitive or confidential information, it's wise to encrypt before you send it to the person that you intend to.

Using zipcloak, you'll be able to encrypt files within your existing archive.

Do the following after you've created a zip archive:


zipcloak files.zip    

Now, you'll be prompted twice to enter a new password and verify your entered password. If they match, your archive will get encrypted. So whenever, you try to unzip or open using an Archive Manager, you'll be prompted to enter the password or else, you won't be able to access it.

You also have the choice of not encrypting the original archive and creating a new one instead, just like this:


zipcloak files.zip -O encrypted.zip    

On the other hand, if you do wish to remove the encryption from your archive, just type the following:


zipcloak -d files.zip

And you'll be prompted again to enter your password before it removes it's encryption.

Hope this helps you out! 😁



Although, Laravel is a good framework, it's quite heavy when it comes to executing queries especially if you're using the Eloquent ORM instead of the normal query builder.

But Laravel does offer the option of caching your queries in the server and will only make calls to your database if there's a change in content.

Quite handy when you're having a content-heavy website and huge amount of user traffic.

Using the Cache class, you can cache your queries like this:


$apples = \Cache::rememberForever('apples_cache', function(){
    return FruitsModel::where('item_name', 'LIKE', '%apples')
        ->get();
});

In the above example, apples_cache is the key that stores your queries of apples forever and which will be used to obtain your cached results from the server.

Oh, be sure to create distinctive names for different types of queries or else, you'll end up being confused! 😜

You can also give it a time limit in milliseconds:


$apples = \Cache::remember('apples_cache', 300000, function(){
    return FruitsModel::where('item_name', 'LIKE', '%apples')
        ->get();
});

Hope this tip helps you out! 😀


Algorithms

Looping infinitely around an array

Published on July 4th, 2020


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.


Apache

Forcing HTTP to HTTPS redirect after enabling SSL

Published on June 22nd, 2020


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.


Apache

Enable HTTP Strict Transport Security (HSTS)

Published on June 22nd, 2020


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.



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 😃


Linux

Configuring audio drivers in Arch Linux

Published on June 20th, 2020


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!



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:

SSL Certificate 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.


Linux

Transfer files remotely using SCP

Published on June 13th, 2020


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.



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.


JavaScript

Add search functionality to your static site

Published on June 6th, 2020


If you have a static site or a blog generated using a static-site generator but want to add a simple search functionality? This could be of your interest.

I'll take you through an example on how to build a simple search engine using a JSON file and AJAX requests.

1. Generate a JSON dump of your site

Although, it's not a database but it can act as an alternative to having one. Your JSON dump can contain any metadata that you wanted your users to search in your site. In my case, I thought of allowing the user to search title and category.

Is your site generated using Python and want to create a JSON dump? Read this article for more information.

2. Build search functionality

I won't go through the aspects of UI design in this article as I feel that it's subjective and depends on one's preferences but let's keep it simple enough for this tutorial.

Before you begin writing the function, place this component in your HTML template:


<div class="searchbox">
    <input id="searchinput" type="text">
    <div id="searchresults">
        <ul></ul>
    </div>
</div>

Anyway, here's the function and you can place it directly on your template or in a separate .js file:


var _url = "path-of-your-file.json";

$(document).ready(function(){
    $('#searchinput').keyup(function(e){
        var keyword = $(this).val();
        var code = e.keyCode ? e.keyCode : e.which;

        if(code == 13){
            $.ajax({
                url: _url,
                type: "GET",
                async: false,
            }).done(function(data){
                var results = "";
                if(data.articles.length > 0){
                    $.each(data.articles, function(key, value){
                        if(v.title.search(pattern) != -1 || v.category.search(pattern) != -1){
                            results += `<li><a href="${v.slug}">${v.title}</a></li>`;
                        }
                    });
                    $("#searchresults ul").html(results);
                }
            });
        }
    });
});

That's it! Now, when you execute your script, you should be able to view your search results just like as if it were using a database.

If you want to make it similar to mine, please feel free to inspect the code on the browser or go to my repository to see how it works.


Python

Read and Write JSON to a file in Python

Published on June 5th, 2020


You can make use of the built-in json package in Python to read and write JSON data to a file.

Writing JSON to a file

You can store the information in a dictionary or dict object, which can contain any type of data like integers, booleans, arrays or nested objects.

By using a dict object, the json package will transform your dictionary into a serialized JSON string.


import json

dataObj = {}
dataObj['posts'] = []
dataObj['posts'].append({
    'title': 'Hello world',
    'category': 'Introduction',
    'slug': 'hello-world'
})

with open('data.json', 'w') as file:
    json.dump(dataObj, file)

Reading JSON from a file

Reading is as easy as writing to a file. Using the same package again, we can parse the JSON string directly from the file.


import json

with open('data.json', 'r') as file:
    data = json.load(file)
    for item in data['posts']:
        print 'Title: ' + item['title']
        print 'Category: ' + item['category']
        print 'Slug: ' + item['slug']

I read about different package alternatives like simplejson but I guess for now, this is a great way to get started especially, if you're working with web applications and are interacting with a serialized JSON data on a daily basis.


JavaScript

Using default function parameters in Internet Explorer

Published on June 3rd, 2020


Today, I wrote a simple method that fetches images from the database via AJAX and also, I defined an empty object as a default parameter:


function fetchImages(obj={}){
    // some code here...
}

fetchImages();

The default obj parameter would contain extra parameters like id, slug and page, which would be then used to fetch a particular group of images, else, it'll fetch a random set of images.

This method worked fine in Google Chrome and Mozilla Firefox but not in Internet Explorer. I thought of inspecting the code and I was facing weird errors like undefined or Expected: ')' on the IE console.

Luckily, I had compared it to the other methods that didn't have any default parameters, so I did a little research and turns out that according to Mozilla's documentation, default function parameters are proposed by the ES6 syntax and at this point, I realized that Internet Explorer doesn't support ES6 syntax. What a bummer! 😒

However, there's a way to prevent this from happening by rewriting the method like this:


function fetchImages(obj){
    // Check if obj is defined, else make it assign it as an empty object.
    var data = obj || {};

    // some code here...
}

And BAM! The method worked flawlessly just as it's intended to do so. 😎

Addtionally, you may refer to the ECMAScript 6 Compatibility table that you might find it quite helpful to check browser compatiblity for Internet Explorer versions 11 and under.


Algorithms

Build a menu tree using recursion

Published on June 3rd, 2020


Hmm, what is the most efficient way to build a menu tree? 😅

Most people would go for a brute force solution if it's a straightforward menu but would that be possible if we intend to create multiple levels of menu items?

Sure, you could but as the number of loops increases, the complexity of time increases too. Not to forget, you'll end up writing code that'll look messy and unscalable.

I always loved the idea and simplicity of using recursion. So, I thought of exercising my recursion skills by writing a method that can generate a dynamic menu with x number of parent and child menu items.

The following example is written in PHP:



class FooController extends Controller {
    protected $menuHTML = "";

    private function menuItems() {
        return [
            [
                'title' => 'Item 1',
                'link' => '/item-1'
            ],
            [
                'title' => 'Item 2',
                'link' => '/item-2',
                'child_items' => [
                    [
                       'title' => 'Item 2.1',
                       'link' => '/item-2.1'
                    ],       
                    [
                        'title' => 'Item 2.2',
                        'link' => '/item-2.2'
                    ],       
                ]
            ],
            [
                'title' => 'Item 3',
                'link' => '/item-3'
            ],
            [
                'title' => 'Item 4',
                'link' => '/item-4'
            ],
        ];
    }

    // Build a menu tree
    private function buildMenu($menu) {
        foreach($menu as $menuItem){
            $this->menuHTML .= '<li class="item">';
            $this->menuHTML .= '<a href="'.$menuItem['link'].'">'.$menuItem['title'].'</a>';

            // Check if it has any child items
            if(array_key_exists("child_items", $menuItem){
                $this->menuHTML .= '<ul class="submenu">';
                $this->buildMenu($menuItem['child_items']);
                $this->menuHTML .= '</ul>';
            }

            $this->menuHTML .= '</li>'
        }
    }

    // Return the complete menu
    private function getMenu($menu) {
        $this->buildMenu($menu);
        return '<ul class="mainmenu">'.$this->menuHTML.'</ul>';
    }

    public function __construct() {
        pre($this->getMenu($this->menuItems());
        die;
    }
}


Once you run it, you'll see something like this:


<ul class="mainmenu">
    <li class="item"><a href="/item-1">Item 1</a></li>
    <li class="item"><a href="/item-2">Item 2</a>
        <ul class="submenu">
            <li class="item"><a href="/item-2.1">Item 2.1</a></li>
            <li class="item"><a href="/item-2.2">Item 2.2</a></li>
        </ul>
    </li>
    <li class="item"><a href="/item-3">Item 3</a></li>
    <li class="item"><a href="/item-4">Item 4</a></li>
</ul>

There a lot of ways to achieve this same result using recursion but it sure is easier to read, scalable and extensible, ain't it?


JavaScript

Allow inline elements in CKEditor

Published on June 1st, 2020


Using CKEditor is awesome but I hate it when it removes inline elements like <span>, <i> or any DOM elements that contain attributes like classnames or ID, by default.

Well, CKEditor's documentation states that you can allow it by adding this line to your configuration:


var editor = CKEDITOR.replace('textarea_edit',{
    allowedContent: true,
});

After adding this line, CKEditor will stop removing those elements from your HTML content but it's also open to all tags.

You can set rules to allow only specific ones like this:


var editor = CKEDITOR.replace('textarea_edit',{
    allowedContent: 'span; i; ul; li; a[!href]'
});

Hope this helps you out! 😊


JavaScript

How to identify the current target of an event?

Published on June 1st, 2020


Using the event.currentTarget property which belongs to the Event interface can help you in many ways to identify target of the current event especially if you want to fetch attributes or modify the classname of an element that belongs to a group of elements sharing the same classname.

There are many examples but I chose to write a small snippet of highlighting a tab:


function highlightTab(e){
    /*
        Find elements that has the classname 'active' 
        and remove them
    */
    if(document.querySelector('div.tab_item.active') !== null){
        document.querySelector('div.tab_item.active').classList.remove('active');
    }

    // Add active class to target node
    e.currentTarget.className += " active";

    // Add active class to target's child node
    // e.currentTarget.querySelector('a.child_anchor_link').className += " active";

    // Add active class to target's parent node
    // e.currentTarget.parentNode.className += " active";
}

Read Mozilla's official documentation to know more about getting the current target of an event and it's compatibility with different web browsers.


Algorithms and Data Structures

Queues & Stacks

Published on May 30th, 2020


Let's look at the differences between the two data structures:

  1. Queues: First-In First-Out
  2. Stacks: Last-In Last-Out

Queues

This follows a First-In First-Out processing order i.e. the first element added to a queue will be processed first. A queue should support two operations:

  • Enqueue
  • Dequeue

Enqueue

Adds the element to the tail of a queue. The tail position gets incremented.

Dequeue

Removes the first element of a queue i.e. the head element. Once, it's removed, the subsequent element becomes the new head element of the queue. The position of the new head element gets incremented and the previous one is assigned a negative integer like -1 or some garbage value.

Implementation of a standard queue using C++:


class Queue {
    private:
        int pos;
        vector<int> data;

    public:
        Queue() {
            pos = 0;
        }

        bool enqueue(int value) {
            data.push_back(value);
            return true;
        }

        bool dequeue() {
            if(isEmpty()){
                return false;
            }
            pos++;
            return true;
        }

        int front() {
            return data[pos];
        }

        bool isEmpty() {
            return pos >= data.size();
        }
}

In terms of memory management, a standard Queue is quite inefficient and incapable of handling dynamic memory.

Stacks

This follows a Last-In First-Out processing order i.e. the last element added to a queue will be the first to be removed. Just like queues, it has two simple operations:

  • Push
  • Pop

Push

Each element is pushed towards the end of the stack. Think of it as a card deck where you stack a card on top of another card.

Pop

It removes the most recent element i.e. the newly added element from the stack.

Implementation of a stack using C++:


class Stack {
    private:
        vector<int> data;
    public:
        void push(int value) {
            data.push_back(value);
        }

        bool isEmpty() {
            return data.empty();
        }

        int top() {
            return data.back();
        }

        bool pop() {
            if(!isEmpty()) {
                data.pop_back();
                return true;
            }
            else {
                return false;
            }
        }
}

Unlike queues, stacks are easier to implement and pretty efficient at managing dynamic memory.

Oh, if you ever get to use these, don't worry about implementing them, nearly all programming languages have their own implementations of stack and queue that comes with it's own standard library.



If you've ever come across this type of error when you're trying to fetch parameters of the current route:


Symfony\Component\Debug\Exception\FatalThrowableError: Call to member function parameters() on null

It's probably because the route doesn't exist, which is why it failed to call the parameters() function. It can be easily resolved by checking if the route exists before calling the function:


namespace App\Http\Controllers;
use Route;

class FooController extends Controller {
    public function __construct(Request $request){
        // insert code here...
    }

    public function foo(Request $request){
        $params = $request->route() ? Route::current()->parameters() : '';
        return $params;
    }
}

Although, the sample code above is to fetch parameters of the current route, you can apply this before calling any method from the Route class.

This works for version 5.2 and above.


jQuery

Select all elements except the current element

Published on May 28th, 2020


If you don't want the current element to be selected in an array of elements that belongs to same class or type, just use the .not() method like the example below:


$(".btn").click(function(){
    $(".btn").not(this).text('selected');
});

The above code will change the text for all buttons except the current element.


Terminal

Extract a specific folder from a zipped archive

Published on May 28th, 2020


First, you need to view what's inside of the .zip archive:


unzip -v archive.zip

Once, you've found the folder you wanted to extract, just type this:


unzip archive.zip "folder_to_extract/*" -d .


Bash

Rename extensions of multiple files

Published on May 27th, 2020


In this example, we're going to change a list of .txt files to .md files:


#!/bin/bash

shopt -s nullglob
files=($(ls -v *.txt))

for file in "${files[@]}"
do
    mv ${file} ${file}.md
done

You can use modify this script to rename any extension you want.


Terminal

Remove patterns from multiple files

Published on May 27th, 2020


If you wanted to remove a specific pattern in a list of files, like the ones below:


23_2020_03_01_article-three.md
22_2020_02_01_article-two.md
21_2020_01_01_article-one.md

You can simply do that using Regular Expressions and the rename tool:


rename 's/[0-9]+_[0-9]+_[0-9]+_[0-9]+_//' *.md

Now, the desired output should look like this:


article-three.md
article-two.md
article-one.md

This should come in handy if you're lazy to rename each file manually! :)


Terminal

Zip a file

Published on May 25th, 2020


This comes in handy especially whenever you want to download multiples files from a server or take backups.


zip [option] output_file input1 input2

For example: if you want to zip an entire directory with it's file contents, just do this:


zip -r myfiles.zip folder/


Linux

View hardware info

Published on May 25th, 2020


Want to check the specs of your system? Just type this:


lshw

Too long? Then type this for a shorter version:


lshw -short


Linux

View battery status

Published on May 25th, 2020


This comes in handy if you're using the terminal in full screen but still want to know your battery life. Just type the following:


upower -i /org/freedesktop/UPower/devices/battery_BAT0


Laravel

Symbolic storage link in shared hosting

Published on May 25th, 2020


If you're hosting a laravel project via cPanel, chances are that it could be a shared hosting server and that means you can't really use php artisan storage:link for this. But don't worry, there's another way to this. Just follow the steps below:

1. Create a symlink

In your public_html/public directory, remove the storage folder. Next, create a symlink.php file in your public_html directory and add the following code:


$targetFolder = $_SERVER['DOCUMENT_ROOT'].'/storage/app/public';
$linkedFolder = $_SERVER['DOCUMENT_ROOT'].'/public/storage';
symlink($targetFolder, $linkFolder);
echo "done";

2. Create a custom route to access storage

Alright, this is kind of a hack but it works extremely fine. Just add the following route in your routes/web.php file:


Route::get('/storage/anyfolder/{filename}', function($filename){
    // Your folder path
    $folder_path = storage_path('app/public/anyfolder/'.$filename);

    // check if the file exists
    if(!File::exists($folder_path)) {
        abort(404);
    }

    $file = File::get($folder_path);
    $type = File::mimeType($folder_path);

    $response = Response::make($file, 200);
    $response->header("Content-Type", $type);

    return $response;

Now, you can access your images or any other assets easily using:


asset('storage/anyfolder/'.$filename)

Hope this helps you out!


Laravel

Create a symbolic storage link

Published on May 25th, 2020


When using Laravel, the public directory is used for files that are publicly accessible. By default, it's stored in local and often stored in this storage/app/public directory. You can make it easily accessible by using the following command:


php artisan storage:link

Once, it has been created, you can use access those files using the public_path or asset methods.


echo public_path('images/sample_1.jpg');
echo asset('images/sample_2.jpg');


Terminal

Using SSH with a private key

Published on May 25th, 2020


Got a .pem key but don't know how to SSH to your server, just do this:


ssh -i name_of_key user@domain -p 22

BONUS: Convert .ppk to .pem key

Recently, I started working from home and as a programmer, it's pretty common to access the company server for development purposes.

Back in the office, I used to access it using PuTTY but now that I'm using a linux machine, I thought of accessing it via Terminal but there's a catch, I can't use .ppk key to access it.

So, I did a little research and figured that I can easily convert it using puttygen

Open up your terminal and type:


sudo apt install putty-tools

Now, convert your private key to PEM format:


puttygen yourprivate.ppk -O private-openssh -o your_new_key.pem

That's it and you're good to go!


Git

Set up a new repository

Published on May 25th, 2020


Are you new to using Git? Then this is for you.

1. Set up a Git account

Go to GitHub and create your account with your email address.

2. Create a repository

Just create a new project with whatever you wanted. For this, you can just create git-starter-repo or something like that.

3. Initialize git in your project directory

Now, go to your project directory and initialize git by doing the following:


git init

4. Add your files

Add your files to the repository by doing the following:


git add .

Or if you want add selected files:


git add file_1 file_2

5. Commit your changes

Before you push your changes, you need to write a message about what changes are done:


git commit -m "this is my first commit"

6. Link your project to the repo

Do the following to link your project to the repo that you've created in step 1:


git remote add origin https://github.com/youraccount/repositoryname.git

7. Push changes

You can decide which branch you wanted to push but initially, you'll have one branch, which is called master:


git push -u origin master

Or if you have an existing branch, just replace master with yourbranchname.

Hope that helps you out!


Laravel

Set up reCaptcha in Laravel

Published on May 25th, 2020


I mean, come on, you need to have a reCaptcha in your forms, no matter what.

Here are the steps:

1. Install using Composer


composer require anhskohbo/no-captcha

2. Add provider and alias to configuration

Open your config/app.php file and add this to your providers array:


Anhskohbo\NoCaptcha\NoCaptchaServiceProvider::class,

And this to your aliases array:


'NoCaptcha' => Anhskohbo\NoCaptcha\Facades\NoCaptcha::class,

3. Publish configuration


php artisan vendor:publish --provider="Anhskohbo\NoCaptcha\NoCaptchaServiceProvider"

4. Add sitekey and secret key to .env file

Open your .env file and add this:


NOCAPTCHA_SITEKEY=yoursitekey
NOCAPTCHA_SECRET=yoursecret

How to use it?

Now, you can use it in your validator using like this:


$validate = Validator::make(Input::all(),[
    'g-recaptcha-response' => 'required|captcha'
]);


VIM

Save a file

Published on May 25th, 2020


Want to save your work? Type :w

Type :wq! to save your file and quit VIM at the same time.


VIM

Quit VIM

Published on May 25th, 2020


One of the most infamous issues that new users of VIM faces when using it for the first time. Press :q to quit VIM

If you've worked on a file and want to save and quit? Just type :wq!.

I hope that solved your quitting issue with VIM.


VIM

Insert mode

Published on May 25th, 2020


I get it, a lot of people are confused on how to start typing on VIM. All you have to do is press the A key, the editor will be switched to insert mode.

Press ESC key to switch back to normal mode.


Terminal

Including and excluding files in zip

Published on May 25th, 2020


When zipping a directory or a bunch of files, there'll be a lot of stuff that you want to include and exclude.

To exclude a file:


zip -r files.zip . -x file_1 file_2

Alternatively, you can choose to include files:


zip -r files.zip . -i file_1 file_2


Terminal

Find a file by extension

Published on May 25th, 2020


This comes in handy whenever I want to look for files that exists with a specific extension in a computer or server:


find . -name "*.ext"

In addition, sometimes, you might want to look for a bunch of files with a specific extension but with matching keywords:


find .name "*.ext" | grep "keyword"

BONUS: Display list of files by extension with file sizes

Last month, I was trying to free up some space in our company server, so I realized that there were a lot of .zip files taking up a lot of space. So, I wrote a few commands to get me a list of zip files with their file sizes in sorting order into a .txt file:


find . -iname \*.zip -exec du -sh {} \; > zipfiles.txt
sort -rh zipfiles.txt > newfile.txt

You can .zip with any extension to suit your needs! :)


Terminal

Find files containing specific text

Published on May 25th, 2020


This helped me a lot whenever I'm in a remote server trying to find a keyword or specific text amongst a bunch of files.

This command will save you a lot of time:


grep -rwn [path] -e 'pattern'

  • r stands for recursion
  • n displays the line number
  • w matches the whole word

Refer to man find pages for more info.


Laravel

Integrate Excel into your Laravel project

Published on May 25th, 2020


Before you integrate Excel into your application, make sure your project meets the following requirements:

  • PHP v7.0 or greater
  • Laravel v5.5 or greater
  • PhpSpreadsheet v1.6 or greater

Download the package

Download the maatwebsite/excel package using Composer:


composer require maatwebsite/excel

Add it to service provider

By default, this will be done automatically when you're installing the package but if you want to do it yourself, add this in your config/app.php file:


<?php
...
'providers' => [
    ...
    Maatwebsite\Excel\ExcelServiceProvider::class,
],

...
'aliases' => [
    ...
    'Excel' => 'Maatwebsite\Excel\Facades\Excel::class',
],
?>

Publish your configuration

Last but not the least, run the vendor:publish command using artisan to publish your configuration:


php artisan vendor:publish -provider="Maatwebsite\Excel\ExcelServiceProvider"

Upon publishing, the config/excel.php configuration file will be created where you can make your changes.

Hope this helps you out!


VIM

Enable spellcheck

Published on May 25th, 2020


This can be useful when you're writing stuff, just do the following:


:set spellcheck=[lang]


VIM

Clear all lines

Published on May 25th, 2020


  1. Switch to normal mode by pressing ESC key
  2. Press gg and it will take you to first line of the file.
  3. Then type dG and it will clear all the lines from start to the end of the file.

Linux

Check Ubuntu version

Published on May 25th, 2020


Want to know the current version of your Ubuntu distro? Type this:


lsb_release -r


Git

Check branch status

Published on May 25th, 2020


Ever wondered if you've edited or committed anything in your project before pushing it to your repository, do this:


git status


Terminal

Check RAM and disk space

Published on May 25th, 2020


RAM space

Type the following command to view available memory in your system:


free -h

Disk space

Type the following command to view available disk space in your system:


df -h


Terminal

View the filesize in human-readable format

Published on May 25th, 2020


Wanted to view the size of a file in terminal but don't understand the number of bytes displayed? No worries, just type this command and it'll display the size of the in human-readable format:


du -sh filename.ext


Git

Checkout branch

Published on May 25th, 2020


Want to create a new branch in your project? Simple, just do this:


git checkout -b new_branch

By doing this, you'll automatically be shifted to a new branch of your project. To check which branch you're working on, type this:


git branch

And you should be able to see your current branch marked with a *:


master
* new_branch