Monday, February 18, 2008

Processing videos in Java

In this post, I would like to share with the visitors on how to

  1. How to load videos into Java using JMF
  2. How to extract frames from a video file like avi,mpg,etc using Java Media Framework.

The class I developed for this purpose is called VideoUtility which is similar to the Image Processing utility I wrote in Java. In order to process Videos in Java, you need to use Java Media Framework, which can be obtained from the Sun Website and should be installed. Note that the JMF sometimes can be installed as a platform dependant package which makes it more efficient than the platform-independent version. Anyway once you download the JMF library, add it to the application classpath. Refer to the code shown below. I appreciate if you keep my copyright intact and if you find proper use of this class, please let me know.

   1: import java.awt.Image;


   2: import java.io.File;


   3: import java.io.FileNotFoundException;


   4: import java.io.IOException;


   5: import java.util.ArrayList;


   6: import javax.media.Buffer;


   7: import javax.media.Manager;


   8: import javax.media.MediaLocator;


   9: import javax.media.NoPlayerException;


  10: import javax.media.Player;


  11: import javax.media.Time;


  12: import javax.media.control.FrameGrabbingControl;


  13: import javax.media.control.FramePositioningControl;


  14: import javax.media.format.VideoFormat;


  15: import javax.media.util.BufferToImage;


  16: /** @author Krishna Vangapandu **/


  17: public class VideoUtility


  18: {


  19:     @SuppressWarnings("deprecation") 


  20: /** * videoFile - path to the video File. */ 


  21: public static Player getPlayer(String videoFile) 


  22:     throws NoPlayerException, IOException


  23:     {


  24:         File f = new File(videoFile);


  25:         if (!f.exists()) throw new FileNotFoundException("File doesnt exist");


  26:         MediaLocator ml = new MediaLocator(f.toURL());


  27:         Player player = Manager.createPlayer(ml);


  28:         player.realize();


  29:         while (player.getState() != Player.Realized);


  30:         return player;


  31:     }


  32:     public static float getFrameRate(Player player)


  33:     {


  34:         return (float)noOfFrames(player)/(float)player.getDuration().getSeconds();


  35:     }


  36:     public static int noOfFrames(Player player)


  37:     {


  38:         FramePositioningControl fpc = (FramePositioningControl)player.getControl("javax.media.control.FramePositioningControl");


  39:         Time duration = player.getDuration();


  40:         int i = fpc.mapTimeToFrame(duration);


  41:         if (i != FramePositioningControl.FRAME_UNKNOWN) return i;


  42:         else return -1;


  43:     }


  44:     /** * * @param player - the player from which you want to get the image 


  45:     * @param frameNumber - the framenumber you want to extract 


  46:     * @return Image at the current frame position */ 


  47:   public static Image getImageOfCurrentFrame(Player player, int frameNumber)


  48:     {


  49:         FramePositioningControl fpc = (FramePositioningControl) player .getControl("javax.media.control.FramePositioningControl");


  50:         FrameGrabbingControl fgc = (FrameGrabbingControl) player .getControl("javax.media.control.FrameGrabbingControl");


  51:         return getImageOfCurrentFrame(fpc, fgc, frameNumber);


  52:     }


  53:  


  54:     public static Image getImageOfCurrentFrame(FramePositioningControl fpc, FrameGrabbingControl fgc, int frameNumber)


  55:     {


  56:         fpc.seek(frameNumber);


  57:         Buffer frameBuffer = fgc.grabFrame();


  58:         BufferToImage bti = new BufferToImage((VideoFormat) frameBuffer .getFormat());


  59:         return bti.createImage(frameBuffer);


  60:     }


  61:  


  62:     public static FramePositioningControl getFPC(Player player)


  63:     {


  64:         FramePositioningControl fpc = (FramePositioningControl) player .getControl("javax.media.control.FramePositioningControl");


  65:         return fpc;


  66:     }


  67:  


  68:     public static FrameGrabbingControl getFGC(Player player)


  69:     {


  70:         FrameGrabbingControl fgc = (FrameGrabbingControl) player .getControl("javax.media.control.FrameGrabbingControl");


  71:         return fgc;


  72:     }


  73:  


  74:     public static ArrayList<Image> getAllImages(Player player)


  75:     {


  76:         ArrayList<Image> imageSeq = new ArrayList<Image>();


  77:         int numberOfFrames = noOfFrames(player);


  78:         FramePositioningControl fpc = getFPC(player);


  79:         FrameGrabbingControl fgc = getFGC(player);


  80:         for (int i = 0;i <= numberOfFrames;i++)


  81:         {


  82:             Image img = getImageOfCurrentFrame(fpc, fgc, i);


  83:             if(img!=null) imageSeq.add(img);


  84:         }


  85:         return imageSeq;


  86:     }


  87:  


  88:     public static ArrayList<Image> getAllImages(String fileName) throws NoPlayerException,IOException


  89:     {


  90:         Player player = getPlayer(fileName);


  91:         ArrayList<Image> img = getAllImages(player);


  92:         player.close();


  93:         return img;


  94:     }


  95: }



The main method of interest here is the "getAllImages()" method which returns all the frames as an arraylist of Images. For the specified filename it obtains a Player that is used to retrieve all the images. The reason I posted this article is that I find quiet a few visits to my blog to my article on Image Processing. I am not sure on how useful that post was but I thought may be there is someone out there who might need to get started to extract frames from videos. I put in a lot of effort and looked up a lot of material to actually come up with some code that makes sense.

Thursday, February 14, 2008

Java Closures : Introduction

Folks have been working on getting closures into the next release of Java - Dolphin or Java 7. In the past I have posted a tiny video on how to work with closures in Groovy.

Go to www.javac.info to download the closures prototype compiler and extract it. Extract the archive using tar command on linux(that is what I use for development and testing out something new on Java).

You can notice a "java" command and "javac" command. Now if you already have JDK in your path(which you should have in order to tryout the prototype compiler), you differentiate between "java" in your path and the "java" in this directory by simply doing a "./".

To compile a Closure Demo you need to say

./javac MyClosureDemo.java 

I put ./ in front of "javac" so as to differentiate between javac which is already in my path.

Now try running these commands...

$java -version
$.
/java -version

You would notice that the one with ./java returns an internal bootstrap version number while the java returns the actual 1.x release.

Lets get started and write a simple closure.Within main() method try this statement.

{String => int} myFirstClosure;
myFirstClosure
= { String name =>name.length() };

Two things to notice :
1. Firstly name is the parameter this closure takes.
2. There is no "RETURN" statement (return). Some of us not happy about the missing return and how it deviates from the-Java-way. Anyway, I do not give a damn. We should be happy about that a lot of people have put in a lot of effort to come up with something so cool. Instead of complaining, appreciate their effort.

Anyway, the last statement with no ; is returned to the closure. If there is no such statement without a ; then its a closure that returns void.

Since it returns an integer, we can declare this closure as

{ String => int } myFirstClosure; 

This is of the format

{ parameters => returnType } identifier 

As like any method, returnType is mandatory.

You invoke the closure by calling the "invoke()" method and passing to it the parameters that the closure takes in.

int Length = myFirstClosure.invoke("Something"); 

Try out the shown closure, save the file and compile using the ./javac the prototype compiler. The compilation should be successful!

Complete Code:

package screencast; // I placed the demos in this package

/**
* This is one of my first demos on how to use closure!
*/
class FirstClosure {

public static void main(String[] args) {

{ String
=> int } myFirstClosure;
myFirstClosure
= { String name => name.length() };
//{formal => returntype } identifier;

String name
= "Bhargav";

int length = myFirstClosure.invoke(name);

System.
out.printf("My name is %s and the length of my name is %d",name,length);

}
}


Ok, if you look at what was generated in the "javax" directory. You should see Interfaces in the package javax.lang.function. Some of the interfaces that I know are I, II, III and a closure is actually translated into these interfaces and its body becomes the body of the invoke() method which these interfaces define! More implementation details here.

Now run the program using

./java screencast.FirstClosure 

And you are done!!!

Get started and refer www.javac.info, there is amazing tutorial posted there!

Saturday, February 09, 2008

Closures in Groovy

The following screencast demonstrates usage of closures in Groovy using very simple examples. Look out for more Groovy Programming Videos ...

Keyword Helper - My posts

Intention of this post is to give link to my posts for popular keywords

How to develop Groovy Programs in Eclipse

C# 3.5

Peer to Peer Programming [C# p2p Programming would be posted soon]

Image Processing in Java (Histogram, Grayscale to Color Image, etc)

StackOverflowException in Java - solution

Using SWT Browser

CapGemini 1st round interview

CapGemin 2nd round Interview

Free Screen Recording tools

Installing Audio Drivers on Linux

These keywords, I picked based on the Google Analytics Reports. I hope to improve traffic and at the same time make it easy for people who hit my website...lame idea I guess! ;)

Asynchronous Programming in .NET (C#)

Asynchronous Programming is supported by several areas in the CLR like Sockets, Remoting, Web Services, File IO, etc. In order to fully take advantage of these features, I think, one should know how to make asynchronous method calls, in the first place.
Asynchronous Calls -> You invoke the method and do not wait for it to complete. Instead you go ahead executing the subsequent calls. This is advantageous for situations where the subsequent code has got nothing to do with this method call. For example, you have obtained some data which you wish to write to a socket. In this situation you might not have to wait until the data is written. In this case, you can write the data asynchronously. Refer to this article for more detailed explanation of APM (Asynchronous Programming Model)
In order to make asynchronous calls, follow the steps...

1. Create the method you wish to call asynchronously.
public static void HelloWorld(string message)
{
Console.WriteLine("Welcome to my blog : "+message);
}
2. Write a delegate with the same signature as that of your method. Note delegates are declared outside a class or a struct, but not within.

public delegate void AsyncHelloWorld(string message);
3. Within Main() or wherever you wish to make this call, create an instance of this delegate passing the method you wish to be invoked.

AsyncHelloWorld acm = new AsyncHelloWorld(HelloWorld);
4. Invoke the method using BeginInvoke() which returns an instance of IAsyncResult. The first parameter is the parameter that is to be passed to the method HelloWorld. If there are more than one parameters that the method takes, then pass them in the same order. So we should say the BeginInvoke() takes a variable set of parameters and except the last two, the rest of the parameters are passed to the method. The last two parameters are the AsyncCallBack (you pass a method that is to be invoked on completion of execution of this method) and AsyncState. More about the arguments is here.
IAsyncResult res = acm.BeginInvoke("Krishna",null,null);
5. This call does not block unlike other method calls and instead proceeds further with execution. Now you might at sometime require to wait until this method is actually executed. In that case you make use of EndInvoke() method which takes in argument as the IAsyncResult object returned by the BeginInvoke().
acm.EndInvoke(res); //wait until the method is completed
6. On completion of execution, this method returns.

The complete code is shown below and is written in Snippet compiler
using System;
using System.Collections.Generic;
//should import the following namespaces...Important!
using System.Runtime.InteropServices;
using System.Threading;

public delegate void AsyncHelloWorld(string message);
public class MyClass
{
public static void HelloWorld(string message)
{
Console.WriteLine("Welcome to my blog : "+message);
}


public static void Main()
{
Console.WriteLine("Method to be called");
AsyncHelloWorld acm = new AsyncHelloWorld(HelloWorld);
IAsyncResult res = acm.BeginInvoke("Krishna",null,null);
//HelloWorld("Krishna");
Console.WriteLine("Method has returned");
acm.EndInvoke(res);
}
}


Asycnhronous Programming Screencast ....
[Developed with DeBugMode Wink]

Friday, February 08, 2008

Passing Command Line Arguments in Visual Studio

Recently, my friend Kishore asked me how to pass command line arguments to applications through Visual Studio. It has been long time since I ever passed any command line args to apps while debugging. For convenience sake, I usually hard code and later change it once I think my app does not break(which is not good ofcourse). Anyway, here is how you do ...

1. Go to Solution Explorer. Right click on the project and click Properties
2. Now in the Properties page that you see, go to Debug tab.
3. In debug tab, go to Start Options Section in which you see a textarea with title "Command Line Arguments"

Simple enough but not as easy as it should be. There should have been a menu item within build which you can use to directly pass arguments to your application. May be, a Visual Studio Add-in could do that, but the add-in development is very painful and the documentation does not match with what Visual Studio 2008 actually gives.

Live Translator Fun

As always, I am big fan of Microsoft products. So the intention of this post is not to make fun of Microsoft or Live products, but something that I felt funny. Take a look at the Live translation of my previous blog entry.
Firstly, I do not understand spanish but still I tried a live translation and I found my code to be really funny after it gets translated. May be there should be some research going on, to identify the context of the text and based on that invoke translation! But until then, I find it funny.

Thursday, February 07, 2008

Static Members in C++

 

Static in C++ mean the same as that in Java. It is a shared member and all objects of type X will have the same copy of static members of X. Look the simple example:

1 #include<iostream>
2 using namespace std;
3 class Boo;
4 class Foo
5 {
6 public:
7 Foo(){}
8 ~Foo(){cout<<"Foo Destructor called"<<endl;}
9 static Boo b;
10 };
11 class Boo
12 {
13 public:
14 Boo() { cout<<"Boo constructor called"<<endl;}
15 ~Boo() { cout<<"Boo destructor called"<<endl;}
16 string getName(){ return "Krishna";}
17 };
18
19 /*In order to access a static member, you need to declare its scope first*/
20 Boo Foo::b;
21
22 int main()
23 {
24 Foo f; //object Foo() is created;
25 Foo g;
26 cout<<"End of code in main"<<endl;
27 }
This example conveys two important points
  • In order to be able to access static member of Foo outside Foo, you should declare it as in the line 20.

  • The memory for static members is allocated only when this declaration in the file scope is made. In Java, memory for static members is allocated the first time you access that class which owns these members. (For clarity, comment out line 20 and run the code again).

  • Irrespective of the member being accessed or not, this declaration invokes the constructor of Boo.

    Sunday, February 03, 2008

    Matching two arrays - One Line Beauty ..

    Recently I wrote some "useful" code which I would probably release online as an open source; if things do not go as expected. Anyway during that, I had a requirement where I have to match two arrays and return the match %. So let us do it in C# 2.0 or Java for that matter. Look at my code ...

    public double match(string[] array1, string[] array2)
    {
    int common = 0;
    foreach(string val1 in array1)
    foreach(string val2 in array2)
    if(val1.equals(val2)) common++;
    double avg = (array1.Length + array2.Length)/2;
    return common/avg;
    }


    Now let us do it in C# 3.0 Way, using extension methods which are already written for us ..

    public double match(string[] array1,string[] array2)
    {
    int common = array1.Where(item=>array2.Contains(item)).Count;
    double avg = (array1.Length+array2.Length)/2;
    return common/avg;
    }


    Isn't that sweet? Well, it definitely is sweet. You could do something like that even in Groovy..

    public match(array1,array2)
    {
    def common = array1.find(it->array2.contains(it)).size();
    def avg = (array1.length()+array2.length())/2;
    return common/avg;
    }


    Well, the functions size() might either be length() or count() which I usually am confused and since I always an IDE to code, I usually do not take the pain to remember these simple(but important) details. Anyway, if you want to pick the common elements in 10 arrays, even then the code in C# 3.0 or Groovy is going to be 3-4 lines. So it 400% less code?

    The point here is that languages are getting sexier with time and it is really fun to write amazingly compact code. For those who haven't tried LINQ, should really take a look at it. By the way, I did a little LINQ to XML and with very little code, it makes using RESTful web services very easy. Hats off! to all the genius who came up with these ideas (of course, Microsoft did not invent closures...)

    Wednesday, January 30, 2008

    String comparisons : == vs. equals()

    It is a well known that you cannot compare two objects obj1 and obj2 using == operator. == operator checks for the equality of the references not the equality of the objects. Just a little snippet is shown below

    Point p1 = new Point(100,100);
    Point p2
    = new Point(100,100);
    System.out.println(p1
    ==p2); // ??
    The above code snippet, when run, displays "false" in the output console. But still both p1 and p2 refers to a coordinate (100,100). So if you wish to get your equality to be true for such cases (where the object content! matches), then you should be using "equals()" method. This works for almost all the classes shipped with JDK. For this to work on the objects of the classes that you write (eg: Employee class or Chair or Bench.java), then you should override the method "public boolean equals(Object two)" and implement your meaning of equality of the objects of your class. Also note that, it is highly recommended and important that you override the "int hashCode()" method when you override the "equals" method.

    Anyway, now when we deal with String comparisons, one should remember that "Strings" are not value types but are reference types (I mean String is a class). So Strings have to compared for equality using equals method instead of == operator. But the way the JVM is implemented, there are cases under which the == returns true for matching strings. So what are the cases?

    Case 1: Where == returns true

    String s1 = "Krishna";
    String s2 = "Krishna";
    if(s1==s2)
    System.out.println("Strings are equal!!");
    else
    System.out.println("You cannot use == here");

    Trying running the code as it is and you see the "Strings are equal" on the console. Well can you guess why?

    The reason for the == operator to work in this case is that the Java compiler optimizes the strings s1 and s2. Since they are both "initialized" to "Krishna", instead of having two different string objects, optimization is done by having only one object and both s1 and s2 refer to the same "Krishna" object. Remember that the == operator only works for "static" kind of initialization. So if it was the case where s1 = new String("Krishna"); then s1 == s2 would return false instead of true, though it appears both are being initialized to the same "Krishna". Let us see another case where s1 == s2 fails.

    Case 2: Where == returns false and equals() return true

    String s1 = "Krishna";
    String s2 = new String(s1);
    if(!(s1==s2))
    System.out.println("You cannot use == here");
    else if(s1.equals(s2))
    System.out.println("You should use 'equals' method in all cases");
    Anyway the moral of the story is that you should always use "equals" to compare strings and should never use == even though it works in few cases.

    Monday, January 28, 2008

    More C++ Pointers

    When you perform pointer arithmetic, you move the pointer to the next or previous element of the array. When you say ptr++ where ptr is an integer pointer, it is equivalent to ptr = ptr + 4 (mathematically) assuming integer is of 4 bytes.

    Do not do math on pointers that does not point to array. If one keeps this in mind, then you would probably prevent most of the problems.

    The following code snippet is perfectly legal:

    int
    *ptr = array;
    ptr = ptr+2;
    ptr--;
    ptr++;

    Consider the following declaration:

    int
    numbers[10];

    In the above declaration, numbers is of type int const*. This implies that numbers even though is a pointer, is a constant pointer and it cannot appear on the left side of an expression(as a pointer).

    int *numbers;

    In the above shown declaration,numbers is of type int*. It can still point to an array of itegers and you can actually do a math and can appear on the left side of an expression. So the statement numbers++ in this case is perfectly legal while in the previous case; it is not legal.

    Technorati Tags: ,

    Sunday, January 27, 2008

    .NET 3.5 : VB and C#

    [The code in this post appears weird for some reasons, I used LiveWriter and few good but buggy plugins to attach code]

    I recently made a list of ASP.NET Videos that are out there online. Excluding the MSDN Nuggets and Microsoft Webcast events, the listings spanned over 4 pages!!! I am really concerned and am cursing myself for not having watched any of those for years. I have actually been a close follower of videocasts/screencasts right from those days when there weren't that many online for free. Now Microsoft, I should say is the largest provider of screencasts, of course only about MS technologies and yet there are tons of their videos that I should be watching. (Of course, lets not forget about Channel 9 where there are quiet a lot more screencasts about everything from MS)

    Anyway there is also this dnrTV.com which is run by .NET Rocks guys and provides .NET TV Sessions. The most recent two shows are really something that everyone who is learning .NET should watch. It is by Kathleen Dollard and gives a first hand explanation about .NET 3.5 and shows VB 9.0 and C# 3.0 side by side which is really something! The actual show can be watched here.

    I am writing down some important points for my own use and others might find it useful. I hope I am not violating any rights(hopefully).The disclaimer is that the images shown below is taken from the show using Snipping Tool which is shipped along with Windows Vista. This is not my work and I hope not to make any violations. In case of any, please let me know so that I can remove this post online.
    Anyway my notes follows ....

    .NET 3.5 Assemblies:

    .NET 3.5 The important aspect is that .NET 3.5 still has the same Core - .NET 2.0. Simply put .NET 3.5 is nothing but .NET 3.0 plus additional features and we know that .NET 3.0 is nothing but .NET 2.0 Core plus few amazing libraries like the WPF, WCF, WF, CardSpace. It is also mentioned by Kathleen that Speech library is shipped in the .NET 3.0 and it is not that well known.

    .NET Versions

    .NET Versions There have been five versions of .NET till date. While VB 7 and C# was for .NET 1.0 and 1.1; VB 8 and C# 2.0 was for .NET 2.0 and .NET 3.0.

    Now the brand new C# 3.0 and VB 9.0 adds a lot of new features makes programming in these languages very exciting.

    Anyway the slides look amazing, you should watch the show without fail if you are interested!


    Nullable in VB vs. C#

    Declaring Nullable in VB

       1: Dim x as Nullable(Of Boolean) = False
       2: Dim y as Boolean? = False   

    C# Nullables and bit more code to help you understand what Nullables are!


       1: bool? x = null;
       2: if(x.HasValue)
       3:  Console.WriteLine("x does have a value!");
       4: else
       5:  Console.WriteLine("x do not have a value and is null!");
       6: bool? y = x.GetValueOrDefault(); //y is initialized to false!
       7: Console.WriteLine("y is "+y);

    Differences:

    Suppose x and y are nullable booleans and x is set to null/nothing while y is set to false. Look at these:
    x == y => False in C# and Nothing is VB (since one of them is nothing!). So can you guess the output of the following VB code snippet!

       1: Dim x As Nullable(Of Boolean) = Nothing    
       2: Dim y As Boolean = Nothing    
       3: Console.WriteLine("x = " + ((x = y) Is Nothing).ToString)


    Another note for beginners! Consider the C# code:

       1: Employee emp = null;    
       2: if(emp==null)    
       3:  Console.WriteLine("Emp object is set to null!");

    The equivalent VB code is:

       1: Dim emp as Employee = Nothing    
       2: If(emp = Nothing) 'This does not return true, = Nothing is not equivalent to == null    
       3:  Console.WriteLine("You would not see this line in the output!")    
       4: If emp Is Nothing ' This is how you check for null!    
       5:  Console.WriteLine("emp Object is set to null!")


    If you read the above code snippet, I have conveyed the message in the comment on Line 2.

    Frankly there are lot more differences with respect to how operators work differently in C# than in VB. Simply put the key point to remember is that

    In Visual Basic, comparison between anything that is null(Nothing) to anything else returns Null/Nothing!!

    In C#, you cannot use any operator but == on boolean

    Note: By the way a great tool for .NET Developers in Snippet Compiler!

    Operators in VB vs C#

    Ternary Operator in C#:

       1: bool buddi = false;    
       2: string nameOfBuddi = buddi?"Bhargav":"Someone";    
       3: Console.WriteLine("Buddi is "+nameOfBuddi); //Displays "Someone"    
       4: buddi = true;    
       5: Console.WriteLine("Buddi is "+buddi?"Bhargav":"Someone"); //Displays "Bhargav"

    Ternary Operator in VB:

    IIf was used as ternary operator in VB but it is actually a function! But in VB 9.0, IIF is an operator! The actual difference would be understood when you look at this snippet:
       1: Shared Sub Main()    
       2:   Console.WriteLine(IIf(true,Method1(),Method2()))    
       3: End Sub    
       4:      
       5: Function Method1 as Integer    
       6:     Console.WriteLine("Method 1")    
       7:     Method1 = 1    
       8: End Function    
       9:      
      10: Function Method2 as Integer    
      11:     Console.WriteLine("Method 2")    
      12:     Return 5    
      13: End Function


    The output of the above snippet is

    Method 1
    Method 2
    1

    As you can see, Method1() and Method2() are first evaluated and then the appropriate return value is returned. Here since its true, return value of Method1() is returned on the screen.

    Another note for beginners, in Visual Basic, you can return a value in two ways. The first way is shown in the above code snippet in Line 7 where you assign FunctionName = returnValue and the second way is to use return keyword, like in other languages. You can use which ever makes more sense to you, well based on your choice.

    The next few features were actually present in earlier versions of VB and unavailable in C# ( the above talked features were in C# only until VB 9.0)

    Contd...

    Tuesday, January 15, 2008

    Storage Classes in C++

    Courtesy: Dave, UGA

    Storage Classes

    Storage class specifies where the object exists in memory. Also the lifetime of the variable's storage determines the storage class of the variable/object.

    Automatic Storage
    1. Default for all the variables
    2. Object is created and destroyed within the block
    3. eg: auto float x,y;
    4. register storage classes is same as auto storage class. Just that it tells the compiler to place the variable to be put in registers(for better performance)
    Static Storage
    1. Lifetime of variable is entire program execution
    2. static can be applied to local variables defined in functions or to global variables
    3. Keeps the value even after the function ends, if its a local variable
    Scopes
    1. Global Scope - visible to any other file - extern
    2. File Scope - visible to only that file - static
    3. Block Scope - visible only within the block.
    Some funda
    1. extern int globalVariable; This is a variable declaration and this can be specified any number of times. No memory is allocated to this variable yet and thus multiple declarations are allowed. If you have an extern variable and try to access it you get a linker error. To prevent this, you should define a variable of the same name. Then you have actually defined a reference.
      Ex: extern int gv; int gv; //then you can access gv.
    2. int anotherVar; This is a variable definition and this can be done only once. This variable has been allocated memory and falls under the auto storage class.
    3. static int getVar() If this function is present in File1.cc and if you try to invoke getVar() in File2.cc, then this is a compiler error since the scope of this function is limited to the File1.cc only.
    4. static has another purpose in C/C++. You have a static variable in a function foo(), then within foo(), increment the variable and print out the variable. Now within main call foo() three times. Then each time you get a different(incremented) value. That is the lifetime of the variable is "complete" program. As long as the program runs, the variable value would be stored. The value is restored even after the function returns.
    5. Global variables in C/C++ default to zero, while local variables are garbage!

    Monday, January 14, 2008

    What is the output of this C++/C Program?

    When compiled using GCC compiler, can you tell what is the output of the following program?

    #include
    int main()
    {
    int y=10,p=20;
    int num[10]={0};
    int x=10,z=4;

    num[-2] = -2;
    num[10] = 10;
    printf("%d\n%d\n",p,z);
    }

    This program is supposed to be compiled on SunOS, using GCC compiler. Running it on different machine might give a totally different output.

    If you run this program, you would understand how dangerous is C++ arrays, if not properly coded. Ofcourse this program does not actually corrupt your system but it does corrupt one of the variables and at times this might be dangerous.

    Courtesy: Got this snippet from Dr. Dave's class. But a different example. I really liked this simple program that conveys a very big idea.

    Wednesday, January 09, 2008

    My work till date ...

    Below is a list of projects that I have developed/worked on. This is to let me have a good idea on what I have worked on, for the upcoming interviews.

    Software Associate

    Online banking system using CICS
    Legacy Decommissioning of 21C Systems

    Freelance Developer
    VB.NET Scheduler Program(with GUI and Win Service)
    FTP Uploader/Downloader(VB.NET)
    IP and System Info(ASP.NET,C# Win Service, Binary Serialization, Set up projects in VS 2005)
    C# to VB.NET Conversion(ASP.NET Project)
    URL Ping Service(C# Win Forms, Set up package, SMTP Coding)
    Localization in .NET(ASP.NET and WinForms examples how-to)
    Social Networking (Java Servlets! Orkut clone like Software)
    ASP.NET Content Management System(ASP.NET VB.NET)
    Postscript Expression Evaluation in C#
    ASP.NET GDI+ Cropping(ASP.NET)
    Small Various VB.NET Projects
    XML Serialization Tutorial and Sample project
    Distributed Error Reporting Tool(C#)
    Whois Lookup in VB.NET
    various book reviews at java-tips.org
    Personal Information Manager(VB.NET)
    Java Servlets Project(my first work!!)
    And few other small help projects.

    School/Personal Work
    Windows Registry Tweaker in C#
    Windows Remote Desktop in C#
    Bulk Mail Sender
    Mail GUI and Proxy Server
    Bulk Image Compressor
    Mean Shift Tracker in Java
    Blob Library in Java
    URL Redirection Detection
    Loads of Web Crawlers
    Grails - BlockBusted Movie Website
    and a few others which i cannot recall at this moment!

    Tuesday, January 08, 2008

    Configuring SWT Browser Preferences (2)

    In one of my previous posts, I blogged about the way one could set SWT Browser Widget Preferences and there has been a comment on my blog!!! (well apart from the comments that my friend Suri makes)
    The comment has rightly pointed out to a way that one could programatically set the preferences of SWT Browser widget. The way it could be done is shown in the following code snippet.

    Browser browser = MozBrowserUtil.openMozillaBrowser("about:blank");
    nsIServiceManager servMgr = Mozilla.getInstance().getServiceManager();
    nsIPrefBranch prefs = ( nsIPrefBranch )servMgr.
    getServiceByContractID("@mozilla.org/preferences-service;1",
    nsIPrefBranch.NS_IPREFBRANCH_IID);

    prefs.setIntPref("network.proxy.type", 1);
    prefs.setCharPref("network.proxy.http", host);
    prefs.setIntPref("network.proxy.http_port", port);

    browser.setUrl(url);


    Again, I thank the anonymous commentor for bringing this to my notice. I appreciate all your comments and would be better if you leave me atleast an email or a URL to your page/blog so that I can get back to you.