JavaScript: The Singleton Pattern

The singleton pattern is the most commonly used design pattern and one that you will probably is more than any others. It provides a great way to wrap code into logical unit that can be accessed through a single variable.

The Singleton design pattern is used when only one instance of object is needed throughout the lifetime of an application.  

In JavaScript there is different way to achieve singleton object than any other object oriented supported language (Java, C++). In JavaScript Singleton pattern have many uses, they can be used for Namespace, which reduce the number of global variables in your page (Prevent from polluting global space), Organizing code in a consistent manner, which increase the readability and maintainability of your pages.

There are two important point in the traditional definition of Singleton pattern

  • There should be only one instance allowed for a class and
  • We should allow global point of access to that single instance

Let me define singleton pattern in JavaScript context:

“It is an object that is used to create namespace and group together a related set of methods and attributes (encapsulation) and if we allow to instantiate than it can be instantiate only once.”

In JavaScript we can create singleton though object literal, However there are some another way but that I will cover in next post.

A singleton object consists of two parts: The object itself, containing the members (Both methods and attributes) within it, and global variable used to access it. The variable is global so that object can be accessed anywhere in the page, this is key feature of the singleton pattern.

JavaScript: A Singleton as a Namespace

As I have already stated above that singleton can be used to declare Namespace in JavaScript. NameSpacing is a large part of responsible programming in JavaScript. Because everything can be overwritten, and it is very easy to wipe out variable by mistake or a function, or even a class without even knowing it.

A common example which happen frequently when you are working with another team member parallel,

/* Declare globally */

function findUserName(id){
    
}

/* Later in the page another programmer 
added code */
var findUserName = $('#user_list');

/* You are trying to call :( */
console.log(findUserName())

One of the best way to prevent accidentally overwriting variable is to namespace your code within a singleton object.

/*  Using Namespace */

var MyNameSpace = {
    
    findUserName : function(id){
        
    },
    // Other methods and attribute go here as well 
}

/* Later in the page another programmer 
added code */
var findUserName = $('#user_list');

/* You are trying to call and you make this time workable */
console.log(MyNameSpace.findUserName());

UML Diagram for Singleton design pattern:

CaptureUML diagram for the same is given below. This implementation provide global access to the object through static method getInstance().

Singleton Design Pattern Implementation

/* Lazy Instantiation skeleton for a singleton pattern */

var MyNameSpace = {};
MyNameSpace.Singleton = (function(){

  // Private attribute that holds the single instance
  var singletonInstance;  
    
      // All of the normal code goes here 
      function constructor(){
          // Private members
          var privateVar1 = "Nishant";
          var privateVar2 = [1,2,3,4,5];
          
          function privateMethod1(){
              // code stuff
          }
          
          function privateMethod1(){
              // code stuff
          }
          
          return {
              attribute1 : "Nishant",
              publicMethod: function(){
                  alert("Nishant");// some code logic
              }
          }
      }
      
      return {
        // public method ( Global access point to Singleton object) 
        getInstance: function(){
            //instance already exist then return  
           if(!singletonInstance){
                singletonInstance = constructor();
           }
           return singletonInstance;           
        }           
      }
  }
})();   

// getting access of publicMethod 
console.log(MyNamespace.Singleton.getInstance().publicMethod());

The singleton implemented above is easy to understand. The singleton class maintains a static reference to the lone singleton instance and return that reference from the static getInstance() method.

Random PhantomJS Review

A well-designed video tutorial by Stefan Judis.

In Video Stefan has covered every scenarios where you want to programmatically capture web contents or want to access and manipulate webpages with the standard DOM APIs, or interested in monitoring page loading, PhantomJS is the tool you will look for.

 

Rapid PhantomJS video tutorial by Stefan Judis will prove an excellent guide in learning PhantomJS. Three sections in this video tutorial will teach you from basics of PhantomJS to automating your workflow with included tests based on PhantomJS.

 

Basics are covered in Section 1, PhantomJS – Introduction. In most video tutorials in the Internet, you will see that author will first install and then explain the topic. But here, Stefan has taken a different route. He first has run few examples to prove the usefulness of PhantomJS. I believe every reader will like this approach since it will help everyone in understanding the use cases of PhantomJS. Secondly, in introductory section only, he has covered basics of error handling, ‘phantom’, ‘system’ and ‘webpage’ APIs. For more detailed information about the APIs, you can visit http://phantomjs.org/api/.

 

Various aspects of frontend unit testing is covered in Section 2, Frontend Unit Testing using PhantomJS. I am a big fan of unit testing and therefore, this section can prove to be very useful and informative. Author has covered following topics in this section:

 

Using PhantomJS in Terms of Rendering

Using PhantomJS in Terms of Page Automation (Reading)

Using PhantomJS in Terms of Page Automation (Writing)

Using PhantomJS in Terms of Network Monitoring

Using PhantomJS in Terms of Testing

 

All the examples in the above sections are very practical and well explained. Also, every example is a continuation of the previous example which makes it easy for the reader to understand and implement the examples. Because this way, you can start thinking very easily how to use these concepts in your use cases.

 

Another note is that PhantomJS can be used with Karma, the JavaScript test runner for running your unit test cases in a headless browser.

 

Final aspect of the course is Section 3, Automating Your Workflow with Included Tests Based on PhantomJS. In any project as a developer you are not going to run your test scripts manually. You will look for options to automate your test cases/ scripts. This section will show you setting up of make, npm scripts, grunt and gulp scripts to run your PhantomJS scripts. This is a good ending of any course for any reader.

 

From above discussions, we can conclude that this is a well recommended course for anyone who wants to start PhantomJS from ground up.

C Programming Important notes

1) void *realloc(void *ptr, size_t size);
-> realloc changes the size of the allocated memory pointed to by the argument ptr
-> newly allocated memory will be uninitialized
-> you can pass a NULL ptr safely to realloc
-> realloc may move your data to a new pointer and free the memory at the old pointer. It will return the new pointer, or the old pointer if the data is not moved.

2) Calloc
-> allocates a region of memory large enough to hold “n elements” of “size” bytes each. Also initializes contents of memory to zeroes.
-> void *calloc (number_of_blocks, size_of_each_block_in_bytes);
-> The allocated region is initialized to zero.
-> void pointer (void *). If the allocation succeeds, a pointer to the block of memory is returned.
void *calloc(size_t nelements, size_t bytes);

Malloc:
-> allocates “size” bytes of memory.
-> void *malloc (size_in_bytes);
-> The contents of allocated memory are not changed. i.e., the memory contains unpredictable or garbage values. This presents a risk.
-> void pointer (void *). If the allocation succeeds, a pointer to the block of memory is returned.
void *malloc(size_t size);

3) In theory, which is faster, the call to strcpy or the call to memcpy?

#include <string.h>
#include <stdlib.h>
int main(){
        char msg[12] = "Hello World";
        char buffer1[12];
        char buffer2[12];

        strcpy(buffer1, msg);
        memcpy(buffer2, msg, sizeof(msg));
        return 0;
}

Answer:
memcpy should be faster because it does not need to check every byte for a NULL, it is copying a known size of data.

4)Variables declared outside of functions or with the static specifier are always initialized to zero. Therefore this program has deterministic behavior.

#include <stdlib.h>
#include <stdio.h>
int* ptrToData;
int main(){

    if (!ptrToData){
        ptrToData = (int*)malloc(sizeof(int) * 10);
        printf("%p\n", ptrToData);
    }
    free(ptrToData);
    return 0;
}

5) Fortunately, C/C++/Java makes this simple.

* To write numbers in octal, precede the value with a 0. Thus, 023 is 238 (which is 19 in base 10).
* To write numbers in hexadecimal, precede the value with a 0x or 0X. Thus, 0x23 is 2316 (which is 35 in base 10).

6)
How to Write a Negative Value
When you write 0x23, you might wonder how to negate it. Should you write the minus sign before the 0x, or after it? The answer is before. 0x indicates that the digits afterwards are written in hex. – is an operator, so it applies to a non-negative representation. Thus, you write -0x23. which is equivalent to -35

7) Structure Member Alignment, Padding and Data Packing

http://www.geeksforgeeks.org/structure-member-alignment-padding-and-data-packing/
8: C Bit Fields : http://msdn.microsoft.com/en-us/library/yszfawxh.aspx
struct-declarator:declarator
type-specifier declarator opt : constant-expression

The constant-expression specifies the width of the field in bits. The type-specifier for the declarator must be unsigned int, signed int, or int, and the constant-expression must be a nonnegative integer value. If the value is zero, the declaration has no declarator. Arrays of bit fields, pointers to bit fields, and functions returning bit fields are not allowed. The optional declarator names the bit field. Bit fields can only be declared as part of a structure. The address-of operator (&) cannot be applied to bit-field components.
Unnamed bit fields cannot be referenced, and their contents at run time are unpredictable. They can be used as “dummy” fields, for alignment purposes. An unnamed bit field whose width is specified as 0 guarantees that storage for the member following it in the struct-declaration-list begins on an int boundary.

Bit fields must also be long enough to contain the bit pattern. For example, these two statements are not legal:

short a:17; /* Illegal! */
int long y:33; /* Illegal! */

This example defines a two-dimensional array of structures named screen.
struct
{
unsigned short icon : 8;
unsigned short color : 4;
unsigned short underline : 1;
unsigned short blink : 1;
} screen[25][80];

7) C bit field storage question: stackoverflow.com/questions/21164939/unexpected-behaviour-of-bit-field-operator-in-c

8)

#include<stdio.h>
struct st
{
    int x;
    static int y;
};
 
int main()
{
    printf("%d", sizeof(struct st));
    return 0;
}

->In C, struct and union types cannot have static members. In C++, struct types are allowed to have static members, but union cannot have static members in C++ also.

9: A structure cannot contain a member of its own type because if this is allowed then it becomes impossible for compiler to know
sizeof such struct. Although a pointer of same type can be a member because pointers of all types are of same size and compiler cancalculate size of struct

10) Size of array can’t be constant

#include<stdio.h>
void main(){
    int const SIZE=5;
    int expr;
    double value[SIZE]={2.0,4.0,6.0,8.0,10.0};
    expr=1|2|3|4;
    printf("%f",value[expr]);
}

Give compiler error

11) strlen(“nishant”) = 7
sizeof(“nishant”) = 8
strlen(“nishant “) = 8
sizeof(“nishant “) = 10
strlen(“nishantkumar”) = 7
sizeof(“nishant kumar”) = 16

12) Hexadecimal : 0X, \x,
Octate : 0 Followed by number less then 7 ex: 01001 = 513 , ‘\111′ = 73 here \ representing octate

#include<stdio.h>
#define WWW -1
enum {cat,rat};
void main(){
    int Dhoni[]={2,'b',0x3,01001,'\x1d','\111',rat,WWW};
    int i;
    for(i=0;i<8;i++)
         printf(" %d",Dhoni[i]);
}
1
2 98 3 513 29 73 1 -1

In c any character is starting with character ‘\’ represents octal number in character. As we know octal digits are: 0, 1, 2, 3, 4, 5, 6, and 7. So 8 is not an octal digit. Hence ‘\08’ is invalid octal character constant.

13) 
1
#include<stdio.h>
void main(){
    int a;
    a= (3,4,5);
    printf("%d",a);
}

[/sourcecode ]
a= 5

1
 #include<stdio.h>
void main(){
    int a;
    a= 3,4,5;
    printf("%d",a);
}

a=3

14) What will be output if you will compile and execute the following c code?

void main(){
char c=125;
    c=c+10;
    printf("%d",c);
}

15:

 #include "stdio.h"
#include "string.h"
void main(){
   char *str=NULL;
   strcpy(str,"cquestionbank");
   printf("%s",str);
}

Note:

void strcpy(char *target, char *source){
   while(*source)
   {
      *target = *source;
      source++;
      target++;
   }
   *target = '\0';}
  ***Note: In strcpy function target should not be character pointer.

16)

void main(){
int i=10;
static int x=i;
if(x==i)
printf("Equal");
else if(x>i)
printf("Greater than");
else
printf("Less than");
}

Output: Compile time error
Explanation:
static variables are load time entity while auto variables are run time entity. We can not initialize any load time variable by the run time variable.
In this example i is run time variable while x is load time variable.

17)

#include<stdio.h>
int main(){
    printf("%c",*"abcde");
return 0;
}

18) Label of GOTO: scope is function block it is not visible outside of function.

19) Scope of variable

19)

#include<stdio.h>
int main(){
    int i=0;
    {
         auto int a=20;
         XYZ:;
         printf("%d",a);
         a++;
         i++;
    }
    if (i<3)
         goto xyz;
    return 0;
}

Explanation: Variable a which declared inside inner block has scope only within that block. Ones program control comes out of that block variable will be dead. If with the help of goto statement we will go to inside that inner block in the printf statement complier will not known about variable a because it has been destroyed already. Hence complier will show an error message: undefined symbol a. But if you will write goto statement label before the declaration of variable then there is not any problem because variable a will again declared and initialize.

20) We cannot initialize extern variable locally i.e. within any block either at the time of declaration or separately. We can only initialize extern variable globally. For example:

(a)

#include <stdio.h>
int main(){
extern int i=10; //Try to initialize extern variable
                 //locally.
    printf("%d",i);
    return 0;
}

Output: Compilation error: Cannot initialize extern variable.

(b)

#include <stdio.h>
int main(){
    extern int i; //Declaration of extern variable i.
    int i=10;     //Try to locally initialization of
                  //extern variable i.
    printf("%d",i);
    return 0;
}

Output: Compilation error: Multiple declaration of variable i.

#include <stdio.h>
extern int i;
int main(){
    i=25;       //Assignment statement
    printf("%d",i);
    return 0;
}
int i=10;   //Initialization statement

Output: 25

21) Typedef is a storage class : http://itee.uq.edu.au/~comp2303/Leslie_C_ref/C/SYNTAX/typedef.html

Javascript: How to convert string into XML Object in Javascript ?

In JavaScript we have string which format is equivalent to XML but In actual data is not in XML so we can’t enjoy predefine function and can’t manipulate string as XML so shoot out this issue we have to first convert string into XML object so that It allow to use manipulation of content inside node easily.

Cases Where we need to consider this conversion ( String into XML Object)

-> From server In response we get XML like formatted data but in actual data type of data  is string so we can’t apply manipulation on string by using XML manipulation function.

Let’s have example: First we have declare a var xmlString of type string if we want to see the type of xmlString we can use console.log( typeof xmlString); it will return string.


var xmlString = "<userInfo>
                    <name>Nishant</name>
                    <email>mindfiresolutions@gmail.com</email>
                </userInfo>";

So We will use XML Parser to parse string into XML object to enjoy feature of XML. As all modern browser have built
in XML Parser.

Below ParseXML function will take string val and return XML object


function ParseXML(val)
{
	if (window.DOMParser)
	  {
		parser=new DOMParser();
		xmlDoc=parser.parseFromString(val,"text/xml");
	  }
	else // Internet Explorer
	  {
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.loadXML(val);
	  }
return xmlDoc ;
}

After converting string into XML object we can enjoy XML manipulation

var xmlDataObj = ParseXML(xmlString);
console.log(xmlDataObj.getElementsByTagName('name')[0].childNodes[0].nodeValue)

Output will be Nishant

How to calculate the Last Day of the month using Filemaker

Often we need to calculate the last Day or Date of the month of a year. Particularly useful to display on the report headers where we need to display the data from first of the month to the last. The calculation of last day of the month is a problem when we take into consideration the month february and the leap year. We will have to write some case statements to arrive the calculation. But there is simpler approach here. A pretty small calculation that will give you the last date and hence the day can be calculated from it.Here it goes like this below one.
 
Date((SuppliedMonth+ 1), 1, SuppliedYear) -1
 
This gives you the last date of the month. Now to calculate the day just use the day function.
 
Day(Date((SuppliedMonth+ 1), 1, SuppliedYear) -1)

Optimized way for Counting total no of record in Portal in Filemaker.

As we know that we generally we use count () function for counting total no of record in related table, but it’s take time when we have large number of data. So there is a function called Get(FoundCount) which calculate total no of record in portal in fastest way.

Put a Field Called Found_Record_Count  in Related table on wich Portal is displayed and make it Unstored Calculation field with Get ( FoundCount ) function and mark calculation result as Number.

What are P, NP, NP-complete, and NP-hard ?

P (Polynomial time decidable problems) is a class of problems which can be decided in polynomial time i.e., there’s an algorithm for such a problem which tells whether the solution of a given instance of a problem is true/false in O(n^k) time for some constant k.
For example, deciding whether there exists a path of at most k links between two vertices u and v is in P.

NP (Non-deterministic polynomial time decidable problems) is a class of problems which have short accepting certificates and efficient verification algorithms i.e., given a certificate of a solution, it is easy to check if the problem is satisfied.
Accepting certificate is information which can be used to decide if the answer is true or false.
Formally, a problem is in NP if there exists a verification algorithm A such that for any input x for which the answer is “true”, there is a certificate c such that |c| is polynomial and A(x,c) = true. For any x for which the answer is true, there is no certificate c such that |c| is polynomial and A(x,c) is true.
For example, given a graph G and a number k, deciding whether there exists a clique (complete subgraph) of size k, is in NP.

P is a subset of NP i.e., any problem that is in P is also in NP. It is easy to see that for any problem that can be decided in polynomial time, there exists a verification algorithm that given any certificate just ignores the certificate and returns the result of the polynomial-time algorithm.

Whether NP is also a subset of P (i.e., P = NP) is an open question. No one knows yet.

NP-hard is a class of problems which are hardest of all problems in NP. These are the problems such that if we can solve them fast, then we can solve all problems in NP fast and P would equal NP. NP-hard problems may be of any type: decision problems, search problems, or optimization problems so they may not even be in NP.
For example, the clique problem discussed above is NP-hard.

NP-complete is a class of problems which are in NP and are NP-hard. NP-complete problems transform to each-other by polynomial-time many-one reductions so if a polynomial-time algorithm exists for any one of them, then polynomial algorithms exist for all of them. However, no polynomial algorithm for any NP-complete problem has yet been found.
For example, the clique problem discussed above is NP-complete.

How to add JavaScript file dynamically from JavaScript on client Side

We can add java script file on client side under head tag by JavaScript dynamically. Below is working code

            var filename = 'http://code.jquery.com/jquery-2.0.0.js';
            var fileref = document.createElement('script');
                fileref.setAttribute("type", "text/javascript");
                fileref.setAttribute("src", filename);
                fileref.setAttribute("ID", "jsScript");
                document.getElementsByTagName("head")[0].appendChild(fileref);

Let’s Understand the above code We have to put script under head tag in below format

<script src="http://code.jquery.com/jquery-2.0.0.js" type="text/javascript"></script>


So for doing this have to define filename = which can be file name and absolute and relative JS file path name.Now we have to create script element which can be done using document.createElement(‘script’) method. And for adding attribute can be used setAttribute method.


Note: Here I have also set ID property fileref.setAttribute(“ID”, “jsScript”); which is optional. It will be helpfull when you want to check whether already page contains script with this ID or not.

Below code is used for check whether already have included Js file if yes then don’t include So It can be used to Check to see if script is present before adding one.

        var jsSelector = document.getElementById("jsScript");

        if (!jsSelector) {

            var filename = 'http://code.jquery.com/jquery-2.0.0.js';
            var fileref = document.createElement('script');
            fileref.setAttribute("type", "text/javascript");
            fileref.setAttribute("src", filename);
            fileref.setAttribute("ID", "jsScript");
            document.getElementsByTagName("head")[0].appendChild(fileref);
        }
 

Page Keyword: How to check js file already loaded or not, add js file dynamically, add java script file by java script