Thursday, May 17, 2012

Obray Curry: A dish using Obect and Array- II

Today is another interesting find:

console.clear();

var a ={};
a.p1 = "kiazen";
a["p2"] = "krook";
a[0] = 10;
a[1] = 20;
a[2] = 30;
a[3] = 40;
console.log(a)
console.log(JSON.stringify(a));


console.clear();

var a =[];
a.p1 = "kiazen";
a["p2"] = "krook";
a[0] = 10;
a[1] = 20;
a[2] = 30;
a[3] = 40;
console.log(a)
console.log(JSON.stringify(a));

The catch is
var a= []; 
 //=> this implies 'a' as associative array and not oject
or
var a= {};
 //=> this implies 'a' as object.

So my interpretation leads that serialization of javascript object/array depends on the first initialization fo the object.

Obray Curry: A dish using Obect and Array


Most of us know to write a simple javascript object in object literal notation (JSON) as:

var o = { "p1" : "value1" , "p2" : "value2" };

We also know that, we can add property dynamically as following ways:

  • o.p3 = "value3";
  • o["p4"] = "value4";

Most of us also know that we can write a simple javascript array object notation (JSON) as :

var arr = [10,20,30];

So far so good. Today I have a question to share.

How about making a curry of array and object.

Ain't that f**king lovely!!!!

var a = [10, 20, 30, 40 ];
a.p1 = "kiazen";
a["p2"] = "krook";


lets execute this code and see the object.
Here is the output::
















Questions:
1. What do we call this "a" as object or array ?
     I'll be referring to Obray (object array).

2. How do we represent this Obray.
     My assumed representation:  
{ [ 10, 20, 30 ], "p1": "kiazen", "p2": "krook" }
.

The site jsonlint failed to process my assumed representation

which is absolutely correct as per ECMA-262. scroll below to know exact reason.

Again on the server side, C# allows us to emulate similar structure implementation:

class MyArray[T]
    {
        List[T] _list = new List[T]();
        public string p1 { get; set; }
        public string p2 { get; set; }
        public T this[int i]
        {
            get { return _list[i]; }
            set {
                if (_list.Count < i)
                    _list[i] = value;
                else
                    _list.Add(value);
            }
        }
    }


MyArray[int] obj = new MyArray[int]();
  obj.p1 = "kiazen";
  obj.p2 = "krook";
  obj[0] = 10;
  obj[1] = 20;
  obj[2] = 30;


So far so good, but if we serialize it, what should be the JSON ?
   JsonConvert.SerializeObject(obj);
*used Newtonsoft.Json.dll for object to json conversion.
It gave me the following output:

{"p1":"kiazen","p2":"krook"}

What happened to the array while serialization?
Well thanks to ECMA-262.pdf which tells us about the parsing.
Parsing (serializing/deserializing) is on either object or array. And while serializing, this component will be an object and not an array and hence, the object serialization is happening.


image source: json.org

so there is no options for our Obray, Its either Object or Array !!!

I have raised the same discussion point in json.net development forum [http://json.codeplex.com/discussions/356118]. You are free to put your opinion here.

I think we need some improvisation in json as well ?


Monday, May 7, 2012

soma.js

Soma.js : Javascript MVC

My current assignment asks me to work on javascriptmvc based out of jquery.

Today while googling came across another javascript based mvc framework based of of mootools named soma.js.
The documentation of soma.js much nicer over javascript mvc.

javascriptmvc is suppose to get more success as such since it is commercially driven but I assume soma.js is much cleaner.

So far it is my assumption which I am going to investigate and discover more in it. Definitely I am going to let you all know about it.


Tuesday, March 13, 2012

Generic Utility for Console Logging



I very much belief that you might have used the following statement in your web development:
console.log(text);


Again the browser must have been firefox or Safari or chrome.
How about the tackling the same in IE ?

I have used a small hack to skip logging in IE and all those browser which does not support console directly.


Here is the code:

utilities = {
    logMessage: function (text) {
        if ((window['console'] !== undefined)) {
            console.log(text);
        }
     }
}

Usage:
utilities.logMessage (" .... message to log...");

Tuesday, March 6, 2012

Dynamic custom DOM Events - Mouse Event

As always every post has a reason.
Today I needed a solution where i need to invoke a event (rowclick) on a Ext GridPanel's object which is handled by a delegate function.
This invoking is suppose to be from an non DOM event. So the requirement is to MouseClick Event without clicking the mouse.

To clarify more.

Scenario:
I have a Ext.grid.GridPanel and is populated with some records.
Each 'rowclick' event is handled using a delegate function.


Problem Statement:
On an ajax request error event,
Need to add a row on the top and fire 'rowclick' on the same grid.

Solution:
Add a new row to the Grid.
Create a custom click event object.
Find the row HTML element.
Fire the custom click event object  on the row HTML elemnt.

Code:
1.var message = { Message: 'Communication error, server returned unexpected data', Description: message,    
                          Date: new Date() };
2.var rec = new this.store.recordType(message, ++this.counter);
3.this.store.insert(0, rec);


4.var evObj = document.createEvent('MouseEvents');
5.evObj.initEvent('click', true, true);
6. gridObj.getView().getRow(0).dispatchEvent(evObj);

Explanation:
Add a new row to the Grid.

1.var message = { Message: 'Communication error, server returned unexpected data', Description: message,    
                          Date: new Date() };
2.var rec = new this.store.recordType(message, ++this.counter);
3.this.store.insert(0, rec);

Create a custom click event object.

4.var evObj = document.createEvent('MouseEvents');
5.evObj.initEvent('click', true, true);



Find the row HTML element.
6.gridObj.getView().getRow(0).

Fire the custom click event object  on the row HTML elemnt.

6. gridObj.getView().getRow(0).dispatchEvent(evObj);

Thats iT!!!! Bingo.

Reference:  http://www.howtocreate.co.uk/tutorials/javascript/domevents

Thursday, December 8, 2011

Json is Strict

I have been using JSON as DTO (Data transfer Object) for quite some time.
Today while educating myself with jquery came across an interesting thing about it.

So far today I knew the following is valid, but i was wrong
{ id : '01', name: 'kris' } <= invalid

It should be

{ id : "01", name: "kris" } <= valid


Refer : http://json.org/ for more information

Extjs accepts the above invalid data but jquery doesn't (as far as i have educated myself in jquery).

Aint that interesting !!!

Thursday, October 13, 2011

Lazy Evaluation


var boolV = true || false || true || false || true;
 console.log(boolV); //output is true

Question is did all the operations (logical) got executed ?
Ans is NO.

If several logical operations one after the other, but the result becomes clear at some point before the end of entire operation, then the remaining operations are not performed.

Lets consider the above statement.

var boolV = true || false || true || false || true;

It is before the first local operation it is clear that boolV is  suppose to have value true irrespective of any logical or operation. hence the other logical operations are not executed. in the above statement.

To verify this, we will the following code.

var a =10;
console.log(a); //output 10
console.log(!!++a); //output true
console.log(a);        //output 11
var boolV = true || false || true || false || true || !!++a;
console.log(boolV);  //output true
console.log(a);         //output 11 (which imples the !!++a didn't got executed)
boolV =  !!++a || true || false || true || false || true ;
console.log(boolV); //output true
console.log(a);        //output 12 (which imples the !!++a  got executed)


Ain't that interesting !!!

Wednesday, October 12, 2011

Starting reading Object Oriented Javascript by Stoyan Stefanov again

Starting reading Object Oriented Javascript by Stoyan Stefanov again.

I used to read this book managing between my office work and completing house hold choir.
Interestingly this time, I am being asked to complete this book by tomorrow (thats a big task) and that too as an work which I'm liking it.

This book contains conceptual treasures of javascript and everytime I read, I am starting to like it more.

Small interesting codes for all.

var a=10;
var b =20;
var c = "20";

var d,e,f,g;

d= a+b;
e= a+c;
f= b+a;
g= c+a;

console.log(d);
console.log(e);
console.log(f);
console.log(g);

Can you guess the output???
d>>> 30
e>>>  1020
f>>> 30
g>>> 2010

the value of d and f remains same whereas e and f are different. since e and f becomes string variable  from the operation  e= a+c; and g= c+a;

<< number >> + << string >> will result in string concatenation
and result type will also be << string >>.


Thursday, June 23, 2011

HTML5 & Detection Techniques

New Logo of  HTML5
HTML5 is the new specification of HTML 5 with lots of new feature and it is still being drafted the latest specification can be found at http://dev.w3.org/html5/spec/Overview.html .

Some of the new features are
  • Numerous new tags like (article, aside, bdo, command, datalist, details, embed, footer, hgroup, keygen, mark, meter, nav, output, progress, rp, rt, ruby, section, source, summary, time, wbr). 
  • Custom tag for audio and video
  • Custom tags for images and its captions (figure, figcation)
  • Custom tag for Custom Graphics (canvas)
  • New controls for webforms like (dates, times, email, url, search, number, range, tel, color).
  • Geolocation Support.
  • Web Sockets: Socket programming for client browser.
  • New logo to identify  HTML5.
The are lots of more features in it, I am yet to go through all of them and the draft is still being updated.

Canvas element allows dynamic and scriptable rendering of 2D shapes and bitmap images. [Read More...]
SVG (scalable vector graphics is supported using canvas element). Various representation of reports are presented using graphs, pie charts, etc. canvas element with the help of SVG allows to create nice images and graphics. Javascript is required to program the SVG in canvas element.

How can I detect if the browser is supporting HTML5?
Here we have to depend on javascript. A javascript library named Modernizr available under Open Source for HTML5 and CSS3.
However, as per Mark Pilgrim('s book HTML5 Up and Running), we can employ the following simple techniques to quickly identify HTML5 compatible browser.

  1. Checking the presence of certain property on the global object(such as navigator or window object).
    • Example. checking the presence of Geolocation support.
    • function supports_geolocation() {
            return !!navigator.geolocation;
      }
  2. After creating an element dynamically, then testing the presence of a certain property to that element.
    • Example. checking the canvas support.
    • function supports_canvas() {
            return !!document.createElement('canvas').getContext;
      }
  3. After creating an element dynamically, then testing the presence of a certain method to that element. Then call the method if present  and check the value returned.
    • Example. checking the video support.

    • function supports_h264_baseline_video() {
            // checks the video support
            if (!!!document.createElement('video').canPlayType;) { return false; }
            var v = document.createElement("video"); //create element
            return v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');
      }
  4. After creating an element dynamically, set value to a property and then to test if it has retained the value.
    • Example: Create a element 'input' dynamically (which is of type 'text' as default). Then setting the property 'type' to other value and retesting the value of the property 'type' 
    • function supports_PropertyPersistance() {
         var i = document.createElement("input"); //default element is text
          i.setAttribute("type", "color");
          return i.type !== "text";
      }

Read More on detection technique...

Reference: http://en.wikipedia.org/wiki/HTML5
Specification - Working Draft: http://dev.w3.org/html5/spec/Overview.html
Specification - Released Working Draft: http://www.w3.org/TR/html5/

Monday, June 20, 2011

Rule of Thumb : Declaring variables

"var" is the keyword used for declaring a variable. It lets you define an number, string , datetime value or an object or function.


Example(s):

var a1;
var a2 = 10;
var a3 = 1.23;
var a4 = "hello world";
var a5 = true;
var a6 = {prop1:'some values', prop2: 'some other values', prop3 : true} ;


var a7 = new Object();
var fn1 = function() { return "hello world"};


what happens if we use in the following way
 ax=10;

Well well, the above line adds a variable name "ax" in the global scope. At a glance it can pretend to be an trivial mistake, but that is not the case, rather it is of very high importance, since such statement can make the global scope dirty and making the code fault prone and fragile.

Lets take another example for more clarity:


function sayHello(username){
  strn = "Hello " + username;
  return strn;
};


console.log( sayHello( 'kris' ) );
console.log( strn ); //=> "hello kris"

*console is a class available in almost all browsers but not in all browser for development/debugging purpose.

The above javascript function "sayHello" adds a variable "strn" to the global scope.

The following change of declaring the variable with "var" will make sure that the variable "strn" is applicable to local scope only.

Examples: 
function sayHello(username){
  var strn = "Hello " + username;
  return strn;
};


console.log( sayHello( 'kris' ) );
console.log( strn ); //=> undefined
Hence the scope of  local variable is managed correctly.

So we conclude this post with the memoirs of golden rule of variable declaration in javascript.

Tuesday, June 14, 2011

Beginning Javascript

The blog of mine is making a focus shift from blogging to javascript preaching.

JavaScript was earlier called "LiveScript".
you will get a good information on javascript history here wikipedia:javascript

My inception of javascript was like simple validations for web pages in 2005. Beginning 2007, I understood that javascript has some more potential. Errie, whats the potential. Well well, you can use javascript as a full blown applications. During june-2008 I wrote my first javascript class. Yessss my first javascript class.

well here it goes.

Code:



var A= function(){
  this.sayHello = function(){
    alert('hello world');
  };
};
var o = new A();
o.sayHello();


Yes it is as simple as written here.

More is on way to you.

Wednesday, April 6, 2011

ExtJS new version

Exciting new Sencha (EXTJS version4) has arrived.

Sencha is formerly known as EXTJS(EXTended JavaScript).

The interesting question is "So what exciting about it????"

The following are to name a few.

Using a swf runtime super cool "Drawing & Charts" exploiting the advantaqge to positioning the SWF component inside DOM using javascript with possibility to pass parameters. Its capability is not restricted rather increased with the ability of scalable vector drawing.

The Ext.Data package has been overhauled with interesting additions.

Its not last but the UI which matters the most is now supported by CSS3 themes, and the theme has been overhauled to give more richness with reduced size on browser.

Last but not the lease the "Performance" aspect has been improved drastically.
The reduced size load at DOM(i.e. DOM reduction) with an implied and tuned effect on speed gains. And the most interesting is the Infinite Scroll on Grids with data request on demand to scroll.

Click [here] to check out the beta4 version of Sencha .

Tuesday, December 29, 2009

Double Trouble with Keyless Entry for car

Morning was as usual good when I woke up.
Today was the first business day of the week since yesterday was holiday declared for muhharam. So you can make out that its an important day at office and that too after a 4 day long holidays.

I pressed the remote of my car. "No sound" !!
Again I pressed the unlock button. It didn't worked!!!
I tried again couple of times. All effort gone to waste.

I asked mom to get me the 2nd set of remote keys.
Tried with the 2nd set as well. But alas there was no response.

The wrist watch was pointing it to 8:46am. I was getting late.
So thought to get a forced entry by using the metal key.

Opened the lock and door.
Christ!!!
I realized what mistake I did. It started to beep like anything. It was all chaotic. Entire neighborhood turned to check out what happened.

Holy Christ!!!
The embarrassing moments. The sound was just not stoppable. It paused for 2 seconds started again. I guess it continued for 5 mins and then stopped.

The embarrassing troubled moment was over I thought. I was terribly mistaken which in a short while i came to know.

I used the key for ignition. No response!!!!!
Again i tried. No response!!!!!
Repeated couple of times again before I realized that the keyless entry mechanism had disconnected the ignition channel.

And with every ignition try the vehicle started making beeping sound like madness.

I realized the vehicle cannot be started without third party/service engineer's help.

I kept the car in garage and closed everything. Without delay headed with laptop, office document/papers and lunch box towards nearest taxi stand(cab terminal). It was already 9:10am by that time.

Thats the beginning of the day. lets see whats there kept more during the day.

Called up Maruti and the provider of the keyless entry system.
The service engineer came around 11:30 am.Thanks to Dad who was there at home to guide the service engineer.

Seems, he has replaced the main keyless entry machine.

After reaching home I'll come to know whats the status.

Advice for all:
If you car buzzer begins to beep without any notice or/and creates issues with the keyless remote, immediately take the matter to the provider.

The mentioned were the symptoms for keyless entry machine problems.

Luckily i was not out for a long drive during that period. Else god knows what more problem would have been there.

Wednesday, November 4, 2009

Thursday, June 18, 2009

Using EXT JS

In recent time Client Side scripting has become very popular. Particularly if you observe maps.google.com or gmail, etc... every website/application is using client side scripting extensively. So did i encountered in my recent project. Before this project i have used core javascript , classes, objects, JSON, etc. This project required those aspects as basics, and a rich client side UI framework. We discovered ExtJs serving the purpose providing a stable, scalable,extendible framework with numerous widgets as the building controls.

One of the control is Window. How does it sound to simulate a window inside you webpage. To me it was something WOW!!! The following is the example for the same.

Chapter 01
A simple window with predefined text

Code Sample:

var initializeFn = function(){
var windowObj = new Ext.Window({title:'First ExtJs Window',html:'Sample predefined text',height:300,width:400});
windowObj.show();

};
Ext.onReady ( initializeFn );




This code uses ExtJs Base framework (http://www.extjs.com/).
You can refer the
examples at http://extjs.com/deploy/dev/examples/samples.html.


Sunday, December 21, 2008

70 reasons to stay in Kolkata


      Hello all,

      Created this blog nearly an year back. Today i am starting my first post with a copy paste of an email received couple of days ago. this mail was shot to me by a freind/dada of mine. We adoringly call him patla~pata (means thin paper). I have moved to kolkata, couple of months ago and he left kolkata just a month back. I hope people staying away from kolkata will have something to say onto the following 70 reasons.

    1. Phulkopir Shingara: samosas don't stand a chance against these.
    2. Phuchka: gol-gappas aren't a patch on phuchkas. Try Bengal Lamp/Dakshinapan.
    3. Karaishutir Kochuri: a seasonal favourite, have it with "alur dam".
    4. Alurdom: the world's best. Try the offering at Vivekananda Park .
    5. Jhalmuri: a unique concoction, with nothing to equal it.
    6. Telebhaaja: these and jhalmuri are like 'made for each other'.
    7. Chanachur: many have tried unsuccessfully to steal the formula, MNCs included!
    8. Alukabli: where will you get something like this?
    9. Ghugni: again, chana is not the same at all.
    10. Radhaballavi: try it with alurdom or cholar daal.
    11. Chanmp: even Pakistani cricketers have sampled these, in Chitpur.
    12. Rezala: out of this world, just out of this world!
    13. Paradiser Sharbat: there is one which is green, and another, pink. No college student from Presidency or the University has failed to sample these!
    14. Lere Biscut: needed to make the batter for chop-katlet.
    15. Chicken Kabiraji: an unbelievable variation on the chicken cutlet.
    16. Moton Afghani: an equalsly innovative presentation of the mutton cutlet.
    17. Dimer Kalia: again, where do you get something like this?
    18. Kasha mangsho: it has become an institution now.
    19. Roll: the ubiquitous mutton, chicken or egg roll. Unquestionably superior to any variants (Frankies 4 that matter) in any other city of the world. And also....
    20. Coffee houser coffee ar adda : try the float with ice-cream.
    21. Bharer chaa: on the Maidan, from shining brass vessels on a rainy day. And not to be missed in all this.
    22. Pan: unmatched, even in Benaras or Lucknow . Honestly!


    The sweeter side


    1. Roshomalai: a creamy, mouth-watering delight!
    2. Jilipi: smaller than the jalebis and tastes quite different.
    3. Lal Doi: is an experience by itself!
    4. Sada Doi: have it @ the shop, "Mithai"
    5. Kamala bhog: a pale yellow orb, delicately sweetened.
    6. Darjees of Metiabruz: are a cut above the rest. Even if they cut corners at times!: a winter speciality available in no other city.
    7. Rosogolla: simply needs no introduction.
    8. Natun gurer Rosogolla: the latest innovation. There are many, many more traditional favourites.and also...
    9. Shitabhog: pure white, sweetened to just the right extent.
    10. Mihi Dana: golden yellow, saffron scented.
    11. Maalpoa: rich brown pancakes, dripping in sugar syrup.
    12. Ranga alur pithey: another traditional favourite in winter.


    Up fashion street


    1. Fashions keep changing. But the dhuti-panjabi and tangail look never becomes out-dated.
    2. Dhuti with extra broad borders: the finest and most elegant available here.
    3. Dhutis in red or black: The latest sensation in Calcutta.
    4. Giley kora Panjabi: those with the improbably crinkled sleeves.
    5. Tangail Sari: the best in these all-time favourites can be found here.


    and the other marks of distinction are...


    1. Bidyasagari choti: you still get them here.
    2. Kabuli Chappal: another old favourite.
    3. Garader Sari: ideal with pujo bari , shankher awaaj. Sights and soundsOne wakes up in the morning and hears their voices drifting through the air. So typically do they say their bit...that it is difficult to forget....and even more so ...to imitate...
    4. Shil katowala: they chip the stone slabs which grind masalas.
    5. Chhuri Kanchhi Shaanwala: sharpens knives, scissors and anything with an edge.
    6. Lep Shelaiwala: they make those cotton quilts which warm you up in winter.


    And early in the morning, before Durga Pujo, who can forget the strains of


    1. Mahalayar mahishashuromardini:Other things, quaint and very special.
    2. Chinese Food in China Town : an early morning breakfast here is an experience.
    3. Metro Rail: spick and span, and the trains are dot on time.
    4. Maidan: the ideal p lace to be on a sleepy, winter morning.
    5. College Streeter Boipara: bookworms buzz around this place morning, noon and night.
    6. All Night Music Conference: you won't find a minute to yawn.
    7. Circular Rail: see the river all along as you travel on the train.
    8. Ganga te nouko bihar: either in a country boat or a steamer or on hover craft!
    9. Dolphins in the Ganga : if it's your lucky day, you might catch a glimpse of a frolicking shoal.
    10. Morning tram to the Maidan: see how green and fresh the city looks.
    11. East Calcutta Wetlands: our very own eco-system regulator - just on the outskirts.


    Travel in style


    1. Rickshaw: still the preferred form of transportation for some, especially children and the elderly.
    2. School van: it's to be seen to be believed.
    3. Tram: if you have time on hand, you can see the city glide by.


    Calcutta 's passion


    1. Roker adda: Calcuttans are an adda baaj lot.Mohan Bagan & East Bengal : prices of ilish or chingri go up, depending on who wins the day.
    2. Jatra: who says it is all melodrama?
    3. Durga pujo: the pomp and pageantry, reserved each year for the 'mother of all festivals'.
    4. Little magazine: you still find devotees of this publishing wonder.
    5. Book Fair: when the fair is on, you are there - whether you love books or not.
    6. Cricket match at the Eden : cricketers and cricket lovers the world over treasure the experience.


    City's own


    1. Hydrant: there's a move by the CMC to revive the practice of splashing the streets with Ganga water from the hydrants.
    2. Italian Saloon: road side barber joints, where you sit on a piece of brick (it).
    3. Chinese dry cleaners: do a very clean job, indeed.
    4. Darjees of Metiabruz: are a cut above the rest. Even if they cut corners at times!


    Tell me is there any place better than Kolkata !!! post you opinion...