Monday, 17 April 2017

SinonJS - the spy

The example is more of a revealer to an error that can be quite vexing in sinon, node js parlance.

It is called "attempted to wrap undefined property as function" as if it were an attempt to murder.

The case in question is that of a call made to sinon's spy method

var theSpy = sinon.spy('get');
If used as such, this line will throw the error. The trick is to use the container that contains the 'get' method as the first parameter:

Not much of a sinon, but a spy nevertheless, much like Johnny English!

The spy method of sinon helps you to understand how many times a method call happened and it can also help you understand that if at all a call did get made to a method. This can be helpful in calls over the wire, say, http.

You need mocha, sinonjs and nodejs to run the example.

Below is the code.

var assert = require('assert');
var sinon = require('sinon');

var http = require('http');
var api = require('../myapi.js');
describe('testingBlogPost', function() {
var theSpy = sinon.spy(api,'get'); //  the first parameter will resolve the undefined property method

it('should get result to compare', function() {
var expected = 'Moved Permanently';
api.get(function(err, result) {
api.get(function(err, result) {


var http = require('http');
function myApi(){};

myApi.prototype = {
get: function(req,res) {
var req = http.request({
hostname: '',
path: '/2017/04/how-to-setup-middle-game.html'
}, function(response) {
var data = '';
response.on('data', function(chunk) {
data += chunk;
response.on('end', function() {
module.exports = new myApi();

And the result, because the get method was twice called

Of course, another reason for writing the test also helps in knowing what if bots were to call posts on my blog! :)

Happy spying!

Tuesday, 4 April 2017

How to setup the middle game

It was way back in 1985. I was the captain of my college chess team and we were playing the Delhi University's Inter-College Chess Championships.

Our college, Sri Venkateswara College, had been a finalist in the previous year (first time in the history, I recall somebody saying it during the sports meetup) and since the captain had attributed that it was largely due to my efforts, I was offered the captaincy by the college principal and the Sports chief! I can just about recall that I barely managed to accept the captaincy because I was hugely reticent then.

We were playing the winners - Kirori Mal College - and they were formidable.

I had played the different boards in the previous championships so I knew how the order was set and the strategies played.

I knew that there were the smaller fishes that I could always attack, later, as the tournament format, being the swiss rounds, progressed and eyed the larger ones for just a point or a two. So, I decided to play the weakest on the top board, against a later-to-become-Delhi State champion (or possibly the then Delhi state champion), and myself played the 3rd board, hoping to at least fetch a half point for the team.

I don't recall the outcome much but I do recall that I decided to play the 2nd board in the next round against - another formidable team - the St. Stephen's ...! It had another well-known player on the top board and the second board was played by a fair girl, who, too, was a No.2 in the Women's category of the State level!

I decided to chance my luck against her and played the 2nd board!

To put it in perspective, I remembered this game because this post is about how a good opening can lead to a good middle game and a solid end game.

She played the French defense.

I say that with reverence.

Ever since I had eyed her on the floor, tall, fair, slender and very good looking, I had developed a crush on her. And there I was, playing against a ...e6!

In all my preparations, that mostly included games of the Rusian Grandmasters and a Chess Mate subscription that I had won in an Open tournament, the French Defense was the one that I had avoided, not because I did not like it but because Fischer demonstrated some stuff that put me off it forever!

I should have known. A slender soft female would go for the French Defense. It is docile, meek and extremely defensive. Of course, I loathe the opening and not just because I lost the game even before it reached the middle game for me to get my combinations going, but because, at that age, it seemed like I had lost some right to woo her! I still remember that feeling - a squashed out Bertie-Wooster-type-after-meeting-Madeline kind.

Since then I rarely play e4 in games of importance.

So I decided to check out d4 when I started playing Chess again around the early 2000s, with opponents who were four former Delhi State Champions, at an outdoor park, where we gathered each day over many months to play Chess, and which led to my book on Chess!

The only weapon that I had or could muster, against their class and experience, was to play some unconventional Chess and I started to explore Bf4 after Nf3 and not C4, as is the normal.

One of the former champions, the co-author of the book, "Analytical Games of Chess", remarked on why I didn't play the usual Queen's gambit C4, and the reason behind the move. I said that I am very comfortable playing the move. That was not the whole reason.

The real reason is that Bf4 provides the means to attack the black queenside as well as be in a position to switch to a kingside attack, without being obvious.

Another key element, in this strategy, is to sustain the diagonal's importance and make Black pay for moves like Be7 (instead of Bd6) and so, it is equally important to play h3 as soon as Black plays Nf6.

And yet another advantage is that it guides Black to play Ne4 as Nh5 could make no difference as the Bishop could retreat to h2, without causing any double pawns at f4 or g3.

Like so.

Take no notice of the Computer saying it is +0.80. It is just bunkuming itself! A human would not have played g5 before castling, anyway.

The middle game becomes a cake walk.

As I said, take no notice of what the computer thinks of a position.

It says "Checkmate" at the end, too, when it got checkmated - as if it was announcing it to me! :)

Below is another very good game to demonstrate the power of Bf4, in which the white Bishop in h2 makes life miserable for the entire diagonal, all the way to b8 and, to protect the c7 pawn or free the pressure, black has to think of a different strategy to play the Knight via d7!

Check out the difference in the two games - one, played by a computer and the other, by a human - played with the same strategies but the attack varies, depending upon the moves by Black.

The key to playing Bf4 is to have a strategy that mobilizes the a, b and c pawns to build the pressure on black's queenside. More often than not, it works.

It is important to note that with Bf4 and no c4, the White Bishop, in the opening, must be played, always, to Be2 and not to Bd3 or to Bc4 if attacking black's queenside is to succeed. Always. 

Sunday, 19 March 2017


A new vision proposed by the Prime Minister of India, Mr. Narendra Modi, in the India Today conclave, 2017, in which the new India would be all about opportunities and hard work, sets the tone just right for out of the box solutions to some persistent problems over the past century.

That the Prime Minister has announced more reforms in redundant legislative and legal practices and laws is another right step in the right direction for the BJP led government that promises the people of India for some breathtaking changes and initiatives in the near future. The existing techniques used by the human resources, administrative affairs, planning have more often than not led to more problems than resolving them.

The approach, as the Prime Minister said in his address, has to change into a more holistic one. Current planning, at least since 2000, has heavily focused and relied on the Information Technology sector to provide jobs and stabilize the employment ratio but this has caused innumerable side effects like nurturing rogue real estate manipulators, which has resulted in greedy land grabbers taking control over a region, to the effect that even the politics of the country got changed due to it but more importantly, it increased the corruption mafia's hold on many administrative matters as well as affecting the business due to the swing in favor of the greedy manipulators and the whole situation gets back to square one for the people.

To reduce the burden of employment in the IT industry, which projects 'lottery' like dreams to the education sector that there are more riches in the IT jobs than in show biz, a parallel and alternate means to earn should be made available to the people so that anyone, of any age, could do some work and earn money from the government directly, increasing the bonding of people with the country and the government, thereby reducing the scope to favor criminal ways to earn money and reducing the scope for terrorism in the country, and make way for a robust economy with a steadily improving employment ratio. The mafia mentality that ultimately shows up as a mob culture to the outside world, when activists whip up chaos in cities, is actually a product of this system of the 'controlled' and 'organized' sector of the country that has, somehow perfected, 'organized dishonesty'.

So, the agenda-based 'planning' measures and processes should be forsaken for newer approaches with a focus on a leaner approach in governance.

There are only two elements that bother the progress of the country - one, work and the other, money. With just these two elements, the approach is to provide a new model of work - earn from anywhere doing anything!

This new model of work, earn, from anywhere, for any type of work, would also reduce the burden on the government to plan for employment with uncertain data and improve the unemployment scenario in the economy plus it will greatly reduce crime as the means and opportunity to earn for everybody will be readily available.

Other advantages of such a work model are that it will enable social changes with increased, healthy interactions between the people and the various segments of governance. For instance, in India, the saddest of all social evils is the fear to help a rape victim or an accident victim even if the inclinations are right, due to the many pitfalls with hospital regulations and the police, which is, anyway, the most abhorred unit in the country.

When this model of work is implemented, due to the associated evidences of work (that need to be submitted for the government to approve that it is part of the category for which a payment rate is set), the transparency will act as deterrent for the corrupt or ignorant laws 
and the confidence, that the government knows that the accident victim or the rape victim was helped by this citizen and vouched for by a witness, will help reduce the fear of getting framed, .


A government enabled/driven. powered service that would provide for means to earn money by doing any work that a citizen may want to like cleaning the street, helping an accident victim (which is the most troublesome and feared of events due to the various red tape associated with the hospitals and the police and the bribes associated with it would majorly improve public welfare because this service model will not only have everything documented and the police that there would be no possibility that the person helping an accident victim would not get harassed for doing a good job), catching some miscreant on the streets, providing food to some needy, helping an old woman or man crossing the street, fighting against over-charging auto rickshaw driver or helping a girl in distress or helping some needy and if the government cares, just about anything that is considered useful for governance.

This model would accept work done on the streets or at any place, which could be logged in by the citizen with a valid Aadhar card and attested by any other citizen that "Yes, the work for which the person is seeking compensation has been validated" with a screenshot or a mobile picture uploaded to the server for which adequate, appropriate compensation could be remitted by the government, online, directly into the work submitter's bank account or even a PayTm account.
The country has lots of problems - cleanliness, waste management, fringe elements that have no clue nor business to be in any region as they have nothing to do and this lot numbers in millions, in the country, traffic discipline, bribery as a culture in many departments of many organizations (even now, in 2017, driving license can be obtained through bribes), tax evaders at the level of employees of well paying organizations where producing and getting away with fake travel bills, fake fuel bills, undeclared income, false declarations of investments, fake rent receipts to claim HRA is all considered as the 'normal' and anyone who thinks otherwise loses their job or is targeted - and the diktat that it is the government that should handle all the problems and provide solutions is the wrong attitude and the chief cause for such blatant practices to be there in our daily, routine life. 

Tuesday, 7 February 2017

"Lazy" vs "Greedy" Design

"Convention over Configuration" always intrigued and fascinated me although I knew, deep in my heart, I did not understand a word of the trilogy of words! So, when I chanced upon this opportunity to relate two examples of design that I happened to come across (one, due to my recently, of some years, acquired liking for simplicity and two, as a user with limited resources), I chose the middle path - not to coin any new set of fancy words but to rely on the existing set of terminology doing the rounds in technical forums - "lazy" and "greedy".

The process of authentication has become far more refined and varied than it used to be in the days when WSE sounded like some Chinese royalty among peasants so, rather than go into all the intricacies of "packaged" libraries or encryptions of the Da Vinci code type, I decided to check out the OTP (One Time Password) with Time and Space as the chief factors of ensuring the authentication cycle.

The "Time", as in the 'time' that the OTP gets sent to the 'time' that the user uses the OTP and the "Space", as in the 'space' between the email window and the application window. For this form to be called a "lazy" design is not exactly correct if not contrived, but when put in relief with the other forms of authentication doing the rounds, it does have a "lazy" tinge to it even though, put to some severe test, it may break due to the space factor but the 'laziness' becomes pronounced when seen in relief with the following description of a 'design' that I found on a gateway (and possibly, that which exists, across the world!) - that of a payment gateway authenticating the OTP sent to the user by automatically picking up the OTP sent by SMS to the user's mobile and then submitting it for processing to the gateway!

There is a huge flaw in such a design that is far too greedy in its functioning and the greediness can be better perceived with an elaboration using a Context and a Domain diagram but since there is no real need for me to prove a point or score one over the application (anyway, it is my blog so what I say is always right ! :)) designers, suffice it to say that it fails a test scenario, where the network or the network signal of the user's service provider gets broken and the session, too is lost, or quite simply, in a dual SIM mobile, the user simply switches on the SIM (which is the registered mobile for the payment gateway to send the SMS to) a few seconds or minute after touching the "Pay now" option (obviously, this is a dual sim mobile phone app test scenario).

There is a hilarious story that explains the parallel human behavior (I am a strong believer that software design evolves (not just out of tests as in TDD) out of the culture of the region) of such a scenario nutcase that goes, "I know, I know what he 'thinks'" to another nutcase that calls it up to ask for an 'update' (with no possibility of corroborating on a 'thought' of another person (leave aside the thought of the same person) but it gets best explained by actually knowing the nutcase and its group of  'girlfriends' (ie., because the nutcase 'thinks' (it is quite possible for roles to get switched here due to the language and interpretation ! :D) that the other person 'thinks' that it is talking to a girl, it uses words that one uses only with girlfriends while, on the other end of the phone, the man may simply be cursing the nutcase or quite simply, the mother (as in 'Psycho's mother)!

To get back to the bug, this means that while the app tries to desperately read the last (most recent) SMS received and does not find it and gives the user the option to use the "Regenerate OTP" option and one scenario is that the user touches it as a selection, by which time, the previously generated OTP gets sent and the app once again, goes into the automatically submit OTP option! This now results in the second scenario that of the "Enter OTP manually" option, which if the user uses results in the wrong OTP getting entered into the text area because the newly generated OTP is queued but has not yet been received by the user (for whatever reason, one being that the user's messaging space is full and the other being, the network) and if the user loses patience and presses the Regenerate option and deletes the earlier SMS then it results in another cycle of confusion!

Sometimes convention is not the best of reasons to use or follow in design (especially in software design) and neither should too much of user friendliness be the yardstick to judge a design as the right design because over-zealousness, in software design, actually translates to "greedy" and even though a "greedy" design may work but an "over zealous" design will (or must) fail as the human factor, that of using time and space, in contrast, will always succeed!