# 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 51 short articles.

Hope you enjoy learning along with me! 😄

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

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



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.

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!

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!

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! 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! 😄 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. 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! 😁

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.

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.

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;
}



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 😃

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: 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. 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. 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. 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. 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 = "";

return [
[
'title' => 'Item 1',
],
[
'title' => 'Item 2',
'child_items' => [
[
'title' => 'Item 2.1',
],
[
'title' => 'Item 2.2',
],
]
],
[
'title' => 'Item 3',
],
[
'title' => 'Item 4',
],
];
}

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! 😊 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.

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.

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 .



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.

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



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:

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:





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.

## 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







Or if you want add selected files:





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


git commit -m "this is my first commit"



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





## 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





## 2. Add provider and alias to configuration

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





And this to your aliases array:





## 3. Publish configuration





## 4. Add sitekey and secret key to .env file

Open your .env file and add this:





## How to use it?

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


\$validate = Validator::make(Input::all(),[
]);



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.

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! :)

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.

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



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