Translate

Thursday, 9 August 2018

Master JSON in 30 minutes

Nowadays, programming can be done just with the help of Google and GitHub, so many free, online resources are available! So, how does one justify an online, paid training?

Obviously, by differentiating the contents, substance and the goal of the training by including some aspect of the training that is either not there in online bundles of courses as offered at Udemy or adds so much value because it can be delivered only by an expert.

Although I do not claim to be an expert except in professional forums where such words are used to stress that "Ok, you can safely rely on this guy's knowledge because he knows what he is saying", I do claim the years of experience in software development, in open source software development and in the Agile world that I can put a stamp to a module that I designed as an online training resource, possibly leading to learning capsules for online learning portals like Udemy.

I will update the topics in this series of earning capsules in forthcoming weeks, so please do stay tuned for a great experience in online training.

For now, take a look at an extract from the first capsule "Master JSON in 30 minutes".


Monday, 18 June 2018

Single page web app to single file web app

If the concept of a single page website was a novelty, then the single file web app is a wonder.

Without using the commonly used terms for describing the single file web app, let me describe what the file does -

1. it listens to a request using the HTTP or the https protocol and can respond with JSON. Is it a REST API?
2. it can contain multiple route handlers for a web request. A web server?
3. it is written in plain javascript or es6. A node.js web app?
4. it uses express.js to handle the request, response. A node.js web server?
5. it spins itself up as and when required to serve requests. Wait! Is it an appEngine?
6. it provides for modular services. Ok! Is it microservices?
7. it is a function that can handle web requests hosted on the cloud.

Alright, it is a lambda function or a cloud function.

What the Google Cloud Function (GCF) does as a FaaS (Function as a Service) is well-documented but it is in the enhancement of the DX (Developer eXperience) that the GCF scores hugely.

For an architect, it helps ensure that there are no async calls on the main app.js file, or promises used that don't get fulfilled because the app.js is the main server file that is only concerned about setting up the server and to start listening after running through a sequence of synchronous flow.

Like the moron in the '3 idiots' movie (Hindi movie) who simply rattles off memorized words, from a prepared speech in an unknown language, as it got interpreted in its mind, without bothering to understand the meaning of the sentences used, the app.js file in the node.js, expressjs context, simply runs through all the statements, dumbly - its sole purpose being to reach the end of the file for the magical server.listen statement!

Not so with the GCF.

The GCF simply spins up, executes the lines, intelligently, and once the request, response cycle is done, it shuts down by itself. So, no worries about load testing or listening to requests when there are none as in the app.js context or bothering about server resources! The GCF is a serverless server.

The GCF handles thens and catchs but most importantly, with its ability to act as a route handler, with the help of Firebase-functions, it completes the requirement for the most robust, lean web server - a single file web server. The GCF, by itself, cannot handle/parse parameters or query strings passed via the URL, but with firebase, it can!

Here is a simple GCF [Edit: link removed] - Edit: One of the pitfalls is managing the connections in a cloud function as each time, a new container instance may execute the Cloud function causing new connections with the Cloud Database server so, it becomes more than challenging to keep or share db connections!

Of course, the workaround is the infamous "Allow access from anywhere" option but then this is where the prudence in using something like a firebase library lies because it enables authorization token to be submitted in the request URL and so the infamous workaround may actually become an ideal workaround if not the solution.

And yes, with the GCF, you can query external databases in other cloud regions like a Mongodb Atlas database and the speed of the response is phenomenal! 

Thursday, 3 May 2018

A binary converter in typescript and a reference to blockchain

While writing a binary to a decimal converter in Typescript, I came across the idea of using the example of a class of students in which every student is given a binary value and asked to convert it to a decimal value.

Add a little imagination to the idea and you can come up with an interesting parallel of how a BlockChain node functions - imagine a guy not sure if the steps that he has used to convert a binary to a decimal value is correct or not and asks the nearest neighboring girl for the answer and she gives him the SHA256 hash value of, let's say, 268 (the solution), the decimal equivalent of 100001100, which is 8b496bf96bbcc9e5ac11c068b6cfb00c32f9d163bb8a3d5af107217499de997a!

Now, the guy has the hash value and knows that till his steps yield the decimal value whose sha256 hash value matches the hash given to him, he must process the steps. This, in effect, explains what happens in mining a blockchain node.

Anyway, the code is as below: (Edit: a note on refactoring: although the code has been written with a unit test and the test was written first, it is only partially refactored, for reasons of obfuscating the logic.

Point is, many bots or maybe just humans ;) mine for code but don't bother to even leave a note of thanks and when I noticed this way back in the early 2000s, I did not bother to correct Blogger's tendency to eat up the angular brackets as used in C code where the #include statements require the < and > and even changed all the return statements to return 1 instead of 0. Make them think, don't you think? :))

// binaryconverter.ts

export default class BinaryConverter{
convertBinaryToDecimal(n){
let z=1,b=0,val=0, zeroFlag=false
b=n.length-1
for (let a in n){
var num=0
for (num=b;num>0;num--){
z*=2*n[a]
}
if (num==b){
z=0
zeroFlag=true
}
else if (num!=b){
val+=z
z=1
}
b--
}
if (zeroFlag==true && n[n.length-1]==1)val++
return val;
}
}

and the mocha test,

import BinaryConverter from '../src/ComputeBinary.ts'
import {expect} from 'chai'
describe('Computation test',()=>{
it('to check if binary conversion is successful', ()=>{
var b=new BinaryConverter()
var bin='100001100', binResult=0
binResult=b.convertBinaryToDecimal(bin)
expect(binResult).to.equal(267)
})
})

The test result: I include the screenshot, usually, to complete the cycle of learning for the reader as the command line switches and flags, if not known, will not compile or may produce a different output.

If your test does not run from your default installation, install typescript and ts-node using npm install - explained in previous posts related to typescript.


I will try to build on this example with a blockchain reference in future posts

Monday, 30 April 2018

Some Truffle tips and Blockchain blocks

Platform: node.js/Windows
Technology: BlockChain

Smart Contracts, Smart Money and Smart Wallets - be your own bank!


The BlockChain is now a famous Go-To-Technology that has innumerable possibilities for peer-to-peer interactions for exchanges of various kind like a currency, a representation of an asset, a virtual share, a proof of work, ownership etc. 

The path to adopting a new technology or framework can be really vexing if the resources online are less.

Ironing out the vexes

One very simple problem with Truffle, on Windows ie., is caused by how Windows processes the file extensions from the command line as well as a possible buggy Ganache GUI distribution bundle. Edit: Instead of the .appx file, download from this link, which provides a fully working installer for Windows.

First, the most common problem with truffle.


On node.js, after installing truffle, the first thing that you need to do is remember to either,

1. Use truffle.cmd because, by default, the Windows command-line processor runs the truffle.js file instead of the .cmd file. Simply use truffle.cmd compile or truffle.cmd migrate or any other command when using truffle.

2. Exclude the .js extension from the PATHEXT environment variable

3. Change the .js filename to something else so that the .cmd file gets executed.

Second, git clone the ganache-cli from  https://github.com/trufflesuite/ganache.git

Once cloned, open the node.js command prompt (this is assuming that you have npm installed truffle), you can do npm install and npm start from the git clone repository folder. 


Commands after cloning ganache-cli:
  1. npm install 
  2. npm start
from the cloned repository.

If you face the Microsoft Script runtime error, make sure that ganache is added to your PATH environment variable.


The cli will start and listen in to a port configured in the truffle.js with values as below:


 networks: {
    development: {
      host: "127.0.0.1",
      port: 7545,
      network_id: "*" // Match any network id
    }
  }



What Ganache does is, it creates a virtual Ethereum based blockchain that acts as a Private net (the mainnet is the live or the production network) with some dummy accounts, which you can use for testing and development without having to use any real ethers, the gas!
A personal Ethereum Blockchain.


The mnemonic is a 12-word combination that can be used to recover a wallet if you have forgotten the details required to access your wallet. Of course, using the mnemonic combination will result in creating a new wallet.






Once your personal blockchain is created, you can download and install the 
geth and Ethereum Wallet to work with your Ethereum based blockchain apps.


What all this means is that you can act as a bank by issuing your own token that will become a cryptocurrency that you can use for interchanges between your friends, club, for betting platforms etc.


Happy creating your own bank with cryptocurrency!