megacolorboy

Abdush Shakoor's Weblog

Writings, experiments & ideas.

Built a new static site generator using Python 3.7

Thought of giving it some new upgrades and finally decided to open-source it.

Since 2019, I always used a custom static site generator for the website. The previous one was written in Python 2.7 but ever since Python decided to sunset it, I decided to rewrite it using Python 3.7.

Unlike the previous one, it's quite flexible and I thought of giving it some new features that would help me maintain it with ease.

The new features I have added are:

  • A neat CLI to build the entire site or certain parts of the website
  • Able to switch between different templates
  • Archive mode
  • Pagination
  • Generates RSS Feeds and JSON files

Why rewrite it again?

Over the past few months, I didn't really maintain my blog and when I visited the old codebase, I realized it wasn't flexible and it didn't have many features and it was slow, too.

Recently, I got new ideas of building different sections for the website and thus, is why I had the motivation to rewrite everything and make it modular and flexible enough to build a powerful yet simple custom static site generator.

Have a look

I have decided to open-source my static site generator on my GitHub repository and I'm having plans of writing a new documentation for it, so that if people are interested, they could contribute or use it for their own personal uses.

Conclusion

If you've been following my blog posts, you may know that I have a knack of displaying JavaScript widgets on some of my previous blog posts. Well, I've decided to rewrite all of those widgets, one-by-one, using ReactJS and hopefully, write more tutorials for each of them.

Hope you liked reading this article.

Do we really need to use pointers?

Did a little digging on whether it's useful to make use of pointers in your application

The topic about pointers isn't new as you're probably introduced to this concept in your first computer science class. I started learning Go and once again, I came across the concept of using Pointers and wanted to finally understand, why are they used and do we really need to use it?

Frankly, I don't really remember using pointers when I was developing web applications in PHP and JavaScript but it was quite a refresher to get back on track again.

Well, what is a pointer?

In it's basic form, a pointer is a variable that contains the memory address of another variable.

For example, you have a variable named x that contains some data, in this case, we'll store an integer:

package main

import "fmt"

func main() {
    x := 10
    fmt.Println(x) // prints 10
}

The code above prints the variable x by referring to it's name. We can do the same using pointers by referring to it's memory address via another variable that points to variable x.

To do this, we must use & operator to get the address and * to return the value stored in the address of variable x like this:

package main

import "fmt"

func main() {
    x := 10
    p := &x
    fmt.Println(x)   // prints 10
    fmt.Println(*p)  // also, prints 10
}

Hmm, that was pretty straight forward.

So, why was it created?

In the modern era, most high-level programming languages are capable of handling memory allocation (like Java or C#), automatically.

But when C was developed, computers weren't as powerful as today but that also meant the programmers must create systems that made use of memory and speed, efficiently. Which is why some tasks do require it when programming low-level embedded systems or microcontrollers.

Why use them?

Whenever you pass a variable to a function, you're basically creating a copy of the variable. But if you're using pointers, you just have to pass the address of the variable and in most cases, a pointer is much smaller in size than the value being pointed at.

It allows you share data and it's quite appropriate when it comes to modifying the data being passed to it.

To some extent, it might seem efficient but there are some tradeoffs, when you're going to talk about optimization.

Do pointers really optimize your application?

I was thinking if pointers are used to optimize applications, I mean, you don't have to duplicate data and it saves memory, so why not?

Turns out that there are a few points that I came across:

  1. Accessing values can use up memory though not so much but it can add up.
  2. Data will be placed on top of heap stack which increases the memory overhead and can be cleaned up the garbage collector.

Most programmers tend to avoid using it in order to make their codebase less complex and reduce the increased work for the garbage collector.

Apart from that, there are some concerns when it comes to the security of the application implying that it could be unsafe when using pointers.

Takeaway

Pointers are useful but don't think of using it, blindly, by assuming that it might give you a boost in performance.

Hope you found this article useful!

Readings

Launched a microblog site

A tiny experiment to see how it could improve my writing productivity.

Ever since I've been working from home (due to COVID19 pandemic), I hardly find time to write any posts on my blog and I felt that it was counter-productive whenever I wanted to start a new one after a long time.

And then, I came across this trend of TIL a.k.a Today I Learned on GitHub and one of my favorite ones is written by Josh Branchaud.

What is this about?

Unlike writing long articles, which takes a lot of time, I believe that by having a microblog and writing short articles could help improve my productivity in writing.

So, I thought of sharing whatever I have learned on a day-to-day basis and accumulate this knowledge in a "repository" where anyone could learn from, thus is why I started this microblog. Besides, as of writing this article, I wrote 25 short articles in a month.

What kind of articles can we expect?

It'd be wonderful to say that I can talk about anything over here but currently, I'm restricting it to Computer Science, Mathematics, Software Engineering and Digital Design.

So what about your main blog?

Oh, I'm not ignoring it! The main blog will be there but now that I have segregated it, it'll allow me to take some time to plan and write content-heavy articles. There'll be more articles coming in a few months time.

Click here to view my microblog and let me know what you think about it! 😄

Stay tuned for more!

Writing a book on how to build ReactJS applications

I'm challenging myself to write a book on how to build simple applications using ReactJS

Over the past few months, I've been spending some of my free time to learn ReactJS and I've got to say, I really like it and got a hang of it after lots of trials and errors.

Just to make it clear, I didn't become a ReactJS expert or something but I figured that writing a book on something that you've learnt would help you understand the material much more deeper.

And since I do believe in it, I decided to challenge myself to write a book on it.

What's the aim of the book?

I aim to cover the fundamentals and concepts of ReactJS using a progressive and an example-driven approach. You know like on how to write reusable UI components, handle user events and interactions and managing state and props of a component.

By the end of this book, the reader will have solid understanding of React's concepts and be able to build cool applications using it.

When's it going to be released?

Honestly, I didn't plan on the size of the book yet but the practical content for it i.e. the actual code and applications are ready. I aim to release it somewhere around late April 2020.

Are you planning to monetize it?

Umm, nope! I believe that knowledge should be accessible for everyone and I plan on making the book open source, so that it can get updated as per the latest changes.

Conclusion

I know it's a short article but I feel like I wanted to challenge myself with a small goal for this year.

Let's see how it goes!

Using Laravel events and listeners in your application

Sharing my experiences of using events and listeners in my Laravel application.

Recently, I have started learning Laravel and now, I'm building an application for my new company using this amazing framework.

My senior developer was curious and thought of having a conversation with me that went like this:

Senior dev: Hmm, can I have a look at your code?

Me: Oh sure, here take a look.

Senior: (Goes through project file structure)

Senior: So, have you ever thought of using events in your application?

Me: Yeah, I wrote a custom JavaScript file to handle and fire events on the client-side like validating the forms and passing async requests to the server.

Senior: Hmm, that's okay but I'm talking using events in Laravel.

At this point, I was pretty clueless and I didn't know what the heck was going on. Events in PHP? I mean, I know about it in JavaScript because of it's event-driven architecture that we are all familiar with. But in PHP? I didn't know that.

Still confused, he proceeds to explain about it's concepts in an abstract manner and thanks to him, it induced my curiosity by asking myself: What's the deal in between using events over function calls using a route on a standard controller?

In today's article, I'll be talking about why and when to use events over function calls using Laravel in your application.

What's an event?

An event is a piece of reusable logic stored somewhere in your application that has a set of listeners waiting to be executed, if triggered.

Let's say, you have a simple CRUD application that involves user registration. Whenever a user registers, you may want to perform certain actions, such as:

  • Adding them into your mailing list
  • Confirmation of account

You can add more but this is just to give you an idea. Let's see take a look at two different approaches:

  1. Functional
  2. Events and Listeners

Functional

If you're using an MVC framework (Laravel, in our case), you'd do this in a controller with a bunch of methods like so:

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\User;

class UserController extends Controller {
    public function index() {
        // insert code to view users page
    }

    public function create(Request $request) {
        $arr = [
            'username' => $request->username,
            'email' => $request->email,
            'password' => bcrypt('something')
        ];

        $user = User::create($arr);

        $this->sendConfirmationEmail($user);
        $this->subscribeToMailingList($user);
    }

    // Send confirmation email to user
    private function sendConfirmationEmail($user) {
        // insert code
    }

    // Subscribe user to mailing list
    private function subscribeToMailingList($user) {
        // insert code
    }
}
?>

This is approach is self-contained and simple to follow but you're also adding in a lot of responsibility to your controller.

Not only that, what if the user wants to register from another place in your application, in that case, you'll have to duplicate your logic in multiple places.

Events and Listeners

Using this approach, you can split this into Event and Listener files in your application.

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\User;

class UserController extends Controller {
    public function index() {
        // insert code to view users page
    }

    public function create(Request $request) {
        $arr = [
            'username' => $request->username,
            'email' => $request->email,
            'password' => bcrypt('something')
        ];

        $user = User::create($arr);

        // Emit event
        event(new UserRegistered($user));
    }
}
?>

This is how your UserRegistered event would look like:

<?php
namespace App\Events;

use Illuminate\Queue\SerializeModels;
use App\User;

class UserRegistered {
    use SerializesModels;

    public $user;

    public function __construct(User $user) {
        $this->user = $user;
    }
}
?>

And this is how your SendConfirmationEmail listener would look like:

<?php
namespace App\Listeners;

use App\Events\UserRegistered;

class SendConfirmationEmail {

    public function __construct(User $user) {
        // insert code
    }

    public function handle(UserRegister $event) {
        // insert code
    }
}
?>

Using this approach, you can use the UserRegistered event anywhere you wanted in your application. No matter what happens, it will trigger the same actions as it was intended to do so. If you want to add a new functionality, create a new listener and register it with the event in your EventServiceProvider file like this:

<?php
protected $listen = [
    'App\Events\UserRegistered' => [
    'App\Listeners\SendConfirmationEmail',
    ],
];
?>

If you follow this approach, your logic complexity is toned down and the controller will have less responsibility.

Why use events and listeners over function calls?

Just like this answer that I found on StackOverflow question regarding events and listeners over calling functions:

You might not be in control of the code that's doing the calling. Or even if you are, you don't want to introduce dependencies into that code.

Think about it, what if you built an API or library that you want people to use but don't want them to modify the source code. Instead, you could provide a documentation that states specific events are raised under specific circumstances, in turn, they can write code that responds to such events.

I'm sure that there are more examples as to where this methodology might be applied.

When to use it?

Truth be told, it depends. If you have a simple application, then a functional approach is all you need but it's a larger and more complicated application, using Events and Listeners can be a better option.

Conclusion

Please note, I'm not an expert at this topic as I'm still learning and I thought of sharing what I had learnt. If you have any suggestions or thoughts, please share it with me on Twitter or send me a message to my inbox.

Hope you liked reading this article.

Stay tuned for more.

Extras

The Circle Packing Algorithm

Implemented a mathematically beautiful generative pattern that looks deceivingly complex to the human.

Beautiful, isn't it? It might look complex but it's mathematically quite impressive. Making this pattern wasn't hard but it definitely took a lot of trial and error to get it right and honestly, I don't really know if it's this is the most efficient way to generate this pattern.

This article isn't a tutorial but rather, I'll be talking about the algorithm itself. However, you can check out the source code in my GitHub repository.

How it works?

In order to achieve that "stacked" effect, there are two things to keep in mind:

  1. Generate circles with a random radius
  2. Look for collisions with other circles

The logic is quite similar to the Overlapping Rectangles problem except this is done with circles.

Generate circles with dynamic radius

This method will help generate valid circles with a random radius. Circles that don't overlap or collide with other circles are considered to be valid.

// Generate a valid circle
const generateCircle = () => {
    let newCircle;
    let isValidCircle = false;

    for(let i=0; i<attempts; i++) {
        newCircle = {
            x: Math.floor(Math.random() * width),
            y: Math.floor(Math.random() * width),
            radius: minRadius
        };

        if(checkForCollision(newCircle)) {
            continue;
        }
        else {
            isValidCircle = true;
            break;
        }
    }

    if(!isValidCircle) { return; }

    for(let i=minRadius; i<=maxRadius; i++) {
        newCircle.radius = i;
        if(checkForCollision(newCircle)) {
            newCircle.radius--;
            break;
        }
    }

    circles.push(newCircle);
    drawCircleOnCanvas(context, newCircle, colors[Math.floor(Math.random() * colors.length)]);
}

Look for collision with other circles

Thanks to some online research, I was able implement the Euclidean Distance equation that helped with calculating the distances between each circle and detect for collisions. Along with that, I also found another article on Touching Circles that was quite useful.

These are the formulas used to detect the collision:

  1. Find the distance between two centres \[ AB = \sqrt{ (x2 - x1)^2 - (y2 - y1)^2} \]

  2. Calculate the radii of both circles. \[R = r1 + r2\]

If the radii is greater than or equal to the euclidean distance of both circles, then it's a valid circle with no collisions.

// Check for collision in a canvas
const checkForCollision = (newCircle) => {

    let x2 = newCircle.x;
    let y2 = newCircle.y;
    let r2 = newCircle.radius;


    // Determine the euclidean distance between two circle
    // using Pythagorean Theorem.

    // Refer to: 
    // https://en.wikipedia.org/wiki/Euclidean_distance

    for(let i=0; i<circles.length; i++) {

        let otherCircle = circles[i];
        let r1 = otherCircle.radius;
        let x1 = otherCircle.x;
        let y1 = otherCircle.y;
        let xx = ((x2 - x1) * (x2 - x1));
        let yy = ((y2 - y1) * (y2 - y1));
        let radii = r2 + r1;
        let euclidDistance = Math.sqrt(xx + yy);

        if(radii >= euclidDistance) {
            return true;
        }
    }

    // Check collision on top
    if(x2 + r2 >= width || 
        x2 - r2 <= 0) {
        return true;
    }

    // Check collision on bottom
    if(y2 + r2 >= width || 
        y2 - r2 <= 0) {
        return true;
    }

    //else return false
    return false;
}

Conclusion

I'm thinking of implementing more generative patterns like Triangular Mesh and Piet Mondrian's Red, Blue and Yellow composition.

Hope you liked reading this article.

Stay tuned for more!

Deploy your Laravel app on Heroku

Learn how to deploy your Laravel application along with a database on Heroku.

In my previous article, I talked about how to setup your environment for developing your Laravel applications. Today, I'll be talking about deploying your application along with a database on Heroku.

I wrote a simple CRUD application using Laravel but didn't understand on how to host it. I tried to host it on free shared hosting service but apparently, most of them don't support PHP system calls like proc_open(). However, if it was a VPS hosting service, it's supported but ain't nobody got time for shelling out cash for a test drive.

As an alternative, I went on google and discovered that Heroku does support my requirements and it worked flawlessly, which is why I thought of sharing this information to others as well.

If you're a developer who's at the early stages of learning Laravel (like me 😆), then this article is for you.

Prerequisites

You'll be doing some minor configurations, so you should be fine as long as you have a stable internet connection, familiar with using the CLI (Command Line Interface) and have some PHP knowledge.

If you're a Windows user, please Git for Windows. Else, if you're a Linux or macOS user, you should be fine.

How to deploy?

You can ignore the first two steps if you already know about Heroku and how to work with it but please follow the rest of the steps:

  1. Install Heroku
  2. Create a Heroku repository
  3. Define Procfile
  4. Push Laravel app to repository
  5. Add configuration variables
  6. Setup your database

Install Heroku CLI

You can install this directly from the command line by typing the following:

sudo snap install heroku --classic

Create a Heroku repository

If you don't have a Heroku account yet, create an account now and once you're done with that, type the following:

heroku login

Follow the login instructions from the command line prompt, fill in your login credentials and you'll be in!

Once, you're done with that, create a repository by doing the following:

heroku create

In a few seconds, you'll get a randomly generated domain address, which is the link to your Heroku repository. If you can't remember the link, it's fine, you can make changes to it in your Heroku account.

Define Procfile

In case, you don't know what's a Procfile, it's a file that specifies the commands that needs to be executed by the application on startup. You can declare a variety of process types, click here to learn more.

Since our application is PHP based, we need to add some specific command that selects the server on boot, I chose Apache server for this project:

cd your_laravel_project
touch Procfile
echo "web: vendor/bin/heroku-php-apache2 web/" > Procfile

Push Laravel app to repository

It's similar to pushing your code into your GitHub, except this time, it's your Heroku repository. Type the following in your command line:

git add .
git commit -m "pushing application to repo"
git push heroku master

To check if your application is launched, type the following:

heroku open

At this stage, you might face Error 500, that's normal because we'll take care of that in the next step.

Configure your Heroku environment

We need to add some config variables that changes the way your app behaves. So, let's start adding it:

heroku config:set APP_DEBUG=true
heroku config:set APP_KEY=yourlaravelapplicationkey
heroku config:set APP_URL=https://yourwebsite.herokuapp.com
heroku config:set REDIRECT_HTTPS=true

In this configuration, you have done the following: - Enabled debug mode - Set your Laravel application's base64 encrypted key - The website's URL - Force HTTPS redirect (Useful, when you're calling external assets that uses HTTPS protocol)

Note: You can find your APP_KEY in your .env file that's found in your project directory.

Setup your database

Initially, I built the database on MySQL but I later learnt that Heroku gives a free PostgreSQL starter database. I've never tried PostgreSQL before but it's quite similar to MySQL, so you shouldn't worry about your schema as Laravel supports PostgreSQL and MySQL databases by default.

Type the following in the command line:

heroku addons:create heroku-postgresql:hobby-dev

This will create a PostgreSQL database and sets a DATABASE_URL, which contains the username and password to the database. To check it, type the following:

heroku config

Now, go to your project directory and open the config/database.php file and add the following:

<?php
// Place these variables above
$url = parse_url(getenv("DATABASE_URL"));
$host = $url["host"]??null;
$username = $url["user"]??null;
$password = $url["pass"]??null;
$database = substr($url["path"], 1)??null;

// Replace the default connection
'default' => env('DB_CONNECTION', 'pgsql_prod'),

// Under the connections attribute, create a new connection called 'pgsql_prod'
'pgsql_production' => [
    'driver' => 'pgsql',
    'host' => $host,
    'database' => $database,
    'username' => $username,
    'password' => $password,
    'charset' => 'utf-8',
    'prefix' => '',
    'schema' => 'public',
],
?>

Push the new changes to your repository:

git add .
git commit -m "configured database"
git push heroku master

One last step, we need to create the tables from your schema, so type the following:

heroku run php /app/artisan migrate --seed

Follow the command line prompt and voila, you have successfully deployed your Laravel application with a database on Heroku.

Conclusion

Well, I hope you found this article really useful especially if you're a beginner. If you do find this useful, please share it with others too!

Stay tuned for more!

Getting started with Laravel Homestead

Wanted to install Laravel but scared of configuring files on your host operating system? This article is for you.

I started learning Laravel and I thought of writing a small tutorial on how to setup your own local development environment for Laravel projects with Laravel Homestead and Vagrant.

What is Laravel Homestead?

It's an official package from Laravel that provides a neat development environment that comes along with a Vagrant box that has pre-installed software. Read their documentation to know more about it.

Note: The examples of this tutorial are applicable to any developer that uses any UNIX-based operating systems such as macOS or any Linux distributions like Ubuntu. If you're using Windows, I recommend that you install Git for Windows on your local machine.

Prerequisites

The only requirement for this tutorial is that you should be familiar with using the command-line interface.

Install VirtualBox and Vagrant

VirtualBox is the software used to run a virtual machine with a sandbox operating system within your own computer.

Vagrant is a software that's used to manage a development environment. Through the command-line, you can perform any operation such as installing an OS, configuration, deployment and so on.

You can install VirtualBox and Vagrant via the command-line:

sudo apt install virtualbox vagrant

Once you're done installing them, you should add the laravel/homestead box to your Vagrant installation using the following command:

vagrant box add laravel/homestead

To check if it has been installed, use the following command:

vagrant box list | grep "homestead"

Using VirtualBox and Vagrant allows you to simulate your Laravel development environment without messing up any configurations on your hosting system. Even if you did, no worries, Vagrant boxes are disposable, so you can destroy and create a new box again in minutes.

Download Laravel Homestead

You can install Homestead by cloning it's repository onto your local machine by typing the following command:

git clone https://github.com/laravel/homestead.git ~/projects/Homestead

Generate configuration file

Once you're done cloning the repository, go inside the projects/Homestead directory and run the init.sh or init.bat (for Windows) to create the Homestead.yaml configuration file:

cd projects/Homestead
bash init.sh

Open the default Homestead.yaml file and make the following changes:

---
ip: "192.168.10.10"
memory: 2048
cpus: 2
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: ~/projects/code
      to: /home/vagrant/projects/code

sites:
    - map: homestead.test
      to: /home/vagrant/projects/code/public

databases:
    - homestead

Generate SSH key

The documentation for Laravel Homestead doesn't really talk about generating SSH keys used to access the Vagrant box. Use the following command to generate it using ssh-keygen on the command-line:

ssh-keygen -t rsa -C "root@homestead"

Map the project's shared folder

Make sure that you have created a folder named code in your projects directory. This folder will keep all of your Laravel project files in sync between your local machine and Homestead environment.

Installing Laravel

Time to install Laravel into your virtual machine. So, get switch on your virtual machine by doing the following in the command-line:

vagrant up

As you're switching it on for the first time, depending on your internet connection, it might take somewhere around 10-20 minutes to getting it running but it'll be fine afterwards.

Alright, login to your Vagrant machine by doing the following the command-line:

vagrant ssh

Once you're in, go to your code directory and type the following in the command-line:

composer global require laravel/installer

Create a new project

Now, it's time to create a new Laravel project by simply typing the following command:

laravel new projectname

It'll take some time to generate the necessary files and boilerplate code and after that, you're good to go!

Oh, you should be able to see the Laravel project files in your local machine as it's synced with the virtual machine and local machine. That means, any changes made on either machines will be synced and reflected on both ends.

Map your hosts file

One last step, make sure you map your project's test domain onto your local machine's hosts file.

Open a text-editor of your choice and do the following in the etc/hosts file:

127.0.0.1   localhost
::1         localhost

# Add this line (Note: It can be any URL)
127.0.0.1   homestead.test

Now, go to your browser and type homestead.test and you should be able to see your Laravel project's sample layout.

Conclusion

As mentioned, in the beginning of this article, I have started to learn Laravel and I'll be building some projects and writing out my experiences about it soon.

I hope you liked reading this article and please share it with others if you do find this tutorial useful.

Stay tuned for more!