October 06, 2018

Quickly creating a progressive web app PWA

Progressive web apps are web apps that can avail some native app like features. They can have their own window. They can show notifications and can optionally work offline. To write a minimal PWA, you need a page to display (index.html) and two files for service worker (sw.js) and manifest (manifest.json).

 Note that service worker requires a secure connection so the site has to be served over HTTPS protocol.

First, in the web page add a link tag for manifest.json and in body add a script tag for registering service worker as shown below.

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>PWA</title>
        <link rel="manifest" href="manifest.json">
    </head>
    <body>
        <h1>My PWA</h1>
        <script>
            if ('serviceWorker' in navigator) {
                navigator.serviceWorker.register('/sw.js');
            }
        </script>
    </body>
</html>

Now we need to create a manifest file. This is a json file that stores properties like app name, starting point, display type, icon etc. Many of these are required to identify your site as PWA.

manifest.json

{
  "name": "My Progressive Web App",
  "short_name": "My PWA",
  "lang": "en-US",
  "start_url": "/index.html",
  "display": "standalone",
  "icons": [
    {
      "src": "http://pngimg.com/uploads/smartphone/smartphone_PNG8511.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ]
}

Finally, we need to add a service worker. A service worker is responsible for managing app caches in the site. In our case, we cache list of static files in install event and then in fetch event we check cache before fetching file.

sw.js

/* Cache static files for offline availability */  
self.addEventListener('install', event => {
  event.waitUntil(caches.open('static')
    .then(cache => cache.addAll(['/', 'manifest.json', 'sw.js']))  
  )
});

/* Fetch file if not in cache */
self.addEventListener('fetch', event => {
  event.respondWith(caches.match(event.request) 
    .then(cached => cached || fetch(event.request))
  );
}); 

Serve above three files from a web server (can use localhost without HTTPS) and point your browser to the site. If your browser supports PWA then it may allow you to install a shortcut on the launcher. Note that browsers have criteria for allowing this. The shortcut will open a standalone window. Once loaded, it should display the page offline also.

September 29, 2018

Javascript Promises with chaining in ES6

 Javascript in version ES6 has introduced Promises. They allow asynchronous tasks to be coordinated. A promise takes two arguments resolve and reject and the asynchronous code calls one of them depending on result. An example would be to fetch a file from network.

The promise can register functions to be called after resolve is called using 'then' method. Similarly, functions to be called after reject are registered using 'catch' method.

'then' method in turn returns a new promise which can be chained.

Following is an annotated example which demonstrates these concepts.


/* Create a new promise with async action inside
    It takes two functions as arguments: resolve, reject */
const myPromise = new Promise( (resolve, reject)=>{
    /* This function represents async work */
    function doWork () {
        // If current time is even then resolve else reject.
        const fulfilled = (((new Date()).getTime()) % 2 == 0);
        (fulfilled)? resolve(fulfilled): reject(fulfilled);
    }
    // Schedule the work after some time.
    setTimeout(doWork, 1000);
    // Return before doWork finishes.
    return;
});

// If resolve is called in doWork function then call following function.
var myPromise2 = myPromise.then( (fulfilled) => {
    console.log("Resolved with " + fulfilled);
    return fulfilled;
});

// If reject is called in doWork function then call following function.
myPromise.catch( (fulfilled)=>{
    console.log("Rejected with " + fulfilled);
    return fulfilled;
});

// Chain this function after "Resolved With " is called.
myPromise2.then( (fulfilled)=>
    console.log('Chained Promise with ' +  fulfilled));



September 23, 2018

Encapsulation with closures in javascript

Javascript supports many programming styles like Object oriented and functional. Functional style in Javascript allows new ways of programming for programmers already having knowledge of languages like C++ or java.

 Javascript supports first class functions. Javascript originally has lexical scoping of variables. This means that you can declare and define functions not only at global level but also inside other functions. With lexical scoping, a function has access to all variables in the ascendant functions. Inner functions, when returned from outer function keep reference to the variables of outer function even after outer function exits. These variables can only be accessed by the inner functions.

This restricted visibility of outer function variables allow encapsulation of data. Following is an example of such a case.

/* Function hiding variable h.
    It returns two function closures. */
    function fn () {
    var h = 0;
    /* Return object with two methods as properties.
        These methods have access to hidden variable h. */
    return {

        // Overwrite variable h
        set : function(v) { h = v; },
        // Read variable h and print.
        log : function() { console.log(h); },
    }
    }  

// Test above function
var ret = fn();
var ret2 = fn();
ret2.set(10);
ret.log();
ret2.log();

/* Output is  
    0
    10
*/

fn is outer function. it returns an object with two functions set and log as properties. The inner functions are function closures that have reference to outer function variables.

The function fn is invoked twice with return values assigned to ret and ret2 variables. Then set function is invoked on ret2 to overwrite the hidden variable of ret2. Finally, we log the values to see that ret and ret2 has separate copies of variable h.


September 12, 2018

Overview of MV* design patterns MVC MVP MVVM

Over the years many design patterns have emerged to enforce separation of concerns in code bases. The MV* patterns have found use in server side technology such as Java EE and Dot Net as well as on browser in some modern libraries. Here we attempt an overview of these patterns.

The MV* patterns have three separations: Model, View and the Glue. The interaction between separated model and the view is facilitated by the Glue, which goes by name of Controller, Presenter or ViewModel. Hence the pattern Model-View-Controller (MVC), Model-View-Presenter (MVP) or Model-View-ViewModel (MVVM).

Model is the encapsulation of business data and logic. This contains the internal representation of the data relevant to the software. It contains business logic, which is the processing of data in order to achieve desired function of the software. It is not concerned with how that information is laid out on the user interface or formatting thereof.

View is the encapsulation of visual aspects of data being presented to user on user interface. This means layout, formatting, effects rendered to the user. It is not concerned about how the data is stored and processed internally for achieving desired functionality of software.

MVC has Controller as the glue. The controller is responsible for receiving user input. After receiving user input it interacts with model to update it. After that the model notifies the view that now it is ready to render. View renders the data and sends it to the user.

The separation of model from view allows testing of model independently from the view. However, the controller is tied to the view and can contain some processing which is not easy to test.

MVP has Presenter as the glue. The presenter is obtains input from the view and then interacts with model to update it. The results are fetched from model and presenter then updates the view.

The View in MVP does not contain any processing for display. Processing is shifted to the presenter. This allows testing of presenter and model easily.


MVVM has ViewModel as the glue. In practice, MVVM relies on a "data binding". Data binding automatic synchronization of data in view to data in viewmodel. ViewModel is responsible for updating the model.

The binding in MVVM reduces boilerplate code required. Without platform support for binding, Implementing MVVM requires much more effort.

MVC, MVP and MVVM has their own applications. All are used in various software frameworks which are popular today.

January 22, 2010

Ways of accessing gmail on mobile and desktop

Gmail is one of the most flexible email services in the cloud when it comes to options to access it. There are many ways to login to gmail from various systems. Here we enlist options provided by gmail when it comes to reading or sending emails.

  • Standard Interface:
    The default interface at http://mail.google.com/mail is an AJAX interface which has access to all the features of gmail.
  • HTML Interface:
    accessible at http://mail.google.com/mail/h/ is lighter version gmail interface which is useful on low-bandwidth connections and on browsers not supported by standard interface. It is vary fast to load and layout is suitable for desktop interface.
  • Mobile interface:
    available at http://mail.google.com/mail/x/ is another light version of gmail interface. It is optimized for mobile access.
  • Desktop IMAP/POP clients:
    You can also use mail clients like thunderbird or outlook to access email using POP/IMAP protocol supported by these clients and send mail using SMTP. Many mobiles also have applications for POP/IMAP.
  • Web interfaces of IMAP clients:
    Third party websites like http://mail2web.com allow access to gmail using POP/IMAP settings. These sites may also have mobile interface to allow access from mobiles.

Each option described above caters to various devices and useful in some conditions. However, only the standard interface allows access to gmail's advanced features and integration. Also the contacts are only accessible from gmail's own web interfaces (first three). On the other hand POP/IMAP access supports multiple accounts at same time which is not available in gmail's web interfaces.

November 04, 2006

Secure email address against spam using email forw...

Email spam is a concern for most these days. It might not take long before you receive spam in your fresh active email account.



A spam email is an email received which you did not ask for. Most of the time, it would be from unknown source. It may even have a fake sender name to make you open it. Spam is sent for various reasons like cheap publicity, frauds and even works as pollinators for computer viruses.

Listed are some precautions for protection against spam.

  • Do not give your email ID to anyone!

    Then ... how to use it? The key is to classify contacts and then use appropriate forwarding mechanisms. A forwarding mechanism allows any email sent to some other address to be automatically received at your email address.

  • For temporary addresses, check spamgourmet.com It offers temporary email forwarding addresses of form 'tempname.youraccount at spamgourmet.com' where tempname is any arbitrary word and youraccount is your spamgourmet account name. This address would expire after some number of emails and that would automatically stop too many emails coming from that sender. For example, this can be used for site registrations where you do not expect more than a couple of emails for registration.

  • Social networking sites allow hiding email address and access control. This way only friends can write to you without giving away actual address.

  • Use Email service providers that allow email forwarding, e.g, gmail. Aggregate mails from these accounts into another account, which is not given even to trusted parties. Thus, if one of your addresses are compromised, it would not effect others.

  • Extended email address are provided by some email providers. If your address is a@b.c, a+anything@b.c also delivers mail to a@b.c, but with added advantage that a+anything@b.c can be filtered out if it is subjected to spam.

Why not share email address with friends? Because they might unknowingly pass your email address to spammers. It works like this: user1 forwards a message to user2 and user3. He uses To: and CC: field to address them. This way, now user2 and user3 have each other's addresses, but they never intended to do so. Now this message is forwarded many time and ends up either in a spammer's hand with all the email addresses or is posted on some site ready for spammer to crawl.



The moral of this story is, when you forward messages to many email addresses, always use BCC field, not TO or CC. use your address in TO if the software forces to write some address there. Unless your friends follow this, your email address is in risk of getting into hands of anyone.



The indirect method of contacts such as social networks has added benefit, that your changes in email address are transparent to your friends. Thus, if your email address is compromised by mistake of someone you share address with or you want to check out new cool email service, you can change the email address without involving people who do not share it directly with you, e.g. users of online groups and social networking sites.



These tips can take little time to practice, but provides good defense against spam.



October 13, 2006

Using Google talk (Jabber) on linux behind proxy and firewall

The official Google talk client works beautifully behind firewall and proxy , but Linux users face difficulties trying to connect behind a proxy and firewall. Google Talk client is not available for Linux. A page describing how to connect using other Instant Messengers (IM) is provided on the Google Talk page, but the details shown there are for standard setup.

Google talk uses an open standard named Jabber for communication between the user-client and the server. This protocol Allows connecting in 3 modes: Direct connection, tunneling over HTTP and HTTP polling.

The HTTP Tunneling mode can be used when the proxy allows HTTP tunneling over Jabber ports 5222 and 5223. Most of the proxies block this.

Recently is has become possible to connect to GTalk Jabber server using port 443. for more details, refer this page Thus, for people behind firewall and proxy, the parameters of connections are as follows.:

Try a good jabber client, e.g. Psi

Jabber ID: your.user.id@gmail.com
Password: gmail password

Proxy server name, port and password from your network administrator

Also select following options
Use SSL Encryption
Ignore SSL Warnings
Allow Plaintext Login
Manually specify server host/port; Host: talk.google.com; Port: 443

Save the setup and try luck!

Also, have a look at the page describing how to use Google Talk with other IM services like AIM, MSN, Yahoo, ICQ etc.

April 02, 2006

Parser generators : ANTLR, SableCC, JavaCC, bison at a glance.

One looks towards parser generators (or compiler compilers) when there is a need to translate something in one language to other language. Basically you need to read a sequence of characters, make a data structure which represents the same. For many interesting problems, you want to build a tree. Using this, one can generate a new sequence of character, which is translation of input or just do things on that data structure.

A grammar (context free grammar, technically speaking) says what type of children a node can have. The leaves of tree cannot have any nodes under them and they directly correspond to the characters in the input. Looking at the input, we try to construct a tree which complies with the rules declared by grammar. If only one such tree can be made for any valid input, then the grammar is called unambiguous.

To construct the tree, we have many choices for selecting nodes, which can lead to the leaves to correspond to the input sequence seen so far. If we try to construct it from leaves, it is called bottom up approach. This approach usually uses a method of construction called LR parsing. If we attempt to build the tree top-down, the method usually used is called LL parsing.

Now let us discuss about the free tools that we have at our hand. Given a grammar and instructions on what to do with various nodes, these tools generate a parser.

ANTLR is derived from good old C/C++ PCCTS tool. Antlr has lots of features and can generate the parser in Java or C/C++. It uses top down approach to parsing.

JavaCC is a tool used in many applications, which is much like antlr, with few features different here and there. However, it just generates Java code.

The top down parser generators mentioned also support predicates, using which you can try to 'peep' in upcoming input. This is against the rules of game of context free parsing, but convenient in practice.

SableCC is a bottom up parser, which takes an unconventional and interesting approach of using object oriented methodology for constructing parsers. This results in easy to maintain code for generated parser. However, there are some performance issues at this point of time. It generates output in both C++ and Java

GNU Bison is classical bottom up parser. It generates C language output. It has been the standard tool on many unix operating system distributions. Now, it has also acquired the capability of parsing grammars with GLR method. It's implementation of it is not the best around, but we may have a look at lesser used parsing methods some other time.

There is a plethora of such tools. refer to Wikipedia - compiler compilers for details.

March 30, 2006

Parsing C++ Source Code: An overview of available tools

C++ is a popular programming language. On the other hand, compared to Java, there are few good programming tools available for C++. My favorite example is refactoring. Why should it be like that?

It happens to be the case that C++ was not designed with these issues in mind and also, it carries some legacy from it's ancestor, C. Technically speaking, C++ cannot be accurately specified using a context free grammar. A context free grammar is a grammar in which you can look at only a part of the whole document, and can give a name to that part without looking at other parts. An unambiguous grammar is one in which you can give exactly one name to that part.

Due to this, much hand-tinkering is required to write a C++ parser. However, many parsers take approach of accepting some source code which are not written in C++ and sort it out later in a second try called semantic pass. C++ has many dialects due to it's evolution and various compiler providers. These dialects differ from each other significantly.

If one can spend some money, there is a respected product which can parse C++ very accurately and also help you building tools on it. It can be found at: http://www.edg.com/

For free options, there are basically three approaches. First is to start from scratch and write a grammar (or use someone elses). There is a C++ grammar written by Edward D. Willink for his FOG . The thesis also contains good account of issues in the C++ grammar. The popular antlr parser generator also claims a C++ grammar which is updated from old PCCTS based grammar.

The second option is to use a parser tool that generates some type of intermediate representation which is easy to process programmatically. The noteworthy here is elsa. It is a C++ parser built using a special parser generator called elkhound. It can be found at Elkhound and Elsa site.

The last approach is to let compiler do the job! Prominent example is the modified C++ frontend for LLVM project, which translates the C++ code to bytecode and then provides infrastructure to write processing of this bytecode.

Apart from these, there are parsers coded for IDEs like Eclipse KDevelop, Anjuta etc. These are usually heuristics-driven, meaning that they would make some educated guesses when required to make analysis efficient.

One often forgotten pragmatic difficulty is the pre-processing of source. The first two approaches most of the time takes for granted preprocessed code.

These issues make parsing C++ code difficult and hinder the development of tools for C++ source code.