Sunday, October 26, 2014

Design Decisions I Question

Certain things occur every day while browsing the internet, that are very annoying and stupid at the same time. I just wonder why does it have to be like the way it is.

Here is the list:


  • Date of Birth Input Control on registration forms
Why does it have to start with the "Current Date". Many websites just pick the system date and default to it. Pretty Insane.

Some visionaries have empty values or place-holders selected for the date. Here is a Facebook Registration Page:


Now Month and Day are clear, but does Facebook seriously think that someone will have a Year of Birth as 2014? 

Not a big deal, the user just ends up scrolling a bit more, and number of new user registration << existing users, but still, for a website which looks at such tiny things, this should matter.

  • OTP : One Time Passwords
These are those system generated passwords that provide a second level of authentication required before performing sensitive operations, like making a online banking transaction.

My question is, why does it have to be a Obscured Text Input ( input type=password) .

 


Those password type input fields are meant to enter passwords, something, which a over-the-shoulder eves-dropper cannot read. An OTP is a One Time Password, even if someone reads it, they wont be able to re-use it. It just makes the lives of people entering those digits, slightly harder.

  • Signing-In into websites
There would be certain portals which would keep pestering you to sign-in. I am pretty sure the moment a user would see a Lightbox or a Popup blocking content, asking the user to sign-in, the chances that the user would actually sign-in would reduce to 1/4 ( not based on actual data :) ). 


And here is an interesting exercise :

  1. Go to http://www.dominos.co.in/  
  2. Ensure that you get an annoying popup, that starts playing a YouTube Video without you clicking any start button.
  3. Now close that popup.
  4. Click on the Order Online icon
  5. Ensure that you see the annoying sign-in/sign-up shenanigan.
  6. Click on Login via Facebook, and give the permissions ( you can revoke this application from accessing your data at any time)
  7. You are redirected to a page to complete the form, which includes a Date of Birth control
  8. Attempt to enter your Date of Birth
  9. Click approximately 300 times ( If you are born in 1987 ) to reach to the correct month.


Sunday, August 7, 2011

My Project Analysis

Just roaming around here and there, I came across this simple yet elegant tool to analyse your hobby projects.

Its CLOC, a tool to run a Lines-Of-Code count for a source code directory. Its fairly simple to use. Just download the .exe, go to the command prompt and pass in the source directory which you want to be analysed. I passed in my master resource directory, and found a useful trend.

Cloc

The above report did not include my php source files, although I am sure, I have a couple of PHP projects out there. The ignored files must be my svn repo files and images/log files.

If you could avoid the HTML count ( Who codes HTML these days !), It appears to have found quite a few “long” JS source files. That data too has noise, because it would have picked up framework files like prototype.js and mootools.js. The non-noisy count is of the Java files,which indicate that I document a lot Smile. 45KLOCS is not that bad for a hobby. And yes, all the JSPs were hand written as far as I remember,so that too adds to the list. 63KLOCS !!!

Have fun using this tool

Saturday, August 6, 2011

Serialization in Java

It’s been a while since I wrote anything, but today I felt the need to do so,because of an interesting issue I faced.

I, as part of my routine adhoc coding, was serializing java objects over a regular network socket. Objects to be serialized were POJOS. I was using the same stream to write multiple objects, as well as same objects multiple times with different states as shown below:

outputStream.writeObject(obj);
outputStream.writeObject(obj1);
outputStream.writeObject(obj2);
obj.someSetters();
outputStream.writeObject(obj);

In doing the above I used to get 2 different exceptions which occurred inconsistently:

  1. OptionalDataException
  2. StreamCorruptedException

The above exceptions were not reproducible and occurred sporadically.

Another issue that I faced was with the state of the object. It appeared that once an object is written to the stream, and then you change the state of the object,and try to rewrite the same object, the older version is written, and the newer changes are not reflected.

All the above issues were resolved with a call to outputStream.reset()

This call has to be made, if you want the stream to forget that it ever wrote anything. In common scenarios, once a stream is opened, and an object is written to it, it is closed. But if you are planning to write multiple objects to the same stream sequentially, I suggest you pay heed to the above scenario.

Would love to discuss more on the issue.

Saturday, February 19, 2011

CoolJS : Simple JavaScript Text Animation

Usually I spend my weekends doing some kind of coding or the other. My personal favourite is JavaScript. I love the simplicity and power that JavaScript has as a programming language.Add to this a couple of nice JS Libraries, and the effort becomes worth sharing !

I have used mootools to create a script where a simple piece of text like this can be changed into an impressive animation.

Without wasting anymore time, I would like to dwell into the code right away … !!!

First I would like to show the HTML setup required :

 

   1:  <html><head>


   2:  <script type="text/javascript" 


   3:  src="https://ajax.googleapis.com/ajax/libs/mootools/1.3.0/mootools-yui-compressed.js" >


   4:  </script>


   5:  <script type="text/javascript" src="cooljs-1.0.js" >


   6:  </script>


   7:   


   8:  </head>


   9:      <body onload=loadCoolJS() >


  10:      <p>&nbsp;</p>


  11:   


  12:      <p>Text below is animated. Hover mouse to see it in action</p>    


  13:          


  14:      <p>&nbsp;</p>


  15:          


  16:      <div class="cooljs" style="font-size:22px;">


  17:      This is some sample text which i intend to animate.


  18:              


  19:      </div>


  20:          <p>&nbsp;</p>


  21:          <div>


  22:          Here is some normal text.


  23:          </div>


  24:      </body>


  25:   


  26:  </html>




 



The code need not be explained,  but just for the heck of it, I am including 2 javascipt files, first one is the mootools JS library hosted at Google, and the second one is the JS code that I wrote.



I call the function loadCoolJS()when the document loads, whose functionality I would describe later. The JS code automatically picks the element which have the CSS class named “cooljs”,and animates the inner text.



Note: Make sure there is no HTML inside the element which you are declaring as cooljs. That’s all at the HTML end.



Moving to the javascript setup, which surely needs some explaining, here we go :




   1:  var bg = document.bgColor; //background color


   2:  var fg = 'black';   //foreground color


   3:  var ig = 'red'        //initial color


   4:  if(bg=='')


   5:      bg='white';


   6:   


   7:   


   8:  function  loadCoolJS(){


   9:   


  10:  $$('div.cooljs').each(function(item,index){


  11:   


  12:  var s = item.innerHTML.trim();


  13:  item.innerHTML='';


  14:   


  15:  for(i=0;i<s.length;i++){


  16:   


  17:  var sp = new Element("span",{


  18:              styles:{


  19:              opacity:0.01,


  20:              cursor:'pointer'


  21:              },


  22:              events:{                


  23:              mouseover:function(){eMouseOver(this);},


  24:              mouseout:function(){eMouseOut(this);}            


  25:              }


  26:              


  27:              });


  28:   


  29:  sp.set('html',s.charAt(i));


  30:  sp.mouseOverFx = new Fx.Tween(sp);


  31:  //console.log(sp);


  32:  item.grab(sp);


  33:  }


  34:   


  35:  });


  36:  }


  37:   


  38:  function eMouseOver(e){


  39:  e.mouseOverFx.cancel();


  40:   e.mouseOverFx.start('opacity',0.01,1);


  41:  }


  42:   


  43:  function eMouseOut(e){


  44:  e.mouseOverFx.cancel();


  45:  e.mouseOverFx.start('opacity',1,0.01);


  46:  }





Mere 46 lines of code! That’s the beauty of JS. Anyways moving forward line# 1-5 do nothing but setup the color, which as a matter of fact I am not using at the moment. I keep the text style intact as it was in the cooljs element.





In line# 10 I iterate through all DIV elements of class type cooljs and for each element do the following



First I extract the text contained in the DIV tag in line#12. Then, I remove whatever text the tag has in line# 13, to be replaced by HTML code generated by me via code.



Then I iterate over each character in the extracted text, creating a SPAN tag out of each,setting 2 CSS properties: opacity(0.01) and cursor,and adding 2 event handlers mouseover and mouseout.. The opacity has been set to nearly invisible so the the text is hidden initially.



At line# 29 I set the text inside the span. ( 1 character for each span).



At line #30 I create an Object of Fx.Tween over the created span, and add it to the SPAN DOM object. Fx.Tween is provided by the mootools JS library. This performs the actual animation over an element, tweening the specified CSS property from x to y over a specified time interval.



At line# 32, I insert the created SPAN into the DIV from where I took the text. This process happens for each character inside the DIV tag.



Then comes the event handler functions, at line#38 I have the mouseover event handler. The function gets the SPAN item itself as the parameter, since at line#23 and 24, “this” is passed to the event handler code, which means the current object in scope i.e. sp in this case.



At line# 39 any currently running animations are cancelled, and at line# 40 a tween starts, for the CSS property opacity, changing it from 0.01 to 1, which means from nearly invisible to perfectly visible.



A similar code exists for mouseout event handler, the only difference being that this time the opacity changes from 1 back to 0.01.



The logic is simple, the code is small, and the demo can be found at http://bpnarain.com/cooljs/ .



I would love to get some feedback over this. If you are interested in using this code somewhere else, you are free to do so, and you are free to ask for my help if you are incapable of it.

Wednesday, January 26, 2011

Garbage Collection and Object Size in Java

This is not one of those High Class profiling tools, but this class performs a simple function of creating and destroying a large number of instances of a Test class, and seeing how much memory is freed after every garbage collection call. Assuming that it does run on every request.
The code is pretty customizable, with all the parameters at the top of the code. The comments try to explain the working, but additional explanation is provided at the bottom of the code, wherever necessary.
 


/**


 * To test Garbage Collection , and Object Size


 */




import java.awt.Color;


import java.awt.Graphics;


import java.awt.image.BufferedImage;


import java.awt.image.RenderedImage;


import java.io.FileOutputStream;


import java.text.NumberFormat;


import javax.imageio.ImageIO;




/**


 * @author Bageshwar Pratap Narain


 * 


 */


public class GraphDemo {




/**


     * @param args


     */


public static void main(String[] args) {




/*


         * Graph Image Width


         */


int imW = 1200;




/*


         * Graph Image Height


         */


int imH = 800;




/*


         * The initial number of objects to check with.


         */


long initValue = 10000;




/*


         * The increment value to plot the graph. The <code>incValue</code> is


         * added to <code>initValue</code> until it reaches <code>limit</code>


         */


long incValue = 10000;




/*


         * The Upper limit of the number of objects to check with.


         */


long limit = 120000;




/*


         * Image Type. Exceptable values are "jpg", "png"


         */


String imageType = "jpg";




/*


         * The complete path where the graph image will be saved. Take care of


         * directory separator in Linux vs Windows yourself.


         */


String imgPath = "d:\\graph.jpg";




/*


         * The Radius of the point that is drawn on the graph.


         */


int pointRadius = 6;




/*


         * Initializing Graph Image


         */


BufferedImage bi = new BufferedImage(imW, imH,


BufferedImage.TYPE_INT_RGB);


Graphics g = bi.getGraphics();




/*


         * Setting the background to white. Strangely it was black by defualt.


         */


g.setColor(Color.WHITE);


g.fillRect(0, 0, imW, imH);


g.setColor(Color.BLACK);


// now the image writer is ready to create the graph.




/*


         * An array of [Number of Objects][Average size of Objects].


         */


float data[][] = new float[(int) ((limit - initValue) / incValue)][2];


int temp = 0;




// get all the doRun values and need the min and max values also.


float min = Float.MAX_VALUE, max = Float.MIN_VALUE;




/*


         * Runs a method, which creates "n" number of objects at a time and


         * garbage collects them. The average size of the object is calculated.


         * The loop works on <code>initValue,incValue and limit</code> . The


         * maximum and minimum average object sizes are also calculated in the


         * same loop.


         */


for (long i = initValue; i < limit; i = i + incValue) {


data[temp][0] = i;


data[temp][1] = doRun(i);




if (data[temp][1] >= max)


max = data[temp][1];




if (data[temp][1] <= min)


min = data[temp][1];




temp++;


}




/*


         * x_files is the scale factor, which is used to expand the Y-axis to


         * better visualize the graph, by only concentrating on the concentrated


         * part of the graph.


         */


float x_files = (max - min) * 1.3f; // taking a 30% margin




/*


         * System.out.println("Min : " + min); System.out.println("Max : " +


         * max); System.out.println("X : " + x_files);


         */




/*


         * Used internally to draw the line graph.


         */


int initX = 0, initY = 0;




/*


         * Used internally with the scale factor on the Y-axis.


         */


float unit = imH / x_files;




/*


         * 


         * To format the Average Object 


         * size float value


         */


NumberFormat nf = NumberFormat.getNumberInstance();


nf.setMaximumFractionDigits(5);


nf.setMinimumFractionDigits(5);


 


for (int i = 0; i < temp; i++) {


float r = data[i][1];




/*


             * X and Y co-ordinates are calculated based on the simple arithmatic


             * function.


             */


int x = (int) ((data[i][0]) / (limit / imW));


int y = (imH - (int) ((r - min) * unit));


// System.out.println(r + ":" + x + ":" + y);




// Drawing the Point.


g.fillOval(x, y, pointRadius, pointRadius);




/*


             * Drawing the point connecting line.


             */


if (!(initX == 0 && initY == 0))


g.drawLine(initX, initY, x, y);


/*


             * Translating points for the next line to be drawn.


             */


initX = x;


initY = y;




/*


             * Labelling the graph logically.


             */


g.drawString(nf.format(r) +" @ " + (int)(data[i][0]), x, y);


}



try {


/*


             * Finally writing the Image data to the file.


             */


ImageIO.write((RenderedImage) bi, imageType, new FileOutputStream(


imgPath));


} catch (Exception e) {


e.printStackTrace();


}




}




/*


     * @param o O is the number of objects to test. @return Average Size of


     * Object in Bytes.


     */


private static float doRun(long o) {


Runtime r = Runtime.getRuntime();




long noOfObjects = o;




/*


         * Cleaning up the memory before the experiment.


         */


System.gc();




long memSize = r.freeMemory();




/*


         * Creating Bogus objects.


         */


for (long i = 0; i < noOfObjects; i++) {


/*


         * This is the Object under experiment. 


         * Change this to the Object of your choice.


         */


new Test();


}


long finalSize = r.freeMemory();


System.gc();




/*


         * Calculating the Average Object Size


         */


float val = ((memSize - finalSize + 0.0f) / noOfObjects);




return val;


}




}




/*


 * The Test Candidate Class.


 */


class Test {




}




 



Explanation



The initial image dimension are suitable for a normal graph, but if you are testing over a large range of objects, you should increase the width. Height is not that important since the estimated size of object does not change that much.


The initValue, incValue and limit are used to create “initvalue” number of objects, and then increasing the number by “incValue” until it reaches “limit”.


The output on the graph is


Average Object Size @ [Number of Objects created]


The lines of the graph are not that neat, since no anti-aliasing is used neither is planned to!


Drop me a mail if you have any more suggestions.