Posts

Showing posts from 2020

FlappingBird Postmortem (JS13K)

Image
FlappingBird was my Primary entry for JS13K Games competition 2020 It's about a bird flying in a forest of trees (Some of which are upside down) It started out as i was trying to draw some clouds for fun, then later i added every missing component to complete the sky First day. I planned making a game that should as well serve as a 404 page with a hidden game such that when a button is pressed It transitions into gameplay qualities were that it should be easy to play by everybody without need to master many rules Second day. There was a bunch of game ideas up my sleeves one of them was a game where a typical 404 page transitions into a green garden like mine sweeper version made up of a flowering mine field with smooth sweet sound effects Fourth day. We'll Since Mine sweeper is not a very common game there's nothing fun about it and not everyone knows how it's played. So i gave up on it and on this day i started working on backgrounds for flappingBird "the final

FlappingBird JS13K Games

Image
FlappingBird is a Mobile side scroller game where the player controls a bird, attempting to fly between columns trees without hitting them Development of this game started out when i was attempting to draw perfect clouds programmatically on a canvas i later added a few more clouds (Something's missing) add moon, stars,  buildings and also add Gradients and for the games character i settled on a bird (using Sprite sheet obtained freely from opengameart) add more them and animated everything. FlappingBird is a single player arcade-style game in which the player controls the bird, which moves persistently to the right. The player is tasked with navigating the bird through pairs of trees that have equally sized gaps placed at random heights. the bird automatically gravitates and only ascends when the player taps the touchscreen or spacebar. Each successful pass through a pair of trees awards the player one point. Colliding with a tree or the ground ends the gameplay. If a player succ

Adding Gameover and introduction screen on HTML Canvas

Image
Its been four days since my last status report. Ever since then I've been struggling trying to glue myself together and harness that for something gamedev. I've reorganized pretty much everything about the structure of the code by splitting chunks of it into bite sized modules wherever possible  and apart from that I'm proud i brought my "404" and "Gameover" sketchings to life Am looking forward to implementing main characters of the game soon. And am yet to announce everything about gameplay publicly to everybody. Here's Progress so far And gameover screen

Animated daylight on HTML5 Canvas

Image
It's Fourth day and i made improvements by adding new background Obstacle for daylight notice the wind turbines replacing trees, the sun replacing the moon and the disappearance of stars from the Sky. However it's more like day three extended++ (plus plus) trust me i've added nothing new i spent most of the time sketching introduction screens and gameover screens Here's progress so far.

Animated sky on HTML5 Canvas

Image
So far I've added a new bunch of clouds, some stars and a phase changing moon' As the number of Clouds increased i cursed them into an Array and created two more Obstacles the Moon and Stars Here's progress. (Extended preview) In extended preview i added trees and buildings. (everything is drawn programmatically without using static Images)

How to draw clouds on HTML5 Canvas

Image
So basically clouds are shapes with a flat bottom and 3 curves on top (two on the sides on bigger one on the middle) As i was creating a JS13K Game i wondered around googling if i'd find something as simple as that and 'i couldn't find anything interesting So i took some pictures of simple animated clouds and sketched it on my notepad trying to reverse engineer shapes in the figure In my first attempt i discovered that "the base is something similar to css pills, so there's rectangular shape with roundish edges and a circle overlay on top". Putting that into vanilla JavaScript i resorted to creating two canvases 1. foreground layer 2. background layer Clouds are drawn using a solid color formed by four shapes 3 circles and a rectangle then using some alpha the resultant image is then overlay-ed onto the primary canvas. Here's an example It's a sneaky way todraw clouds so they got to be a cleanway todo this without Jumping extra hoops Last reso

JS13K Preparation

JS13K Is an annual gamejam (hackerthon) held on the 13th of August and participants are given 30 days to created a game using JavaScript less than 13KB in size minified (optional) and zipped including assets On the 13th of August a 'secret' theme is announced and everybody must create a game inline with it. Last years competition was so epic. it was themed "back". And as a beginner i dropped two entries "watchmyback" and "firedrone" interpreting the theme in my own way So far i've been watching everyone showcasing their amazing and creative works under the hashtag #js13k on Twitter For today i'm only going to create a new directory for my project, init a git repository and stuff.

Snake monochrome (JS1024)

JS1024 is an annually held code golfing competition where you're basically required to create something creative in 1024 bytes or less of raw "JavaScript/HTML/WebGL" I participated for JS1024 2020 competition with my First entry titled "Snake monochrome" Originally inspired by the old Nokia game going by the same name "Snake" which i used to play as far back as 2007-2008 Another entry making it Second is named "Tetris monochrome" i was compiled to do this game as a dare from my Girlfriend on June 6 the "Tetris 1984" anniversary Third one is F1-racer it's inspired by my bestfriend who wasn't impressed with how i hooked up controls on "Tetris Monochrome" so he requested "i modify controls a bit", and i improved "input/output" by adding smooth touch input to it as requested Snake game contains two entities. The Snake and the Apple, the Snake is an Object with properties position (vect

How to restore PostgreSQL database dump

They'res a magnitude of methods to restore PostgreSQL dumps for a typical plaintext dump "psql" can do a pretty neat Job In few words a PostgreSQL plaintext dump is nothing but a corpus embodied with SQL statements, which when executed tables are created data gets retrieved, inserted and restored. So assuming you have a backup dump saved somewhere on your system open your terminal. And type; psql -U {{username}} < {{dump.sql}} That's it you've imported a database dump

how to dump a postgresql database using from the terminal

PostgreSQL is a relational database management system and arguably the best database management around. postgreSQL comes with utilities used to manipulate databases from the terminal "psql" being the most popular utility I'm sure you've read somewhere or used "psql" dumping "backing" databases is done using PostgreSQL's pg_dump utility In your terminal type; pg_dump <database name> > <output> For instance to backup a database named "books" to a file named "books.sql" do; pg_dump "books" > books.sql How to exclude database data from backups To exclude database data from your output file you should include "-s" flag in your command pg_dump -s "books" > books.sql

Introduction to webshare API (navigator.share)

Image
navigator.share is a JavaScript API providing a sharing interface similar to native apps webshare API is supported on most updated mobile browsers Including Google chrome for Android Sharing is done by passing an Object with parameters "url", "text" or "title" to navigator.share function. For a webshare request to succeed you must supply at lest one of the parameters navigator.share returns a Promise upon being called "upon navigator.share({     "url": document.location,     "text": "I'm an example",     "title": document.title }) .then(resp => console.info("Successfully shared")) .catch(errors => console.error(errors))

How to stop moz dotbot from accessing your website

Image
DotBot is Moz's web crawler, it gathers web data for the Moz Link Index Dotbot obeys robots.txt rules before accessing your host machine so the easiest way to stop dotbot is by adding robots.txt rules that limit dotbot activities To forbid a directory let's say "login" add; User-agent: dotbot Disallow: /login/ Upon reading and parsing directives above moz dotbot won't dare access you sites login sub directory in it's craw routine To forbid an entire website's access include directives below; User-agent: dotbot Disallow: / Alternatively you can limit crawl rate by adding directives below "time is probably in seconds" User-agent: dotbot Crawl-delay: 10 I've attached an nginx log it's a trail left by dotbot along with it's ip and moz support e-mail address; 216.244.66.194 - - [19/Mar/2020:15:16:29 +0000] "GET /index.html HTTP/1.1" 200 13433 "-" "Mozilla/5.0 (compat

How to set content disposition header for nginx server to force content download

Image
Nginx (pronounced as engine x) is an HTTP server, reverse proxy server, as well as a mail proxy server Nginx is well known for its high performance, stability, efficiency, rich feature set, simple configuration, and low resource consumption. content disposition headers direct web browsers to save content instead of attempting to render it To set content disposition open your desired server configuration in "/etc/nginx/sites-available/" within your configuration add code below within your server {block} location ~* (mp3|ogg|wav)$ {     add_header Content-Disposition "attachment"; } mp3, ogg and wav are example file extensions matched by regular expressions rules Test configuration by acessing mp3, ogg and wav files from your webserver Alternatively you can force custom filenames as shown below "$1" substitutes filenames sent to clients. As an example its value corresponds to the requested file's extension lo

Reasons why you shouldn't consider hosting on github pages

Image
Github pages is a service for deployment of static websites normally software documentation and blogs Github pages is available on all public github repositories and on premium accounts it extends to private repositories as well. So what's not to like about it. hmmmm think about it. that's too good to be true It's not a secret that "the only free cheese is served on a mouse trap" 1. "Downtime due to maintenance" Every now and then github pages websites undergo an annoying and imaginary maintenance that causes undesirable user experience especially for professional websites. 2. "Slow deployment" I've been using github pages to host my static website with less than 10,000 pages deployment process knocked my entire site offline for 10 mins again that's unnecessary downtime sometimes it extended to days 3. "uninvited cloners" So you put your site out there few days later 50 clones uninvited unwelcom

How to set content disposition headers for express nodejs apps

Image
In express nodejs apps you can force the user agent "browser" to rather download content instead of displaying or attempting to render given content within the browser. In this example assuming you're using express.static to serve content pass an Object as second argument to express.static function An Object with configuration parameters; const config = { setHeaders: res => res.set('Content-disposition',  'attachment') } In your code replace "path/to/media/" with the path pointing to the static content. app.use('/media/', express.static('path/to/media/', config)) To test try accessing content at /media/*

HTML minifier module for Nodejs

HTML minification is a process involving striping off unneeded, abundant or otherwise unused HTML attributes and elements without affecting the webpage appearance. minification is useful for statically genetated 'serverless' web application webpages as it delivers easy to digest minimal webpages html-minifier is free and open-source npm nodejs module written in JavaScript for minifying HTML documents, as compared to similar nodejs html minification modules html-minifier proves to be pretty fast, flexible and efficient html-minifier module can be used to minify HTML code programmatically or alternatively you can minify HTML code using global commandline module Npm module Installation To install module in your terminal type npm i html-minifier To install commandline version of html-minifier in your terminal type npm i -g html-minifier usage: html-minifier [options] [files...] options: --remove-comments Strip HTML comments --remove-empty-attributes Remove all attri

Open-graph meta data tags introdution

Open-graph elements are meta tags that contain extra meta data of a webpage open-graph is used by Facebook to create website cards for urls shared on it's platform  cards contain website image thumbnail and as well as title, description, type and url open-graph meta tags have a property attribute containing a property prefixed by "og:" For example; <meta property="og:image"  content="image-url">

Solutions to blocked URLs on Facebook

Facebook allows sharing links on it's platform but in order to protect it's users from accessing URLs containing malicious content Facebook on a regular scraps content on shared URLs effectively raising an alarm if content shared goes against Facebook community standards or in short it's content is forbidden on the Facebook platform, Forbidden content may include potentially malicious crafted phishing websites or websites spreading malware among others Facebook may as well ban content flagged spam either reported or flagged by Facebook moderating algorithm "Facebook sheriff" You wouldn't want to find your website 'spam-list handed' you should avoid that There's no way to redeem a website flagged as a blocked website on Facebook except other non viable alternates such as completely changing your domain or using another sub-domain Facebook may as well ban content containing banned URLs in the meta open graph attributes To resolve open-graph sha

How to remove null elements from array in JavaScript

Every now and then arrays normally tend to have null or otherwise empty elements Array filter is a specialized JavaScript function for filtering array elements found to be matching a given criteria for example; const arr = ['max', 'duke'] In order to remove duke from elements of the array you can do it as follows; arr.filter(name => (name == 'duke' ? false : true)) // returns ['max'] You can filter empty and false elements as well, using a similar syntax as done above; const arr = ['max', null, 'duke'] arr.filter(name => name) // ['max', 'duke']

How to strip out html using regular expression in JavaScript

Regular expression isn't a very viable solution for manipulating html due to the complexity of html syntax in the browser it's recommended to create dom elements, appending html source code and then manipulating it using built-in dom querySelectors that has few drawbacks especially for environments without a dom take for instance nodejs You can use regular expression replace function as; const str = "<b>John swana</b>" str.replace(/(<([^>]+)>)/ig, "") // John swana And that's it

Es6 new features summarized round up

Escmascript es2017 or better known as es16 is the edition after the famously popular es15, In this edition there are only two new additional features the exponention operator and Array.prototype.includes() function exponention operator ** Operator is a short hand method used for raising numbers to their power Its syntax is similar to native operators such as '+' Addition and '-' (minus) for subtraction Example usage Initially to raise a number to the power you would need to use math library pow function as; Math.pow({number}, {factor}) Since es2017 you can simplify the operation above down to simply as; {number} ** {factor} Example as; 5 ** 2 // Giving you 25 Array.prototype.includes () Array includes is a feature similar to a pre existing function array.indexof() as compared to array.indexof() array.includes() function notably returns a true  boolean on matched value, and false if value not matched Examples on how to use 'array.includes ()' funct

unused css rules tree shaking elimination nodejs

Unused css rules elimination process is a lot more like tree shaking done by JavaScript bundlers for instance if you're familiar with how webpack eliminates dead code as a result tree shaking generates a much smaller bundle with only essential code Purifycss is a nodejs npm open source package that eliminates unused css You can use purifycss to remove excess css from libraries such as bootstrap, materal design lite to name a few, Installation You can get "purify-css" npm package from the package manager by typing in your terminal; npm i purify-css To install globally add -g flag; npm i -g purify-css Basic example usage; You can use css purify global cli package as; Syntax; purifycss {css} {html} Important flags; -m minify output -o specify output file name For example; purifycss *.css *.html -o css.min.css Output containg minified css rules will get saved to css.min.css

what is 'array.includes' function in JavaScript

Array includes is a feature introduced in JavaScript es16 or es2017 it's similar to a pre existing function array.indexof() as compared to array.indexof() array.includes() function notably returns a true  boolean on matched value, and false if value not matched Examples on how to use 'array.includes()' function The first argument is the value to be looked upon in an array; const arr = ['dogs', 'cats', 'snakes'] arr.includes('liars') // false arr.includes('snakes') // true arr.includes('lizards') // false I hope you get the concept

'**' exponential operator in JavaScript

** Operator in an es6 Escmascript feature a short hand method used for raising numbers to their power Its syntax is similar to native operators such as '+' Addition and '-' (minus) for subtraction Example ussage Initially to raise a number to the power you would need to use math library pow function as; Math.pow({number}, {factor}) Since es2017 you can simplify the operation above down to simply as; {number} ** {factor} Example as; 5 ** 2 // Giving you 25

How to make a Snake Game using JavaScript and html5

Image
I compiled stapes to create a game similar to Nokia developed, popular game called 'snake' Snake was first developed by Nokia, programmed in 1997 by Taneli Armanto and published on Nokia mobile devices,  It was introduced on Nokia model 6110, 3310 from 2000 and later the game was rebranded as " Snake Xenzia " Included on later mobile phone models I made a version that is more simplified and more beginners friendly, It's based on the same idea of making a snake that grows as it eats stuff and the score increases as it grows I'm implementing this whole game in pure vanilla JavaScript and a taste of html5 canvas, In this project the canvas is used as a renderer for the game's visual output concepts and initial ideas I got the idea while doing another retro gaming project, i thought it would be good too if i created this game, from start my plan had been simplicity and making this game easy to implement, So to simplify everything i had

How to create zip archives in nodejs

I'm going to compile ways in which you can create archives compressed using zip algorithm in nodejs or a similar JavaScript runtime. node-zip is an open source zip archiving utility authord by daraosn and folked from jszip capable of compresding files into a zip archive and extracting zip archives in JavaScript. node-zip is available on npm you can install it in your terminal window by typing; npm install node-zip example usage const  zip = new require('node-zip')() zip.file('test.file', 'John Swana') const data = zip.generate({base64:false,compression:'DEFLATE'}) console.log(data) How to unzip a zip archive const zip = new require('node-zip')(data, {base64: false, checkCRC32: true}) console.log(zip.files['test.file'])

Basic commands to open, zip and unzip archives

zip  is  a compression and file packaging utility for Linux, Unix OS, MAC and MS zip utility comes handy with another companion program called unzip, unzip is used to list, test and extract zip archives Basic usage ; zip basic usage ; Zip command line program can be used to compress files as; zip -{flags} {package} {item} Example on how to zip a file using zip You can zip and compress a file as; zip pack.zip filename.mp3 Zip will get the command to package filename.mp3 and store it in an archive named pack.zip How to compress a directory with zip Directories can be archived using the -r flag You can zip and compress a directory as; zip -r bundle.zip directory How to unzip files using unzip unzip a companion program to zip is used to extract archives typed unzip followed by archive name to extract a package as; unzip  {filename} for example; unzip pack.zip

Tar basic commands to store and extract files

Targeted is an archiving program designed to package, store, and compress multiple files into a single portable package the name tar is an abbreviation for tape archiver Apart from creating .tar archives tar is also capable of compressing files using zip, bzip2, and gzip compression algorithms Tar flags c — compress directive x — extract directive t — tabulate contents f — specify filename z — use zip/gzip compression j — use bzip2 compression k — do not overwrite t — files from file w — ask for configuration v — verbose gzip flags d — decompress file Tar commandline commands syntax tar -{arguments} {params} Example tar commands tar -cf music.tar music.mp3 Tar archiver will be directed to compress music.mp3 into a tar archive named music.tar and save it in the current working directory tar -xf music.tar Tar will be directed to extract music.tar archive and save the constituent contents of the archive in the current working directory how to make a zip archives

How to install tfjs JavaScript library

Image
Tensorflow is a hardware accelerated JavaScript library for building, training, testing and deploying machine learning models on a JavaScript runtime environment. Installation through html script tag For use within the browser you can link to jsdelivr content delivery network using an html script tag as follows; <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.min.js"></script> Installation through npm package manager Alternatively you can install a self hosted version of tensorflow from npm, in your terminal type; npm install '@tensorflow/tfjs' Installation for tfjs-node on npm tensorflow has two nodejs packages made specifically for nodejs Installation for '@tensorflow/tfjs-node' This version is a cpu only version it doesn't utilize gpu to do the computing, install tfjs node by typing; npm install '@tensorflow/tfjs-node' Installation for '@tensorflow/ tfjs-node

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; "A".repeat(3) 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: Rest parameters 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

Introduction 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} = value for const it's done as; const {variable name} = value similarly with var; var {variable name} = value Scope 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) // undefined values remain accessible only within the if block Scope 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){    

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: MDN Destructuring assignment

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

Image
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

Image
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

Image
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/     |static/         |index.html     |app.js 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.

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

Image
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

Image
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]] //[[1,0], // [0,1]] const arrr2d = [[1,1],[0,1]] //[[1,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

Image
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; ipify.org is a free service that retrieves IP addresses in JSON format fetch('https://api.ipify. org ?format=json') .then(response => response.json()) .then(response => console.log(JSON.stringify(response))) // response {"ip":"--.---.---.---"} In nodejs you can use a package node-fetch Install it by typing; npm i node-fetch Or using curl, in your terminal type; curl 'https://api6.ipify.org?format=json' // response {"ip":"--.---.---.---"}

How to install git on a raspberry PI

Image
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 requir

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){     this.name = name } func.name instance property name is set to that of the first argument; const inst = new func('duke') inst.name // returns duke You can as well extend func to set name using 'this'; func.prototype.set = function(name){     this.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 promises const statusReport = function() {     return new Promise((resolve, reject) => {     setTimeout(() => resolve(), 10000)    }) } You can inquire statusReport as follows; const analysis = new statusReport() .then(() => console.log('hooray'), ()

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" onsubmit="handle(event)"> <input name="query"> <button>     submit </button> </form> You can pass an instance of a dom form to formData constructor as the first parameter; const handle = function(event) {     event.preventDefault()     const data = new formData(event.target) fetch('//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' How to create a constructor in JavaScript For JavaScript functions construction declaration can be made as follows; const greeting = function(name) {     this.name = name } greeting.morning = function() {     const name = this.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 message Once 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 {    

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 files As 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 interval You can use a twitter bot to promote an interest or a campaign unlike Facebook twitter is more tolerant on automated accounts I 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 all And 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 secret Twitter 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 JavaScript Loops 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)     console.log(seconds) }) expected output 1 sec 2 sec 3 sec 4 sec After 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 directory let'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 string JSON 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 data JSON.stringify is a method that converts JSON to a string its may be used for debug or simply to serialize JSON It accepts three arguments (JSON, FUNCTION, SPACER) JSON: maybe an array or object FUNCTION: Is an influencer it's a middle man that alters what is to be returned SPACER; Is a character used to indent or prettyfiy output For 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 JavaScript Object 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

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 others Access permission is dependant on the name and type of distribution of the operating system 751 perhaps :| How to go to your home directory Among 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 variable cd    --- 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 them import('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 characteristics const pets = { {name: " Jenny ", eyes: "brown"}, {name: "max", eyes: "blue"} } To iterate through the characteristics using for loop for (pet in pets) {     console.log(`${pets[pet].name} has eye color ${pets[pet].eyes}`} } Alternatively you can use objects.keys and object. entries for (element in Object.entries(elements)) }

Handy array functions every developer should know JavaScript

Array make a good means of data storage and manipulation in JavaScript if used well arrays are way better than objects especially if you're working with numbers Array.push (element) Its a method used for quickly appending an element to an array For instance const arr = ['code'] arr.push('eat') // ['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'] arr.unshift('sleep') // ['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 // eat Array.pop () Is a method an array property similar to shift that removes the last element of an array and retu

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 application fun 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.jar Execute your application java -jar hello.jar If 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 JavaScript To install kotlin using the Software Development Kit on Debian Ubuntu or Linux environment. First install the SDK using Command: wget -O sdk.install.sh "https://get.sdkman.io" bash sdk.install.sh To install kotlin Type the command: source ~/.sdkman/bin/sdkman-init.sh sdk install kotlin To 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-headless To confirm installation type the command: kotlin -version It should return output similar to one below Kotlin 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 language Kotlin 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 language Kotlin applications must have a main method. println is used for text output just like in Java fun main() {     println("hello world") } After compiling the output should be "hello world" Basic s yntax variable declaration Variables are declared using

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 page window.location.hostname  returns the domain name window.location.pathname  returns the pathname segment of the url window.location.protocol  returns the web protocol of the url window.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 implementations. it'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 webpage Syntax window.location.asign('https://example.com') or simply like window.location = "https://example.com" or simply omit window location = "https://example.com"

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 listener Example 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(event.target.get attribute('class')))

JavaScript event prevent default

JavaScript event preventdefault is a method for intervening event actions preventing normal events behavior Take 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 attribute preventdefault syntax /// HTML <a href="/" id="home">     home </a> /// JavaScript home.addEventListener('click', function(event){     event.preventdefault()     // 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) {     console.log(tux)     // tuxedo     console.log(cow)     // cow     console.log(dog)     // 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 operator const {cow, dog, tux} = mascots console.log(tux) // tuxedo console.log(cow) // cow console.log(dog) // puppy