Category: Code

Code, restores and preserves culture, gives young people the opportunity to create the world they dream, girls are able to express themselves, their potential and views.

As for me, I create a peaceful world by each line of code, I write.

In this section of my website, I will share learning challenges & insights, coding tips, step by step coding tutorials, scholarships and income opportunities.

I wish you a tireless reading.

  • When not to use a forEach loop in JavaScript

    A forEach loop is one of the most optimized JavaScript Higher-Order functions that make it one of the preferred functional programming languages.

    What is a Higher-Order function?

    It is a function which takes in another function (also called a callback) as a parameter or returns a function.

    What is a forEach in JavaScript?

    It a function used to iterate or loop over array elements. It accepts a callback back function which it calls for every element in the array in ascending order and an optional value to be used in the place of the this keyword while calling/invoking the callback. The forEach Higher-Order function returns undefined value.

    What is the Syntax?

    arr.forEach(callback(currentValue [, index [, array]])[, thisArg]);
    arr represents the array to be looped. Example of array below.
    let names = ['David','Harriet','Ronald','Laurence']; 

    or – the old way.

    let names = new Array('David','Harriet','Ronald','Laurence'); 

    callback – The function to be called on each element in the array. The callback can be a named function or anonymous function. The callback itself accepts 3 parameters of which 2 are optional. In fact, I personally use them and I think most programmers rarely use them too, speaking from experience of the code, I looked at from other developers.

    The 3 parameters of the callback are the currentValue, Index, and the array being looped.

    Use case 1: Using a named callback

    const CITIES = ['Kampala', 'Lagos', 'Nairobi','Cairo', 'Kigali' ];
    printCities = CITY => { console.log( CITY ); }
    CITIES.forEach( printCities );

    Use case 2: Using anonymous callback

    const COUNTRIES = ['Uganda','Kenya','Tanzania','Nigeria'];
    COUNTRIES.forEach( country => { console.log( country ) } );

    WHEN NOT TO USE THE forEach FUNCTION?

    How did I discover this? I was training a student and we were doing a practical project. We were mimicking a Single Page Application using vanilla JS. We had a JS object with one of the keys being users. The users key was holding an array of objects. Each user object has a name, email, and password for the user. Something like below.

    ...
    users: [
        {name: "David",email:"student1@school.ac",password:"password"},
        {name: "Ronald", email:"student2@school.ac", password:"password"}
    ];

    And we were picking user-provided username and password. Looping over the users’ array and comparing the user-provided details with the ones in the object. If we find the match we produce a notification that the user is found or not found if we don’t find a match.

    What happened is that whenever we found the match the alert notification telling us that we have found a match, appeared and various notifications, did too. The other were notifications were as many as the elements in the array which don’t match our search.

    We rushed in trying to use a break, return and continue statements but not offered the solution.

    This is when we found out that the forEach doesn’t support those statements. You can break out of the forEach loop. At leaste not as simple as using the break and return statements.

    Try to test it using the code below.

    students: [
        {name: "David",email:"student1@school.ac",password:"password"},
        {name: "Ronald", email:"student2@school.ac", password:"password"},
        {name: "Calvin", email:"student3@school.ac", password:"password"},
        {name: "Rachel", email:"student4@school.ac", password:"password"}
    ];
    //Looping the student to find a given match
    users.forEach( student => {
        if( student.name == 'David' && student.password == 'password') {
            alert( 'Student enrolled' );
        } else {
            alert( 'Student not found' );
        }
    });

    The code above and below this sentence will give you similar outputs, that is to say, four alerts, i.e. one, of Student found and three, of Student not found.

    students: [
        {name: "David",email:"student1@school.ac",password:"password"},
        {name: "Ronald", email:"student2@school.ac", password:"password"},
        {name: "Calvin", email:"student3@school.ac", password:"password"},
        {name: "Rachel", email:"student4@school.ac", password:"password"}
    ];
    //Looping the student to find a given match
    users.forEach( student => {
        if( student.name == 'David' && student.password == 'password') {
            alert( 'Student enrolled' );
            break;
            //return false;
        } else {
            alert( 'Student not found' );
        }
    });

    How can you achieve the result we wanted?

    At the moment I thought of two scenarios of which we practically tested one.

    a. Introduce a variable such as found and set it to true or false accordingly.

    Pros

    It solves the problem of producing many alerts at the user interface.

    Cons

    1. But it poses a con. What if the elements were a couple of hundreds or thousands or millions why waste memory looping all of them just to find a single match?
    2. More lines of code. Since you have to introduce a variable, you also have to check it and make a decision.

    Sample code below.

    let isFound = false
    students: [
        {name: "David",email:"student1@school.ac",password:"password"},
        {name: "Ronald", email:"student2@school.ac", password:"password"},
        {name: "Calvin", email:"student3@school.ac", password:"password"},
        {name: "Rachel", email:"student4@school.ac", password:"password"}
    ];
    //Looping the student to find a given match
    users.forEach( student => {
        if( student.name == 'David' && student.password == 'password') {
            isFound = true
        }
    });
    
    if(isFound) {
        console.log( 'Student enrolled' );
    } else {
        console.log( 'Student not found' );
    }

    2. Use the for ( element of elements ) loop.

    This solved our problem for our use case. I don’t see any cons with at the moment.

    students: [
        {name: "David",email:"student1@school.ac",password:"password"},
        {name: "Ronald", email:"student2@school.ac", password:"password"},
        {name: "Calvin", email:"student3@school.ac", password:"password"},
        {name: "Rachel", email:"student4@school.ac", password:"password"}
    ];
    //Looping the student to find a given match
    for( student of students ) {
        if( student.name == 'David' && student.password == 'password') {
            alert( 'Student enrolled' );
        } else {
            alert( 'Student not found' );
        }
    }
  • Trouble comparing dates in PHP

    The scenario.
    I’m building a custom tool which automates the curation of blogs from member bloggers’ feeds. These blogs must be fetched on a weekly basis because the intention is to make sure every member blogger, blogs at least once a week.
    Where to the feed URLs come from?
    Member joins by submitting a blog feed URL, which will save in the system manually at the moment.
    The system(bot) must;

    1. Retrieve the feed URLs from the database.
    2. The system should loop the URLS.
    3. Connect to each URL.
    4. Fetch one feed item(latest).
    5. Get the feed item date and compare it to the date of last Sunday. If the feed date is greater than the date of last Sunday.
    6. Connect to the database again and retrieve a blog item whose item title is similar to the feed item title. If a blog item similar to the feed item is returned, skip that feed item since we already have it and move to the next. Repeating steps 2 to 6.
    7. If the blog item similar to the feed item is not returned, insert it in our blog database to store it permanently.

    Tools used.
    First of all, I chose PHP programming language to accomplish the task. I would have chosen Python, however, my hosting environment doesn’t have python. Yet am also more experienced in PHP than Python.
    I also hard to extend WordPress so that I don’t have to build everything from scratch. Using WordPress will give me the opportunity to automate member sign up, log in and feed submission easier than if I used something different.
    I will eventually build a frontend interface for the system. This interface will enable the public readers to choose and read any blog of their choice as well as enable bloggers to sign up from any part of the world. Building a WordPress theme will be much easier than if I built everything from scratch.
    Alternative tools one could look at Joomla, Drupal and Django and many others.
    What have I built so far?
    So far I have built a WordPress plugin, with the following features.

    1. Automated Feed fetcher
    2. Shortcode which lists active bloggers. This is helpful for displaying member bloggers on the homepage or any page. Hence make it easy for readers to navigate blogs of any member(author)
    3. Shortcode for listing blogs. The intention of the system is to curate blogs from consistent bloggers around the world and make them accessible by consistent readers. This shortcode helps in displaying the blogs on the platform.

    Challenges

    1. Comparing dates.

    PHP has several inbuilt date functions and objects such as DataTime(), CreateDate() etc but they were not helpful. Sometimes they could function but they were never consistent. Luckily enough converting the date strings to time saved me after many trials and struggle.

    Solution

    $TimelastSunday = strtotime(‘last Sunday’);

    $TimeFeedItem = strtotime($feedItem->get_date(‘m-j-Y’));

    if($TimeFeedItem > $TimeLastSunday) {

    // Do the rest

    }

    Whoa! Whoa!
    Can’t wait to enable automated signing up, blog submission and attachment of categories and tags to the fetched/retrieved feeds.
    Thanks for reading until next time.

  • Hello world!

    Hello world!

    Though I have used the phrase to greet as a welcome to my personal website, I’m absolutely sure you have come across this phrase before, either in the code for programmers or the internet for the none programmers.

    But where does it come from? Today I would like to shade some light about this popular two words sentence, the Hello world!

    The history

    According to Wikipedia, the phrase was first used recently in 1967 in the BCPL programming language as is claimed by Jargon File. Click here to read the Hello world history on Wikipedia. When programmable computers were invented it gave programmers the opportunity to code and print outcomes on the user’s screen. Thus Hello world! got the chance.

    Usage

    Hello world! Is often used by programmers especially in the early stages of learning a programming language and to test the programming language’s ability to handle sentences technically known as strings. See examples below.

    Shell programming.

    #!bin/bash
    echo "Hello world!"

    C programming

    main( ) {
     printf("Hello world!");
    }

    Most programming languages which have the capability of showing characters on the screen, often use the code which introduces printing. So that the programmer can test their ability to use a particular programming language to print a message on the terminal(command line or cmd or console) or other user interfaces.

    However the phrase is not exclusive to programming/coding alone, everyone can use it.

  • The difference "" vs null vs 0

    The difference "" vs null vs 0

    Recently as I was conversing with my young friend, he looked at some of my code and wondered why I was using a zero or null or empty string (“” or ‘ ‘ ) instead of using one wherever I wanted.
    Programming is an interesting though weird or confusing discipline, especially to the novice things don’t mean a lot because most novices concentrate on the output than the efficiency and effectiveness of the output. For the mature programmers optimization is key, after all at the end of the day a user wants something working but requires less attention than something erroneous and slow.
    So let’s get to it. How does null, empty string and zero differ?
    Similarities
    First of all the similarity is of the three is that they are all values to variables and mostly used as the initial value of a variable.
    Second the empty string and null will usually output nothing if printed on the screen.
    Differences
    Differences might be defined differently per programming language.
    For example in Python there is no null but there is None which means the same as null in other programming languages.
    To find out the datatype of None and other values in python use the type( ) function e.g type( None ), will return NoneType data type in python. While in JavaScript we use typeof value to find out the Data type of a value stored in a variable. i.e. console.log( typeof null ) will return object as the data type of null.
    PHP 4+ we use gettype( ) function to find out the datatype of the value stored in the variable. For example gettype( null ) will return for NULL.
    If you are a JavaScript novice it’s good to pay much attention to null values since they are of data type object. For example find out how object data types are treated in JavaScript before you hit a nail in your foot.
     
    Almost all programming languages “” or ” is treated as a string and it occupies the space in memory of the size that is occupied by a string or char datatype. In fact in JavaScript if a value starts with ” even if it’s proceeded by a number or decimal it will be type cast to a string so that the resulting value will of data type string.
    So be careful initializing variables with ” especially if they will be used in mathematical expressions.
    In Java, Python and PHP 0 is treated as an integer whereas it’s treated as a number in JavaScript because in JavaScript integers and floats are number data types. I know most people might be wondering why not a Boolean?
    Though 0 or 1 might represent false/true they are not treated boolean data types.

    Why care?

    It’s always good to code what a programmer and fellow programmers understand to avoid spending time in refactoring than improving functionality and optimization.
    It’s also important to ship a software which will give more predictable results than not to avoid the users plucking hair out of their heads, assuming they’re wrong yet it’s the programmer is the calprit.
    DataTypes determine how big your program will be and how it nay handle memory, avoid confusing by planing to code rightfully from the beginning.
    Note: 
    This tutorial assumes you have some programming knowledge and some level of practice with the one or more of the programming languages cited in the tutorial.
    The tutorial is dedicated to Were Calvin a Ugandan African motion graphics designer and emerging front-end developer practicing at Gagawala Graphics limited.

  • How to set up a Hybrid Mobile App development environment!

    Have you ever wanted to develop mobile apps using web technologies i.e HTML, CSS and Javascript? In fact, you might have tried but failed along the way after failing to set up your computer for the task. It has happened to many others simply because coding and setting up developer environments are two different games which require different skills.
    In this post I have listing what you require and briefly suggest what you have to do to have each tool installed on your Windows computer. Though guideline is eccentric to Windows Operating Systems, it’s transferable to Mac OS and Linux.
    Let’s get started!

    • NODE.JS

    Get Node.js

    Install Node.js and add it to PATH environment variable ). Confirm installation by running $node –version at command line. I prefer using Windows shell instead of CMD. Because Windows shell executes some linux commands such as $ls.

    • GIT

    Install Git with default settings.

    • CORDOVA

    Installation

    In Git Bash or Windows Shell execute the command below

    $npm install -g cordava

    Confirm installation by running

    $cordova –version

    • JAVA

      • Install Java Development Kit (JDK). From Oracle’s website download the Java Standard Edition (Java SE). Add the JDK’s installation path to the PATH environment variables. Usually the location is c:\Program Files\Java\jdk version\bin. Create a JAVA_HOME if it doesn’t exist, setting it’s value to c:\Program Files\Java\jdk version To confirm if all is well run javac -version.
    • APACHE ANT

      • Install Apache ANT. (This is the build system for Java). I kept on failing until I discovered this was the missing piece in the puzzle. Search for it on google, download the zip file and unzip it whenever you want, noting the location. Proceed by adding the Apache ANT bin directory e.g c:\apache-ant\bin to the PATH environment variable and creating a ANT_HOME variable to which you assign the Apache ANT directory. e.g. c:\apache-ant. Now in Git Bash or command line tool of your choice run $ant -version
    • ANDROID

      • Download and Install Android SDK by downloading Android Studio. Before we could install the Android SDK alone but it seems impossible now a days, maybe you or I should do more research about this. Add the Android SDK tools and the Android Platform tools to the path variable. Usually these are located at the SDK installation directory\tools and SDK installation directory\platform-tools.
      • Launch the SDK manager by running the command $android use may use it for downloading additional sdk, platform tools etc.
    • TEST ENVIRONMENT

      •  In command line of your choice. Run $adb -version.

    Navigate to a directory of your choice and issue the cordava app creation command. i.e $cordova create app_directory com.domain.app AppTitle

      • Add android platforms to your app. At command line change directory to app_directory by running.
        • $cd app_directory
        • $cordova platform add android
      • Connect your phone will developer options and usb debugging are turned on.
        • $cordova run android.
      • If phone does work for some reason you can try to install Universal Adb drivers or view your apps in the browser by running $cordova run browser.

    Conclusion.

    Knowing how to code is a good task, setting up the developer environment is another thing.
     
     
     

  • How to remove Woocommerce sidebar from front-page using hooks

    Woocommerce is one of the most popular plugins for WordPress because it’s used by anyone wants to setup online shop without the need writing a single line of code.
    Themes are one of the notable features that come with Woocommerce out of box. It comes with a default theme as well as you can download many out from WordPress.org theme repository and many theme stores online. In fact most of those themes on the WordPress repository and theme stores are fully compatible with WordPress.
    Therefore this post is targeting people with custom themes made by themselves or got from somewhere but haven’t come with Woocommerce support.
    Let’s start right away!
    Go to Appearance -> Edit after logging in to the WordPress Dashboard where Woocommerce is installed.
    Look for the functions.php file. For experienced WordPress coders you can create your own site specific plugin. This is where you can add custom code.
    Let’s remove a Woocommerce sidebar action.
    Use the code below in your themes functions.php or site specific plugin.
    <?php
    remove_action( ‘woocommerce_sidebar’, ‘woocommerce_get_sidebar’, 10 );
    Save and reload the front-end of your shop page.
    As simple as that.
     
     
     

  • How to create Web Applications using WordPress! Part 1

    WordPress powers over 24million websites online, and people are leveraging it’s simplistic to create amazingly life changing web applications, without spending much time on coding. In article I will teach you how to create Web Applications using WordPress, of course it will involve some coding but it will be easier than any code you have come across.
    Assuming you know how to install WordPress, on your host or computer, install it and login afterwards.
    Navigate to the plugins WordPress dashboard and install a plugin called Advanced Custom Fields and Custom Post Type UI
    After installing them follow part 2 here.
     
     

  • Simplest WordPress plugins creation, Part 1.

    Simplest WordPress plugins creation, Part 1.

    There is no question WordPress is the most popular Content Management System, in the world of CMS possibly because of it’s simplistic and the free blog platform wordpress.com and support for several features; theming, plugins, widgets, media management and more being the most notable. I personally love SEO support that it comes with out of box.

    Plugins-available-in-Wordpress-dot-org
    WordPress.org has over 45k plugins!

    Actually wordpress.org has ove 40,000 plugins and more are coming in. So why do I teach someone who to make a plugin? Simply because you may have an idea that is not yet executed though it could be useful to you and other WordPress users. So if you read this short tutorial and other parts, you will be able to do that whenever you want.
    Tip: WordPress plugins can be monetized hence make some income for you.

    Prerequisite knowledge you should have/know.

    It’s important to check yourself for the technologies below.

    • HTML, CSS & PHP knowledge (Must)
    • Javascript/Jquery/Angular knowledge is a plus
    • A text editor such as Notepad++, Brackets & Sublime, etc.
    • A fully working WordPress installation, running on a local/private server. Testing on local(development) set up, is recommended in order not harm the website the visitors are viewing.

    Step 1. In a folder of your choice, create a main PHP file of your plugin and name it. e.g my_plugin.php
    For preview purposes, I suggest to create a folder, residing in the WordPress plugin folder.
    Which is located at /wordpress_install_folder/wp-content/plugins
    If you have xampp installed on your development machine, you have this folder in the path; c:/xampp/htdocs/wordpress_install_folder/wp-content/plugins
    Step 2: Add plugin code to the file

    a.Tell WordPress about your Plugin

    A WordPress plugin begins with code that describes the plugin, they code is so helpful for installation, uninstall and management of the plugin. It also makes extending the plugin or updating it’s code easier. Such details include:- Plugin Name, Description, Tags, Author, Version, Author URI and etc. As a general rule of thumb this code goes at the start of the file, enclosed in comments.
    Example:
    /*
    Plugin Name: My Plugin
    Author: awebdesigner
    Author URI: http://fictiontoactual.wordpress.com
    Description: My Plugin is a cool plugin and it will print the date at the footer of website. For illustration purposes.
    Version: 0.0.1
    */
    b. Add code to do the real thing
    add_action(‘wp_footer’,’print_date’);
    function print_date(){
    echo date(‘Y’);
    }
    Step 3: Compress and upload to server.
    Let see it in action. Compress the plugin and upload it to your site.
    Notice: Since WordPress is coded using PHP, it’s plugins supports everything PHP supports, includes, services, MYSQL etc. Don’t limit yourself.
    What’s next? Improving the functionality of our WordPress Plugin by adding to the Admin Menu, integrating a form which saves something and display to the users.
     

Verified by MonsterInsights