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.

Friday, January 21, 2011

Long File/Directory path in Windows

In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is "D:\some 256-character path string<NUL>" where "<NUL>" represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.)

Note  File I/O functions in the Windows API convert "/" to "\" as part of converting the name to an NT-style name, except when using the "\\?\" prefix as detailed in the following sections.

The Windows API has many functions that also have Unicode versions to permit an extended-length path for a maximum total path length of 32,767 characters. This type of path is composed of components separated by backslashes, each up to the value returned in the lpMaximumComponentLength parameter of the GetVolumeInformation function (this value is commonly 255 characters). To specify an extended-length path, use the "\\?\" prefix. For example, "\\?\D:\very long path".

Note  The maximum path of 32,767 characters is approximate, because the "\\?\" prefix may be expanded to a longer string by the system at run time, and this expansion applies to the total length.

The "\\?\" prefix can also be used with paths constructed according to the universal naming convention (UNC). To specify such a path using UNC, use the "\\?\UNC\" prefix. For example, "\\?\UNC\server\share", where "server" is the name of the computer and "share" is the name of the shared folder. These prefixes are not used as part of the path itself. They indicate that the path should be passed to the system with minimal modification, which means that you cannot use forward slashes to represent path separators, or a period to represent the current directory, or double dots to represent the parent directory. Because you cannot use the "\\?\" prefix with a relative path, relative paths are always limited to a total of MAX_PATH characters.

There is no need to perform any Unicode normalization on path and file name strings for use by the Windows file I/O API functions because the file system treats path and file names as an opaque sequence of WCHARs. Any normalization that your application requires should be performed with this in mind, external of any calls to related Windows file I/O API functions.

When using an API to create a directory, the specified path cannot be so long that you cannot append an 8.3 file name (that is, the directory name cannot exceed MAX_PATH minus 12).

The shell and the file system have different requirements. It is possible to create a path with the Windows API that the shell user interface is not be able to interpret properly.

Thursday, May 20, 2010

A decent way to read articles online

Do you browse a lot, reading articles or diverse fields, and move from one website to another.

Then you must have come across websites, which are pretty badly designed as far as the readability is concerned.

I come across tens of such sites everyday, which have a black background, a grey text color, and some really cool article , worth a try.

So, here is a workaround,

Create a new bookmark, on your bookmark tab, and Give it any name, you feel like, Eg. Readbility.

Then, in the URL box,  paste the following code

javascript:(function(){readStyle='style-newspaper';readSize='size-large';readMargin='margin-narrow';_readability_script=document.createElement('SCRIPT');_readability_script.type='text/javascript';_readability_script.src='http://lab.arc90.com/experiments/readability/js/readability.js?x='+(Math.random());document.getElementsByTagName('head')[0].appendChild(_readability_script);_readability_css=document.createElement('LINK');_readability_css.rel='stylesheet';_readability_css.href='http://lab.arc90.com/experiments/readability/css/readability.css';_readability_css.type='text/css';_readability_css.media='screen';document.getElementsByTagName('head')[0].appendChild(_readability_css);_readability_print_css=document.createElement('LINK');_readability_print_css.rel='stylesheet';_readability_print_css.href='http://lab.arc90.com/experiments/readability/css/readability-print.css';_readability_print_css.media='print';_readability_print_css.type='text/css';document.getElementsByTagName('head')[0].appendChild(_readability_print_css);})();

That’s It !!! Whenever, you need to read a page, which is not readable, due to its design, colors, fonts and sizes, just click on this bookmark.

You can check more about Readability at http://lab.arc90.com/experiments/readability/

Monday, May 17, 2010

Checking out Cheat Engine 5.6

I laid my hands today on Cheat Engine 5.6, and once again jumped into the world of de-compilers and Hex.

ce

Readers should try it for once, to get a feel of the subject. I tried the manual, which has a nice tutorial to cheat Windows Pinball.

Its fairly simple, and easy to learn.

Sunday, May 16, 2010

Bought a new Laptop

Bought a new Laptop, HP Pavilion dv4 2123TX  :)

DSC06346

Pretty excited about it, and to add to the excitement, this one comes from hard earned cash !

The machine is performing pretty well, but I miss a backlit keyboard.

So, now I too belong to the elite brigade of people with more than a couple of devices ! Cheers !!!

DSC06347

Friday, May 14, 2010

Issues with Floating Point Calculations in MySql

Regular comparisons over floating point numbers have some serious issues. The documentation states that DECIMAL type should be used for such comparisons, since they are stored as strings.

Floating point numbers are saved in a platform dependant format, and a simple value 9.78 , might not pass the test someVariable=9.78

The work around for such a problem is to use Round(someVariable,9.78)=9.78 ,for your code to work in the desired manner.

Sunday, May 9, 2010

Archiving your Favourite Mails in Gmail


*Update* : This 5 year post could not keep up with the latest version of firefox and gmail. Continue reading further without any hope of making it work. 




Lately, I had the need to get a few of my chats for archiving offline, but not to my surprize, I found that GMail does not offer any such service, where I could get my data in XML/JSON or a compatible format.

So, I decided to start-off a small venture, to get this thing working.

After a small amount of reverse engineering, I figured that, every chat has a unique msgID, which can be used to get a neat and clean HTML formatted; printer-ready format. But for this to work, needed to fetch all the msgID.

The Trick

  • Every Email is saved as a conversation, each conversation has a msgID and subsequent threadIDs
  • When printing a mail, by its ThreadID, all the threads in the mail are concatenated as neat and clean HTML page
  • Once, one reaches this Printer-Friendly page, it can be saved in plain HTML format
  • Then, using MS Word, one can concatenate such files together, and in the end generate a nice index of emails.

 

The Prick

I Assume, you have already setup the required Label. If not, please get a hands-on on a tutorial to Gmail Labels, and once you master the art, come back to this page.

The following steps have been tested on Firefox 3.5.5.

STEP 1

Download and Install iMacros for your version of Firefox. The best way to do that is to Google for it !

Once you install iMacros, you will have a folder named iMacros inside your My Documents folder. Go inside that folder and the inside Macros.

STEP 2

Create the following files there ( with the attached content )

SaveMails.iim

VERSION BUILD=3700331

TAB T=1

TAB CLOSEALLOTHERS

CMDLINE !DATASOURCE mails.csv

SET !DATASOURCE_COLUMNS 1

'SET !LOOP 2

SET !DATASOURCE_LINE {{!LOOP}}

SET !EXTRACT ""

URL GOTO={{!COL1}}

SEARCH SOURCE=REGEXP:"((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[\s][0-9]{1,2},[\s][0-9]{1,4}[\s]at[\s][\d]{0,2}:[\d]{0,2}[\s](AM|PM))" EXTRACT=$1

SAVEAS TYPE=HTM FOLDER=* FILE={{!EXTRACT}}


 

Links.iim

VERSION BUILD=6650406

TAB T=1

URL GOTO=javascript:javascript%3Am%3Dprompt(%22How%20many%20mails%20are%20their%20in%20this%20label%3F%22)%3Bu%3Dwindow.location.href%2Cs%3D%22%22%3Bl%3Du.substring(u.lastIndexOf(%22%3D%22)%2B1)%3Bu%3Du.substring(0%2Cu.lastIndexOf(%22%3F%22))%3Bfor(i%3D0%3Bi%3Cm%3Bi%2B%3D50)s%2B%3D(u%2B%22%3Fs%3Dl%26l%3D%22%2Bl%2B%22%26st%3D%22%2Bi%2B%22%3Cbr%3E%22)%3Bdocument.getElementsByName(%22q%22)%5B0%5D.value%3Ds%3B


 

ShowMessageIDs.iim

VERSION BUILD=3700331

CMDLINE !DATASOURCE links.csv

SET !DATASOURCE_COLUMNS 1

'SET !LOOP 2

SET !VAR1 {{!LOOP}}

ADD !VAR1

TAB OPEN

TAB T= {{!VAR1}}

SET !DATASOURCE_LINE {{!LOOP}}

URL GOTO={{!COL1}}

URL GOTO=javascript:s%3D%22%22%2Cu%3Dwindow.location.href%2Cs%3D%22%22%3Bl%3Du.substring(u.lastIndexOf(%22%3D%22)%2B1)%3Bu%3Du.substring(0%2Cu.lastIndexOf(%22%3F%22))%3Bt%3Ddocument.getElementsByName(%22t%22)%3Bfor(i%3D0%3Bi%3Ct.length%3Bi%2B%2B)s%2B%3D(u%2B%22%3Fv%3Dpt%26s%3Dl%26l%3D%22%2Bl%2B%22%26th%3D%22)%2B(t%5Bi%5D.value)%2B%22%3Cbr%3E%22%3Bdocument.getElementsByName(%22q%22)%5B0%5D%3D(s)%3B

STEP 3

Switch your Inbox to Basic HTML View ( The Link is at the bottom of the Page )



 
STEP 4

Make sure you are viewing the right label, i.e the one for which you want the mails to be archived.

STEP 5

In iMacros, locate the Links.iim file and play it. Enter the approximate number of email that this label has






 


Thereafter you will see a list of links on the page, select the whole text, and create a new file in "My Documents\iMacros\DataSources" named links.csv. Use NOTEPAD to do this, and not Microsoft Excel. Paste the text there and save.


 


 

STEP 6

Back to Firefox! Locate the Macro named show showMessageIDs.iim. Play (Loop) this Macro, and change the default value "3" to the approximate number of links you saved in STEP 5 (eg. 10, An approximate and large value would suffice.) .This will open a few tabs in your browser depending upon the number of mails you will be archiving.

STEP 7

Create a new File named mails.csv inside "My Documents\iMacros\DataSources" . Open this file in notepad, and then copy the contents of each TAB that opened from the previous step, into this file. Finally save this file.

STEP 8
Disable Javascript by unchecking Tools-->Options-->Content-->Enable Javascript in Firefox.
Now locate the Macro SaveMails.iim, and Play (Loop) this macro, to the number of Mails you wish to archive. An approximate and large value would suffice.

STEP 9

Once STEP 8 completes, ( which will take some time), you will have each of your mails in the folder "My Documents\iMacros\Downloads" . Now comes the more interesting part, Open Microsoft Office ( The code has been tested on Office 2007 ). Go to VIEW-->MACRO-->VIEW-->MACROS-->CREATE MACROS . Provide any arbitrary name, it doesn't matter !

A new Window will open




 

Select all the text and Delete it. Then paste the following Code


 

Sub StartMerge()
'
' StartMerge
' @Author Bageshwar Pratap Narain
' Run this Macros to select a Directory, and merge all the HTML files inside it, into a single file,
' and automatically create a Date Based Index
'
    Folder = "c:\documents and setttings\bageshwar\"
        Dim strPath As String
        Dim strFile As String
        Dim temp As String
        Dim x As Integer
        Dim doc As Word.Document
        Dim current As Word.Document
        'Set current = ActiveDocument

            With Dialogs(wdDialogFileOpen)
                .Name = "*.*"
                If .Display = -1 Then
                    strPath = Options.DefaultFilePath(wdDocumentsPath)
                End If
            End With
               
               Documents.Add Template:="Normal", NewTemplate:=False, DocumentType:=0
               Set current = Windows(1).Document
               
               'Windows(2).Activate
               
            strFile = Dir(strPath + "\")
            'MsgBox (strPath)
            Do While strFile <> ""
                x = x + 1
                strFile = Dir    ' Get next entry.
                If strFile <> "" Then
                    temp = strPath + "\" + strFile
                    Set doc = Documents.Open(temp)
                    Selection.WholeStory
                    Selection.Copy
                    current.Activate
                    Selection.PasteAndFormat (wdPasteDefault)
                    doc.Close
                End If
            Loop
    
    
            Set objWdDoc = Word.Application.ActiveDocument
        
        
    
        ' Set our range to be the entire document contents
        Set objWdRange = objWdDoc.Content
    
        ' To be used for the result string
        Dim Result As String
    
        ' Create a regular expression object.
        Set regEx = CreateObject("VBScript.RegExp")
        
        regEx.IgnoreCase = False
    
        regEx.Pattern = ("((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[\s][0-9]{1,2},[\s][0-9]{1,4}[\s]at[\s][\d]{0,2}:[\d]{0,2}[\s](AM|PM))")
        Dim temp1 As Long
                
                Windows(1).Activate
                Selection.HomeKey Unit:=wdStory
                            
                Do
                        ' Get the first match (Global = False, remember)
                        Set Matches = regEx.Execute(objWdRange)
            
                         ' MsgBox (Matches.Count)
                         If Matches.Count = 0 Then
                            Exit Do
                        End If
    
            
                        ' Get the first match from the MatchCollection.
                            Set Match = Matches(0)
                             'objWdRange.MoveStart(wdCharacter, Len(Match.value) + 1)
                        temp1 = objWdRange.MoveStart(wdCharacter, Match.FirstIndex + Len(Match.Value) + 1)
                        'MsgBox (Match)
            
                        stylize2 (Match)
                Loop
    
                
                ' insertIndex
                '
                '
                    Selection.HomeKey Unit:=wdStory
                    Selection.InsertNewPage
                    Selection.TypeParagraph
                    With ActiveDocument
                        .TablesOfContents.Add Range:=Selection.Range, RightAlignPageNumbers:= _
                            True, UseHeadingStyles:=True, UpperHeadingLevel:=1, _
                            LowerHeadingLevel:=3, IncludePageNumbers:=True, AddedStyles:="", _
                            UseHyperlinks:=True, HidePageNumbersInWeb:=True, UseOutlineLevels:= _
                            True
                        .TablesOfContents(1).TabLeader = wdTabLeaderDots
                        .TablesOfContents.Format = wdIndexIndent
                    End With
    
                    
End Sub


Sub stylize2(text As String)
'
' stylize2 Macro
'
'
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    Selection.Find.Replacement.Style = ActiveDocument.Styles("Heading 1")
    With Selection.Find.Replacement.ParagraphFormat
        With .Shading
            .Texture = wdTextureNone
            .ForegroundPatternColor = wdColorBlack
            .BackgroundPatternColor = wdColorBlack
        End With
        .Borders.Shadow = False
    End With
    With Selection.Find
        .text = text
        .Replacement.text = text
        .Forward = True
        .Wrap = wdFindAsk
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    With Selection
        'If .Find.Forward = True Then
            .Collapse Direction:=wdCollapseStart
        'Else
        '    .Collapse Direction:=wdCollapseEnd
        'End If
        .Find.Execute Replace:=wdReplaceOne
        
        'If .Find.Forward = True Then
        '    .Collapse Direction:=wdCollapseEnd
        'Else
        '    .Collapse Direction:=wdCollapseStart
        'End If
        '.Find.Execute
    
    End With
End Sub


 


 

FINAL STEP

Save the file and close the Macro Editor. Open MS Office, press ALT+F8, and double click on StartMerge.

Finally save the file, print it, eat it or throw it. Enjoy


 

~~~~~~~~~~~~H4x0r~~~~~~~~~~~~


 

ISSUES
The following issues remain unresolved
  • The MS WORD Macros become very slow for more than 100 mails
  • Need to save the mail files into groups,month wise
  • The Regular Expression matching is extremely slow