Showing posts from January, 2020

String repeat in JavaScript

String repeat is a function that can be used to multiply a string for a given number of times, its a feature that is closely related to string multiplication operator in Python programming language, as compared to Python's syntax;
("String") * (number of times to repeat) "A" * 3
// returns "AAA"
Something similar may be archived using string repeat function in JavaScript as;
("String").repeat(number Of times to repeat)
For example to triple "A" you can do as;
Practical example is with lyrics;
const part = "i feel you, "
const lyrics = part.repeat(4) + " A, B, C" // "i feel you, i feel you, i feel you, i feel you, A, B, C"
Further reading;
String.prototype.repeat() MDN

Lambadas in kotlin programming language

Lambadas are similar to arrow functions in JavaScript they are a short alternative method to declare functions in kotlin programing language, You can create a function expression as;
val double = {num: Int -> num * 2} val cube = { num: Int -> num * num * num} val square = {num: Int ->
    val product = num * num
    product }
The last expression in a lambada is considered as a return value; Parameters can be omitted, for a single parameter lambada the value of the omitted parameter is in the variable 'it'

Rest operator in JavaScript

Rest operator is similar to spread operator its an es6 feature that allows converting arguments to an array of values;

Syntax of spread operator is as follows;

function spr(...params) { console.log(params) } spr(1,2,3) // [1, 2, 3] You can use rest operator among other arguments

function sprr(args, ...params) { console.log(params) } spr('foo', 1, 2, 3) // [1, 2, 3] More information:
Restparameters MDN

JavaScript String includes function

String includes is a function introduced to JavaScript in Escmascript 'es6' that returns a boolean true , or false based on the evaluation whether or not a string contains the string passed as an argument to the function For example;

const str = "John swana" str.includes('John') // true str.includes('duke') // false Running string includes testing whether 'John swana' includes John returns trues as it's a fact.

Running the same string against duke returns false duke is not part of the string 'str'

comparison on var, let and const variable declaration

let, const and var are keywords used for variable declarations in JavaScript programming language,const and let were newly introduced to the programming language in Escmascript es6 or es2016.Declaration keywords
the syntax of declaring a variable using let keyword is done as;let {variable name} = valuefor const it's done as;const {variable name} = valuesimilarly with var;var {variable name} = valueScope for 'let' and 'const' variables
let and const declared variables are block scoped that means values assigned remain within the block of assignment;
take for instance;if(true) {
   const declaration = "declared"
}console.log(typeof declaration)
// undefinedvalues remain accessible only within the if blockScope for 'var' variables
var declared variables are function scoped so variables declared within a function are only accessible within the function it's self for example;function assign(param){
    var assignment = param;

Es6 destructuring operator in JavaScript

JavaScript from es6 enables destructuring operation,
In JavaScript destructuring is done using the syntax;
const [elements] = [array] const {properties} = {object}
For instance using Math object as an example destructuring can be done as follows;
Object matching syntax;
const {abs, min, max} = Math;
List matching syntax;
const [max, min, avg] = [10, 1, 5]
Fail-soft destructuring similar to object property look up returns undefined if there's no property matching;
var [item] = [];
item === undefined;
Fail-soft destructuring can also be done with predefined default vslues as follows;
var [item = 1] = [];
item === 1;
More information: MDNDestructuringassignment

How to write a self invoked function in JavaScript

Self invoked functions are function that run on themselves without need to be called, the syntax to create self invoked functions is as follows;

(function(){ // function body })() the runtime will run everything in a self invoked function's body You can pass parameters to the function using the syntax below;
(function(params){     // function body })(params) parameters will be made available to the function as any other argument

JavaScript default parameters

Since es6 its possible to include default function parameters just like other programing languages such as php do, default parameters cut down the need to initially set default Parameters within the code as;
const vec function (x, y){ if(typeof x == "undefined") x = 0; if(typeof y == "undefined") y = 0; return { x, y } }
now the above can be done in a more simple way , using default parameters as;
const vec function (x = 0, y = 0){ return { x, y } } In either of the functions if you omit either of the Parameters your parameter will default to zero ie 0;

How to get first and last character of a string using 'String.startsWith' and 'String.endsWith' in JavaScript

String starts with is an emcscript es6 feature that allows JavaScript developers to test a string if the first character of a string matches the given criteria ,

Take for instance you have a string, you want to test if it starts with characters '#'
const str = "#JavaScript" cons strr = "I love #kotlin" str.startWith('#') // true strr.endsWith('#kotlin') // true strr.startWith('#') // false str.endsWith('#kotlin') // false Both functions return a boolean true for a match and false if there's no match.

endsWith does what startsWith does except that it does it at the end of the string

How to make a static http server in nodejs using express

Express is a fast unopinionated, minimalist web framework for nodejs Authored by  TJ Holowaychuk
Express is a framework for building robust http servers, single page applications and API's among others.

How to create an http server in express

Open your text editor and terminal,
run the commands below to create a project directory, application file
and a landing page

mkdir project
cd project
mkdir static
echo "Hello World" > static index.html
touch app.js

You must have a directory structure as follows; |Project/

Project directory is the root directory of the application Static directory is where static files, webpages will be stored.

index.html is an index page with text "Hello world".

app.js is a blank JavaScript file, open your editor and paste the following few lines of code into app.js

import express from 'express' const app = express() const port = 3000 app.use('/', express.static('static…

How to tabulate array key values using console.table

console.table is a function for tabulating arrays key value pairs it retuns a table when given an array as input. const table = Array(5).fill(0) console.table(table) ┌─────────┬────────┐ │ (index) │ Values │ ├─────────┼────────┤ │ 0 │ 0 │ │ 1 │ 0 │ │ 2 │ 0 │ │ 3 │ 0 │ │ 4 │ 0 │ └─────────┴────────┘

How to use 'console.assert' for assertion in JavaScript

console.assert prints text passed as second argument if the first argument returns false;
for example,

const notTrue = false; console. assert(notTrue, 'I\'ts false') // return "it's false" You can use console.assert to perform simple unit tests of your JavaScript application.

const application = function(params){ if(params.num < 10) return false else return true } const instance = new application({ num: 5 }) console.assert(instance, 'number less than ten') // return "number less than ten"

What is strict mode in JavaScript

Strict mode is a ECMAScript 5.1 feature used mainly for testing and debugging. when enabled the JavaScript engine catches more errors among others undeclared variables, duplicate object properties. How to enable strict mode,
In your code include; 'use strict'; You can put the declarative on the top most line anything that comes after it will be handled in a strict manner.

How to change a String's Case in JavaScript

Strings can be capitalized using String.toUpperCase
For instance;
const str = 'John swana' str.toUpperCase() // 'JOHN SWANA' String.toLowerCase turns strings to their small letters or 'lowerCase'

const strr = "Lorem ipsum" strr.toLowerCase() // lorem ipsum Numbers are not converted, they remain constant, untouched and unchanged.

'65'.toLowerCase() // '65'

Array concat method in JavaScript

Array concat is a method and an array property for concating one array onto another to archive merging of array elements.
Syntax for array concat;
const arr = [0,1,2,3]
const arrr = [4,5]
arr.concat(arrr) // [0,1,2,3,4,5]
Merging nested arrays using spread operator. It's possible to merge nested arrays to form a uniform array.
Take for instance you have two 2-dimensional arrays,
Or let's call them matrices
const arr2d = [[1,0],[0,1]]
// [0,1]] const arrr2d = [[1,1],[0,1]]
// [0,1]]
For instance you want to reduce the two 2-dimentional arrays and create a new array instance;
[].concat(...arr2d.concat(...arrr2d)) // [1, 0, 0, 1, 1, 1, 0, 1]

How to interpolate strings in Kotlin programming language

Kotlin programming language has string interpolation similar to template literals in JavaScript
For JavaScript You can write as;
var passage = `I'm going todo a ${chore}`
In Kotlin you can do string interpolation as;
var passage = "I'm going todo a $chore"
Interpolating expressions in kotlin is done as;
var state = "I'm done with ${numChores()} chores"

How to get user's ip address in JavaScript

An IP address is a unique numerical label given to a computer when connected to a network; is a free service that retrieves IP addresses in JSON formatfetch('')
.then(response => response.json())
.then(response => console.log(JSON.stringify(response)))// response
In nodejs you can use a package node-fetchInstall it by typing;npm i node-fetchOr using curl, in your terminal type;curl ''// response

How to install git on a raspberry PI

Its impossible to write software without using Git, Git according to Wikipedia is a distributed version-control system for tracking changes in source code during software development.
A Raspberry PI is a credit card sized single board computer usually running a linux operating system "Debian, or raspbian" preferably used mostly by schools to teach students computer basics.
How to install apt on a raspberry pi;
Install using apt package manager,
To install using apt open your terminal type;
sudo apt update
sudo apt upgrade
sudo apt install git
You will be presented by a apt screen with package information confirm by pressing y followed by Enter;
Once installation completes you can check if the installation was successful by typing;
git --version
Upon successful installation you will be presented with git version number such as;
git version (2.11...)
Next step is to configure git, before doing any cloning you will be required to configure Git by adding your email address.

How to evaluate a string on a regular expression rule in JavaScript

JavaScript has a built in regular expression function for testing if a string arguments is matching the given regular expression rule;Syntax of the regular expression tester is as follows;/regex/.test(string)Take for instance you want to test if a string contains only alphanumeric upper and lower case characters, space and numbers;const str = "Eat code sleep"/[A-Z,a-z,0-9, ]*/.test(str)
// returns boolean 'true'Or in another example;const str = "Eat, Code, Sleep"/[A-Z,a-z,0-9, ]*/.test(str)
// returns boolean 'false'Because commas are not included in the regular expression match rules.

What is 'this.' keyword in JavaScript

In JavaScript 'this' is an object and a reference to the current object that is used to get and to set properties of the current object.Take for instance within a function;const func = function (name){ = name
} instance property name is set to that of the first argument;const inst = new func('duke')
// returns dukeYou can as well extend func to set name using 'this';func.prototype.set = function(name){ = name
}Running the previous instance with this set method;inst.set('John')
// returns John

How to create promises in JavaScript

Promises enable asynchronous programming, JavaScript is single threaded,
You can use them to wait a lengthy promises take for instance an ajax or fetch process then once ready process the response.How do declare an asynchronous function,
To declare an asynchronous function add async keyword befor function name;const func = async function() {
    return 'OK'
}function func will now return a promise;const inst = func()
.then(response => console. Log(response))
.catch(err => {
    throw new Error(err)
}You can also await it like ummm;const response = await func()
console.log(response)Rejecting and resolution of promises,
This is done to distinguish successful promises from failed promisesconst statusReport = function() {
    return new Promise((resolve, reject) => {
    setTimeout(() => resolve(), 10000)
}You can inquire statusReport as follows;const analysis = new statusReport()
.then(() => console.log('hooray'), () => console.log('failure'…

How to use fetch api submit an html form

Fetch api allows asynchronous means of reading files and a more simplified way of making http requests in JavaScript.How to submit an existing html form using fetch api;Assuming you have html source code with a form and some input fields;<form id="form" action="./submit" method="post"
<input name="query">
</form>You can pass an instance of a dom form to formData constructor as the first parameter;const handle = function(event) {
    const data = new formData('//localhost/api/post', {
    method: 'POST',
    body: data
}Fetch api returns a new pending promise to process the response you will need to await asynchronous process once ready to consume parse it as follows;.then(response => response.json()).then(response => console.log(response))

Constructor functions in JavaScript

A constructor function is a function whose instance is created using the 'new' keyword.Constructor functions in JavaScript can be declared using classes or by using JavaScript functions 'with few tweaks'HowtocreateaconstructorinJavaScriptFor JavaScript functions construction declaration can be made as follows;const greeting = function(name) { = name
}greeting.morning = function() {
    const name =
    return `morning ${name}`
}In the code bove declared a function greeting with a parameter named 'name'I further created a method named morning it returns a template greeting messageOnce the program gets run on a JavaScript engine the expected output is;morning + 'name provided'For instance;const greet = new greeting('John')greet.morning()
// returns 'morning John'Similar to using functions as constructors you can as well declare using classes;const greeting = class {
    constructor(name) { = name

What is /usr/bin directory on a linux, unix operating system

user binary directory or /usr/bin Is used to store user executable applications./usr/bin is also used as a look up directory by the shell so when you type a command the operating system will fetch /usr/bin for matching binary filesAs compared to /bin and /sbin , /usr/bin is a common  directory used to store user installed application files let's say text editors or webservers.

What is /sbin on a linux, unix operating system

What's the sbin directory on a Linux computer system ,An /sbin directory is a sub directory of root directory, sbin is an abbreviation of system bin.It's used used by the operating system to store and lookup essential system specific binary programs
ie ip, mkfs.*

How to build a twitter retweet bot using JavaScript

I'm sharing the code of my tweeter bot called 'JavaScript bot' I forked the original source code from a certain github repository written in nodejs the bot retweets a giver hashTag at a specified time intervalYou can use a twitter bot to promote an interest or a campaign unlike Facebook twitter is more tolerant on automated accountsI used to build Facebook automated accounts which were posting user friendly comments on my Facebook friends posts with no success few months down the line Facebook suspended my account until then i decided to stop using Facebook at allAnd twitter is just the right platform for this kind of thing.For this bot to work you'll simply need an APIs key and a secretTwitter doesn't need waiting the long verification process as of 2020 I created my developer account and almost instantaneously my account got approved.The twitter hard limit on the number of retweets per day is 1000;clone git repository using the command;git clone…

How to wait for a promise within a loop block

JavaScript promises enable developers to write asynchronous applications in JavaScriptLoops are ways of iterating elements
For instance doing an asynchronous task within a for loop can be done as follows;
Note that lag is used to emulate some delay.const items = [1, 2, 3, 4]
const lag = async (delay) => {
    return new Promise((resolve) =>
        setTimeout(() => res(`${delay / 1000} sec`), delay))
}items.forEach(async (item) => {
    const seconds = await lag(1000 * item)
})expected output1 sec
2 sec
3 sec
4 secAfter running the code above every second some text was printed

What is a bin directory

A bin is an abbreviation of binary, a bin directory is a standard directory used to store executable binary applications.For example When you type a command on your terminal the operating system looks up for an entry in the bin directory
Take for instance.cowsay 'hello world'If you type out the command above your operating system will look up for a file named cowsay inside the configured bin directorylet's say /usr/bin/Should it find a relevant entry that matches the command 'cowsay' it will then pass arguments passed as parameters made available to the program 'cowsay'

How to pretty print JSON.stringify output

JSON.stringify is a method of JSON global which converts valid JSON to a serialized stringJSON is an abbreviation of 'JavaScript Object Notation' it's an independent data type that is not specific to JavaScript programming language.JSON is a global object with methods for manipulating JSON dataJSON.stringify is a method that converts JSON to a string its may be used for debug or simply to serialize JSONIt accepts three arguments (JSON, FUNCTION, SPACER)JSON: maybe an array or objectFUNCTION: Is an influencer it's a middle man that alters what is to be returnedSPACER; Is a character used to indent or prettyfiy outputFor instance take a look;const name = 'John'
const surname = 'swana'
const me = {name, surname}JSON.stringify(me, null, '    ')Returns the following output;{
    'name': 'John',
    'surname': 'swana'

Object assign in JavaScript

Object assign in JavaScriptObject assign is a static method of JavaScript Object global.Object assign is mainly used for merging two or more objects, where keys match Object assign overwrites one value of an object with the corresponding value of the same key in the second object.Example usage of object assign;const max = {
    name: 'max',
  type: 'dog',
    bread: 'fluffy'
}Given a situation where you want to derive a new pet of a certain name you will not need to redefine the whole pet structure instead just add or replaced the characteristics of the pet to that of your desire;const khloe = Object.assign(max, {
  name: 'khloe'
  type: 'cat',
  color: 'blue'
})// output after running the code above on a JavaScript engine;{
    "name": "khloe",
    "type": "kitty",
    "bread": "fluffy",
    "color": "blue"
}You can notice that Object khloe is a clone of ma…

What is a /home directory on linux, unix operating system

Home directory on a Unix or Linux operating system is root sub directory and a standard directory where the operating system stores user home directories under their own usernames/home/username/
/home/john/An individual's home directory is a space where one would store their personal items such as media files among othersAccess permission is dependant on the name and type of distribution of the operating system
751 perhaps :|How to go to your home directoryAmong Linux distributions they are a vast number of way one can get back home.On a standard Linux operating system directory path is stored in the $HOME variablecd    --- works
cd ~ -- works
cd ~/ --- works
cd $HOME --- works

E2020 dynamic imports in JavaScript

Escmascript Is a standard from which JavaScript and typescript are both derived from.ES2020 is out it comes with it new ways of writing JavaScript code.Dynamic imports enable importing dependencies in a rather dynamic way.Initially JavaScript developers were restricted to statically load their dependencies for instance;import { property } from 'dependency'On runtime the JavaScript engine loads the required dependencies and makes them accessible globally.However that is a rigid way of writing code.Dynamic imports are  relatively more flexible therefore you can included them at any segment within your program.For instance if you want to load file system module only if a certain criteria is met you would do as follows;If(process.argv[2] == 'start')
Import fs from 'fs'Dynamic imports return a promise use the syntax below to make use of themimport('fs')
.then(fs => {
   // consume module fs

Ways of iterating Object properties in JavaScript

For Objects the ways of iterating their properties are not that plentiful as with Arrays.take for instance we have an object of dogs and cat characteristicsconst pets = {
{name: "Jenny", eyes: "brown"},
{name: "max", eyes: "blue"}
}To iterate through the characteristics using for loopfor (pet in pets) {
    console.log(`${pets[pet].name} has eye color ${pets[pet].eyes}`}
}Alternatively you can use objects.keys and object.entriesfor (element in Object.entries(elements)) }

Handy array functions every developer should know JavaScript

Array make a good means of data storage and manipulation in JavaScriptif used well arrays are way better than objects especially if you're working with numbersArray.push(element)
Its a method used for quickly appending an element to an array
For instance
const arr = ['code']
// ['eat', 'code']Array.unshift(element)
It's a method that's pretty similar to array.push except that unshift prepends an element to the end of the array
For instance
const arr = ['eat', 'code']
// ['eat', 'code', 'sleep']Array.shift()
Array.shift is a function that removes the first element of an array and returns it
For instance
const arr = ['eat', 'code']
const err = arr.shift()
arr returns
// ['sleep']
err returns
// eatArray.pop()
Is a method an array property similar to shift that removes the last element of an array and returns it. Array.pop() and…

Hello world application in Kotlin

Kotlin Hello World Application To get started open your editor and type the snippet of code below fun main() {
    println("Hello, World!")
}in kotlin main is the entry point function of an applicationfun keyword is used for declaring functions it acts like function does in JavaScript.Compile your application into jar
kotlinc hello.kt -include-runtime -d hello.jarExecute your application
java -jar hello.jarIf everything went well you should see "Hello World" output from your terminal

How to install Kotlin programming language

Kotlin is a programming language that is statically typed runs on the JVM and can compile to JavaScriptTo install kotlin using the Software Development Kit on Debian Ubuntu or Linux environment.First install the SDK using
Command:wget -O ""
bash sdk.install.shTo install kotlin Type the command:source ~/.sdkman/bin/
sdk install kotlinTo install Java development kit (JDK) a vital dependency used for execution and compilation of kotlin code.
Type the command:sudo apt-get install openjdk-8-jre-headlessTo confirm installation type the command:kotlin -versionIt should return output similar to one belowKotlin version 1.3.61-release-180 (JRE 1.8...)

Introduction to Kotlin programing language

Kotlin is an open source statically typed programming language named after an island just like Java was named after an Indonesian island.Kotlin runs on the JVM and can compile to JavaScript.Uses for kotlin programming languageKotlin is a preferred programming language for Android application development second after Java programming language.Kotlin can be used for artificial intelligence and data science research applications.Because of its speed kotlin is a well suited programing language for web server application development.On rare occasions you can use kotlin to develop client side application simply because it can compile to JavaScript.Hello world application in kotlin programming languageKotlin applications must have a main method.
println is used for text output just like in Javafun main() {
    println("hello world")
}After compiling the output should be "hello world"Basic syntax variable declaration
Variables are declared using
'var' for mutable …

Get current url port, hostname and path in JavaScript

window.location is an Object with properties of current location namely window.location.href returns the href url of the current pagewindow.location.hostname returns the domain namewindow.location.pathname returns the pathname segment of the urlwindow.location.protocol returns the web protocol of the urlwindow.location.assign() loads a new document

Redirecting a webpage in JavaScript

Redirects are way of navigating a user to another webpage or location redirects are normally done by server side's possible to do redirects using JavaScript too window.location is a object that stores current location information such as path, port, hostname and href or the location in the address bar of your browser changing it invokes a redirect it's a simple way to redirect a user to another webpageSyntax
window.location.asign('')or simply likewindow.location = ""or simply omit windowlocation = ""

How to target all elements of a given class name in JavaScript

JavaScript getByClassName only targets one element by default Workarounds "loops"
Loops can mess up your code I personally don't like them.
To target all elements you will have to iterate through all of them for each element you will have to add a event listenerExample
For instance the are 3 links of a same class and you want to add event listeners on all of them
// JavaScript
const links = document.getByClassName("links")
for(var i = 0; i < links.length; i++)
links[i].addEventListener('click', event => console.log( attribute('class')))

JavaScript event prevent default

JavaScript event preventdefault is a method for intervening event actions preventing normal events behaviorTake for instance you have an anchor on a page when a user clicks on it the browser by default navigates to a url in it's href attributepreventdefault syntax/// HTML
<a href="/" id="home">
</a>/// JavaScript
home.addEventListener('click', function(event){
    // rest of
    // the code

With statement in JavaScript

JavaScript 'with statement' is a simplified way to access object properties as variables.Take for instance;const dog = "puppy"
const mascots = {
    'tux': "tuxedo",
    'cow': 'cow'
}with(mascots) {
    // tuxedo
    // cow
    // puppy
}properties of mascots are converted to variables accessible within the with block 'dog' is not part of mascots and as a fallback, dog global is returned.At the time of writing this post with statement is discouraged.It's not allowed in 'safe mode'With the above sample you can do the same thing using destructureing operatorconst {cow, dog, tux} = mascotsconsole.log(tux)
// tuxedo
// cow
// puppy

Ways to iterate array items in JavaScript

A few days ago i introduced arrays and described what they are and how their elements can be iterated in JavaScript using 'for loop'There many other ways to iterate arrays namely Array.forEach,,
var array = ['eat', 'code', 'sleep']Using forEach
array.forEach(function(value, index){
    console.log(index + ': '+ value)
})// result expected
// 0: "eat"
// 1: "code"
// 2: "sleep"Using, index){
    console.log(index + ': '+ value)
})// result expected
// 0: "eat"
// 1: "code"
// 2: "sleep"It's a wrapp

Lexer and tokenizer for robots.txt in JavaScript

Introduction I'm sharing how i made lexer and tokenizer for robots.txt in JavaScript

Reasons and motives I'm using it in the Nodejs environment of course so it's server side it's part of another project I'm doing.

How it's done robots.txt files contain one directive per line inform of

Key: value
Take for instance

User-agent: Googlebot/{version}
Disallow: {path}

Path the disallowed location it may included wildcards ie "*" or "/" its not a good idea to consume them raw without validation

And version number is ignored to make targeting bots easy i guess
Steps taken by the lexer
Splitting text into an array containing data from the robots.txt file line by line given it's provided with an input looking like this

User-agent: Googlebot/{version}
Disallow: {path}

It may return something that's like this [User-agent: Googlebot/{version},
Disallow: {path}]

Almost there. after that next step is to remove comments from each line using regEx


Removing #hash comments from a string using regEx in JavaScript

Last night i was looking for a method to remove comments from a robots.txt file containing contents of form below`# robots.txt
Disallow:`Or a more practical format obtained by splitting the robots.txt file line by line.["# robots.txt",
"Disallow:"]every element of the array is a string representing a single line of text from a robots.txt plain text file.Regular expression
I used regular expression to strip out the unwanted text until the end of the line
however it's not limited to robots.txt it works perfectly with files as well.Example
var string = "Disallow / #deny bots"
string.replace(/#.*$/, "")
// returns  Disallow /It simply strip's off all characters after the hash character until the end of the line.

How to iterate array elements using 'for loop' in JavaScript

JavaScript arrays are similar to arrays in c and in c like programming languages such as php among others In JavaScript arrays are simply collections of elements for instance Objects Numbers or other ArraysDeclaring an array
An array may be declared using the array constructor for instanceconst array = new Array()
or as
const array = []Iterating an array using 'for' loop
This is the implest and most common method to iterate an array is by using the 'for loop' am sure you're familiar with the syntax. take for Instance you want to iterate an array of integers and print each one of them.var ints = [1, 2, 3, 4]To iterate ints using for loop.for (var i = 0; i < ints.length; i++){
}// output will be
// 1
// 2
// 3
// 4In between the parentheses they are three procedures in three segments separated by colonsfirst segment declares var i an index which gets incriminated in the third segment as long as it's less than the length of the ints…

How to use canvas context rect method for drawing rectangles

canvas context rect method does as it says. It's used for drawing a rectangle on a canvas contextParameters
context.rect(positionX, positionY,
Width, Height)PositionXspecifies the x coordinate at which the rectangle should be drawn at on the contextPositionY specifies the y coordinate at which the rectangle should be drawn at on the contextWidthspecifies the width of the rectangleHeightspecifies the height of the rectangleStroking and filling the rectangle
In order for the rectangle to be actually visible you have to either stroke it or fill it with a color.Stroke
Stroking a rectangle means to draw a line that joins all of it's vertices
To specify the fill color you should set it and call stroke to draw
context.strokeStyle = "#colors"
Similar to srokings filling a rectangle means to paint it's inner bounding box with a specified color
context.fillStyle = "#colors"
context.rect(0, 0, 100, 100)

Install steam locomotive sl using apt

sl or steam locomotive is a commandline application that displays steam locomotive "train" animations aimed to correct users who accidentally enter sl instead of ls.  initialssl stands for Steam LocomotiveHowtoinstalllsorsteam locomotiveAssuming you've root privileges and installed apt package manager on your system
Typesudo apt-get update
sudo apt-get upgrade
sudo apt-get install slTo test installation type
If installation was successful You'll see an ASCII image of a train right in your terminal after few seconds it will stop

JavaScript canvas introduction

Probably next monday I will post a how to make a snake game clone in a few lines of JavaScript code post don't miss it out subscribe to my email newsletter!What isa canvas
I'm sure you've heard of the term somewhere. canvas through their "2d" context allow drawing 2d graphics using a simple JavaScript apiYou can use a canvas to draw text , lines simple shapes, and images
canvas can also be used as a renderer for JavaScript built html5 games "that's were we're going"Example on canvas
it draws a rectangle on a canvas context black color by default<html>
<canvas id="canvas"></canvas>
<script type="text/javascript">
        var context = canvas.getContext("2d")
// stroke a 100px square at 0, 0
context.rect(0, 0, 100, 100)
</html>Save and open it in your browser you should see a square on the top right corner of your browse window

JavaScript spread operator

JavaScript spread operator is a useful operator for manipulation of objects , strings and arrays in JavaScript among others you can you it to effectively copy an object or array expand it or even convert a string into an array of its constituent characters.const chars = ["a", "b", "c"]
const name = "John swana"Copying an array using spread operator
to copy an array using a spread operator you can do it using the syntax as followsvar alphabet = [...chars]
And now alphabet contains chars properties
alphabet // ["a", "b", "c"]Copyinganobjectusingspreadoperator
Similarly you can copy JavaScript objects using spread operator. Take for instance
const object = {name:  "John swana", gender: "male"}
var user = {...object}
user //  {name:  "John swana", gender: "male"}Convertingastringintoanarray
Note that you can use String.prototype.split for this operation if you want
var array = [..…

Installing and using 'cowsay' with fortune

what is 'cowsay' it's a simple commandline program of a cow which basically prints whatever text argument you pass to it inform of a speech bubble from a ancii cow
c:owsay goes hand in hand with another cli programme called fortune it generates text fortune messages which can be easy be tunnelled into cowsay
Cowsay is so popular that i decides to write a how to installation post
To get started open your commandline terminal and type sudo apt-get update 
sudo apt-get upgrade
sudo apt-get install cowsay
To install another cli app 'fortune'
type the following in your terminal
sudo apt-get install fortune
After installation test fortune by typing in your console fortune // typical response Training is everything.  The peach was once a bitter almond; cauliflower is
nothing but cabbage with a college education.
                -- Mark Twain, "Pudd'nhead Wilson's Calendar"
To test cowsay type cowsay followed by a command you want to be said 
Cowsay will print a cow in yo…

JavaScript class getters and setters

I assume you know heard or at least in someone's code seen JavaScript classes. newly introduced classes are much better than functions if your code requires inheritance of constructors "classes"Brief subintroduction
A class can be made using syntax below given cats as an exampleclass chat {
    constructor(params) { =
        this.color = params.color
    meow() {
        console.log("meow meows" + this. name)
cat is a class with a constructor and a method named meow note that you can omit the constructor in the above code if you have nothing to initializeAdding Getters
getters are a piece of code that retrieve properties of a class in class cat they're no user defined getters
JavaScript properties can be retrieved even if you don't use getters for instancevar kitty = new cat({
    name: "tom",
    color: "black"
})kitty is now an object to retrieve kitty properties …

JavaScript es6 modules import, export

Java scrips modules are libraries that export importable properties.With modules you can create reusable independent separate components es6 modules should provide one or more exports.exports can be ie a function or an object take for instance you created a math library you can use the syntax below to create a module.// saved as lib-math.js
export function cube(num) {
    return num * num * num
}To make use of lib-math above in a simple calculator function you can import it as// saved as calculator.js
Import {cube} from "./lib-math"
function calculator(num) {
    return cube(num)
}// calculator(5) // returns 125
// calculator(3) // returns 27
// calculator(2) // returns 8Alternative ways to export
You can export a function as in the example above or you can export functions as an object assuming you have more than oneexport {cube, sqrt, .....}Ways to import a module importing modes is done by the follow keyword following by from proceeded by the relative path or module name …

JavaScript es6 template literals

Template literals are a new syntax to create strings in JavaScript Embedding expressions in a string is now possible using template literals thus there's a new way to embed expressions into strings effectively interpolating the values done using syntax ${expression}
within a string for instanceconst text = 'Hello world'
const string = `Say ${text}` // Say hello world.You're not only limited to that you can as well perform more advanced expressions and arithmetics as wellconst string = `${1 + 2}` // returns 3stringsthatspawnmorethanonelineare now possible with template literals initially the only way to create strings that spawn multiple lines was to break it up in parts the syntax below is now possibleconst text = `

JavaScript var const and let

Signification and let are new JavaScript methods of declaring a variables on modern browser's you don't need to enable strict mode to make use of const, and letWhat'sthedifferencebetweenvar , letandconst
Immutability when you declare a variable using const its value is immutable ie you can't simply reassign the variable with another value neither can you declare const variables as
const variable, another;
because it's pointless afterallscope of this
let variable decelerations are block scoped therefore if used in an if statement or in a function its value is scoped within that block

Arrow functions in JavaScript

Since their introduction arrow function have simplified how we declare functions in JavaScript arrow functions are similar to lambadas in kotlin programming language
Instead of writing a function as function time (param){
} You can simplify code by rewriting it as simply let time (param) =>  {
} Alternatively you can use a neatier syntax let time = param => Arrow functions this context does not refer to their scope.
For further reading "learn es6 the dope way part ii arrow functions and the this keyword",

=== or == JavaScript comparison operator

triple equal === strict and double equal == not type strict are two of JavaScript comparison operators blatantly they are almost the same with an exception.== operator
this type of comparison operator is suitable for basic comparison between two items it's not type strict and normally discouraged unless otherwise and here's why i say so.
Take for instance
console.log((1 == "1")) // returns true
regardless of the fact that "1" is a string and 1 is a Number
because "1" is type casted  to a Number before comparison between the two values is done
Take for instance
var one = 1;
// console.log(typeof one) // Number
It's not a matter of concern neither is it a bug it's because JavaScript is a dynamic typed programming language.=== orstrictoperator
triple equal sign operator or strict operator is an operator that takes account of types of values before evaluating their similarities unlike the double equal sign operator strict operator…

How to train a tfjs model to play breakout game

This is an artificial intelligence mechine learning practical experiment documentary on training an artificial intelligence neural network to play breakout game in the browser powered by tensorflow tfjs for JavaScript.
To understand how things will work breakout is a game which is alot more like ping pong your objective is to make sure the ball never goes by the puck in other words the player's puck should hit the ball before it heads into the lower bond of the screen.
Second objective
Second objective is to make the ball destroy blocks by projecting it into the disired direction.
Normally this is not very important because the ball would normally iterate each and every corner on its own without trouble
Persudo code
below is how this system works
// start initialization
// create model
// end initialization // start update loop
async predict(should i move left or right). On resolve {set linear velocity} if(ball crashed) {diagnose errors and generate reinforced …

removing array elements in JavaScript

JavaScript array elements can be removed in multiple ways using methods pop, shift, splice, filter.Array.shift()
Shift is a method which knocks off the first most element of an array and returns it! ie
var number = [0, 1, 2, 3, 4, 5]
number.shift() // returns 0
console.log(number) // [1, 2, 3, 4, 5]Array.pop()
this method removes the last element off an array and returns the removed element ie
var number = [0, 1, 2, 3, 4, 5]
number.pop() // returns 5
console.log(number) // [0, 1, 2, 3, 4]
Array.splice(start, elements)
start is the index at which removing  starts elements is an integer the number of elements to remove it returns spliced elements
var number = [0, 1, 2, 3, 4, 5]
number.splice(0, 1) // returns 0
start can also be a reference ie of an object.

rgb to hex conversion in JavaScript

A handy function to convert rgb colors to hex in JavaScript
parameters: red, blue, green values.
returns a hex string which is 7 characters long including the hashfunction toHex(r, b, g) {
return "#" + [r, b, g].map(param => {
var hex = Number(param).toString(16)
return (hex.length < 2) ? '0' + hex : hex
}For instance  toHex(0, 0, 0)
// returns #000000

JavaScript intro to classes

Classes are objects 'functions which introduce inheritance parent child relationship in JavaScript it promotes code reusability which reduces the amount of code in a JavaScript application. JavaScript class decelerations start with keyword class proceeded by class name with a class body having a constructor along with methods for instance
class human {
    constructor(name) { = name;
         this.gender = null;
    great() {
        return "Greetings " +
        (this.gender == "male") ? "mr " : "mrs " +
} Child classes are created by adding the keyword extends followed by the parent class name and parent class methods can be called using the syntax super.+"method name"(parameters) class man extends human {
    constructor(name) {
         this.gender = "male";
} const John = new man("John swana")
John. greet()
// returns Greetings mr John Swan…

Npm how to install webpack nodejs

A guide on how to install webpack bundler and webpack-cli using npm package manager first thing install webpack it's recommended not to install webpack globally to avoid conflicts with webpack versions npm i webpack -D
Note it's installed as a developer dependency. You'll also need to install webpack-cli
npm i webpack-cli -D
Again as a developer dependency.

hello world application in nodejs

Nodejs is a JavaScript command line runtime using chromes v8 engine known for its wicked fast speed and execution time. its well known that  the v8 engine compiles JavaScript to archive its impressive performance. Nodejs is a command line application ie the output will be forwarded to the console in our case the terminal of your shell. In your terminal or text editor type
console.log("Hello World") save the file simply as helloworld.js
In your terminal type node helloworld.js
Output // Hello World
// Hooray You dit it.

Adding elements to an array in JavaScript

JavaScript arrays are objects which can be initialized using a syntax of
["", ...] Parentheses with a number of elements ie
var oddNumbers = [2, 4, 6]
or var numbers = ["one", "two", "three"]
Or the global Array constructor using syntax ie  var integer = new Array(length = 2) console.log(integer) // [null, null]
where length species blank filler value by default the element is null and you can't iterate them to change the fill value you can call the fill method of an array ie integer.fill(0) console.log(integer) // [0, 0]

You can append an element to any of the arrays declared above using push , prepend using unshift, assign using manual assigning
Manual assignment Simplest way is by simply assigning a new element
oddNumbers['index'] = "Number"
ie oddNumbers[3] = 8;
console.log(oddNumbers) // [2, 4, 6, 8]
Push Its a method for appending elements to an array is oddNumbers.push(0) console.log(oddNumbers) // [0, 2, 4, 6, 8]
Unshift Its a…

Npm nodejs yarn install

Assuming you have installed nodejs on your system next thing is installing developer build tools and yarn is a must yarn is a nodejs package manager similar but different to npm which is installed by default immediately you install nodejsOpen a terminal session onto it type
sudo npm install yarn -gYarn is going to have a symbolic link in the bin so don't omit sudo or you'll probably get an ugly error if you are not a super user ie root.lastly -g argument specifies the package should be installed globally

How to install nodejs on linux

Nodejs is an open source JavaScript runtime without a dom model nodejs can be used to create web servers api's  and command line applications among others its important to note nodejs is increasing popularity due to its simplicity , speed and developer friendliness i.e frontend developers once limited to using JavaScript in the browser can now create server side backend your terminal execute the command below to add node js repository.
curl -sL | sudo -E bash -update apt packages list
sudo apt apt update && upgradeinstall latest nodejs
sudo apt install nodejs

JavaScript math constants

In JavaScript Math is a global object with mathematical functions and constants.Math object is extendible. for instance to make a function to calculate cuboid of a given number.
Math['cuboid'] = function(number) {
    return number * number * number
or defining a constant
Math['some_constant'] = value;You can use your new function like any other function ie
console.log(Math.cuboid(3)) // returns 27
console.log(Math.some_constant) // returns valueMath.E
Euler's constant and the base of natural logarithms;
console.log(Math.E) // returns 2.718281828459045Math.LN2
Natural logarithm of 2;
console.log(Math.LN2) // returns 0.6931471805599453Math.LN10
Natural logarithm of 10;
console.log(Math.LN10) // returns 2.302585092994046Math.LOG2E
Base 2 logarithm of E;
console.log(Math.LOG2E) // returns 1.4426950408889634Math.LOG10E
Base 10 logarithm of E;
console.log(Math.LOG10E) // returns 0.4342944819032518Math.PI
Ratio of the a circle's circumference to its diameter;

JavaScript math methods

JavaScript comprehensive list of all JavaScript Math methods Math.round()
{type} method
{parameter} {Number}
{description} It returns a given number rounded off to the nearest integer.
ie Math.round(0.6251) // returns 1
or Math.round(1.7252) // returns 2Math.pow()
{type} method
{parameter} {Number}, {Number}
{description} It returns a given number raised to the power the exponent.
ie Math.pow(2, 5) // returns 32
or Math.pow(7, 2) // returns 49Math.sqrt()
{type} method
{parameter} {Number}
{description} It returns the square root of a given integer.
ie Math.sqrt(25) // returns 5
or Math.sqrt(64) // returns 8Math.abs()
{type} method
{parameter} {Number}
{description} It returns absolute positive value of a given number
ie Math.abs(-10) // returns 10
or Math.abs(52) // returns 52Math.ceil()
{type} method
{parameter} {Number}
{description} It returns a smaller number which is greater or equal to the given integer.
ie Math.ceil(9.87) // returns 10
or Math.ceil(51.5) // returns 52Math.

JavaScript dynamic data types

Default variable type is string ie after declaration the data type is normally string or as most things are objects in JavaScript you can call it that way if you prefer to do var name;
condole.log(typeof name) // stringnull means a variable is declared but it still has nothing ie its null. null can also be used as a way to unset a variable's value.Booleans values are true and false.
var on = true;
console.log(typeof on) // Booleanobjects and arrays in JavaScript are of type object ie an array is an object
var matrix = [[0, 1], [1, 0]]
var vector = {"x": 0, "y": 0}console. log(typeof matrix) // Object
console. log(typeof vector) // Objectfunctions are also a special datatype
console. log(typeof  function(){}) // function

How to train a tfjs model on logic gates

Using tensorflow for JavaScript to train an artificial intelligence model to effectively evaluate and predict expected output of a logic gate given two inputs. training data is sourced from a two dimentional array truth table
// logic truth table
// -----------------
const truthTable = [
        [[[0, 0], [0, 1], [1, 1], [1, 1]],
        [[0], [1], [1], [1]]]
]; The first pairs of numbers are the input proceeded by the output

JavaScript introduction to variables

JavaScript is a dynamically typed programming language variables are declared using the following format
var `variablename` `value`
instead of
int integer = 100In JavaScript a variable can accommodate any typeof value ie a variable can be assigned numbers, strings, functions, and objects.among modern browsers or in "strict mode" variables can be declared in an alternative way using const and let keywords.variable's defined this way's values can not be changed once they have been assigned. ie they are referred to as immutable.var name = "John"
var lastname
var year = 2020
// var age
var male = trueconsole.log(typeof name) // string
console.log(typeof lastname) ///undefined
console.log(typeof age) // undefined
console.log(typeof year) // number
console.log(typeof male) // booleanconst pi  = 22 / 7
pi = undefined; // sometimes this can raise a typescript error
// assignment to constant variable in strict modeconsole.log(pi) // 3.142857142857143