Tuesday, November 20, 2012

A recursive binary search algorithm


public int binarySearch(int element)
    {
     
        int middleIndex  = calculateMiddleIndex(data);
       
        int zeroIndexedMiddle=middleIndex-1;
       
        if(data.length==0 || (data.length==1 && data[0]!=element))
        {
            System.out.println("Data Not Found");
            return 100; //denoting data not found
           
        }
        System.out.println(data[zeroIndexedMiddle]);
        if(data[zeroIndexedMiddle]==element)
        {
            return middleIndex;
        }
        else if(data[zeroIndexedMiddle]<element)
        {
            tmp=data;
            data = new int[size-middleIndex];
            System.arraycopy(tmp, middleIndex, data, 0, size-middleIndex);
            size=data.length;
            return binarySearch(element);
        }
        else
        {
            tmp=data;
            data = new int[size-zeroIndexedMiddle];
            System.arraycopy(tmp, 0, data, 0, size-zeroIndexedMiddle);
           
            size=data.length;
           
            return binarySearch(element);          
           
        }
       
    }

Tuesday, September 18, 2012

One minute definations.

Java Serialization.

Java has a built in mechanism for converting the state of an object into a specific form of bytes. All of the data , type , and member information of the object is converted into this byte format by a process called "Serialization" and is stored in a file.

The beauty of this technique is that , that Serialization is a JVM independent process. Hence you can serialize an object from Java , and deserialize it from the .NET platform.

Transient Keyword.

The transient keyword is attached to a member field of an object , whose state you do not wish to persist during serialization.


Thursday, January 26, 2012

Introduction to Quantam Computing

Okay this one is going to be painful at best. For a novice (like me) who has no idea and regards the word Quantam with distaste and annoyance , it is only fair to start from the very beginning. The birth of the word , and follow along. Quantam and company is a vast universe of information , papers , theories, maths , physics , equations and problems. It is ever evolving and promises great change into the shape of planet. Ofcourse that didn't mean it would make our earth look like a pentagon , it would however have considerable effect on the technology and lifestyle for that matter, that we currently are accustomed to.

I foresee this article spawning into many pages , so we'll have our coffee sip by sip , second by second , day by day .

Lets start with Quantum.

Quantam Physics

Quantum physics is considered to be an aspect of modern physics. It can be termed as the only major addition to the early physics led out by the kinds of newton. Max plank , a german physicist would be credited for laying the groundwork of the theory.

In the simplest of words , Max plank noted that radiant energy (for example that coming off from a bulb) is not continuous in nature, as picked up by a human eye. When we see a bulb in our room , we can note that the nature of light coming off is continuous. It doesn’t break down. But quantum physics says otherwise. It says radiant energy emitting from a system is NOT in a continuous stream , but in pieces(quanta); its discontinuous. Its not like the flow of the river , rather its like rain ; drop by drop(or like tears -for the very poetic in nature :) ). This assertion of Max plank astonished the world , who were habitual in considering classical physic’s assertion that the emission and absorption of energy like all physical processes takes place in a continuous manner

Try to drink this in , will come back for more laters

Difference between Hibernate Sessions and Transactions.

This article will focus on analogies regarding Hibernate's Sessions and Transactions with real world situations ,which would help readers grasp the real difference between them. Often in process of getting acquainted with Hibernate , this is the first bone of contention.

Session

Most technology terms mean literally what they represent in the English dictionary, well with a little ketchup. A session is a lease of time that you’d take with a fellow, or any other entity. Once you are in a session with the other entity, you can actively use it ; or communicate with whatever communication mechanism that entity has.

Transaction

A transaction occurs AFTER a session. Once you are in a session, you perform transactions. You are in absolute need to be in a session to perform a transaction. You cannot perform a transaction with an entity without being in session with it. For example let’s take an example of a ATM machine.

You go and stand in queue of waiting customers who wish to acquire a session with the ATM. Once the ATM is free, you initiate your session. Now you and the ATM are tunneled, face to face and ready to do business. You dial your pin, and this is where you start your transaction. So any material work you perform with an entity will be called a transaction. So basically the purpose of acquiring a session IS in effect because you wished to perform a transaction. The transaction is the real action that full fills the business you have with the other entity.

Making the other entity aware of yourself is hence called a session, in which you and the entity have now shaken hands. After that as you work, it’ll be termed as a transaction.


Introduction To Generics

Generics are a direct child of the world Generalize. In such our motive is to make a method, class, property etc able to generalize over a domain, rather than being “centralized” or specific.

Generics were introduced first for an ever haunting issue resolution. From their generics other benefits were leveraged out of the topic and a new paradigm of programming was evolved, which was more concise, perfectly natural and easy to understand (difficult to program at times).

Here is the issue that existed before generics came into being

The issue

Generics prime reason of existence is the detection of code issues during compile time because the issues at runtime are always hard to trace. Compile time errors are reported easily alongwith their location and we can easily go and correct them. However often runtime errors force as to play darts in the dark.

Let’s begin writing a non generic piece of code that will highlight the issue.

public class MyWallet {

private Object object;

MyWallet()

{

}

public void add(Object object)

{

this.object=object;

}

public Object get()

{

return this.object;

}

}

The purpose of this code is simple. It simulates a person’s wallet, in which we pass it and object, then retrieve it. As we can see the methods work on Object, we are free to pass in any object as long as it’s not a primitive time (value types like int , floats etc).

Now the real part , supposedly in future it was decided that the Wallet should only hold Integer. There is no way you can restrict the client of the above code to do so. Except that you have to mention that in the comments. Often a developer doesn’t pay much attention to the comments section. If instead of Integer he passes in String , there would be no stopping ; the compiler wont protest and in a more critical real life example this could mean disaster.

public class MyWalletDemo

{

public static void main(String args[])

{

//Only add Integer objects into the box.

MyWallet integerWallet = new MyWallet();

integerWallet.add(new Integer(10));

Integer obtainedVal = (Integer)integerWallet.get();

System.out.println(obtainedVal)

}

}

Okay the above would work fine, without breaking up. We know that the cast we used on the red line would work because we have honored the comment and did exactly as told. We passed in an Integer to the wallet. However notice that the compiler knows nothing about the comment, and won’t stop you from using the add method with an argument of a different type

public class MyWalletDemo2

{

public static void main(String args[])

{

//Only add Integer objects into the box.

MyWallet integerWallet = new MyWallet();

// a careless programmer modifies the arguments as shown below

integerWallet.add(“10”);

Integer obtainedVal = (Integer)integerWallet.get();

System.out.println(obtainedVal)

}

}

Now the red line would burst. Why because we are trying to cast a String into and Integer and deserve to see a cast exception by the compiler. Note also that this is not a compile time error rather a runtime error, which as discussed is a hideous demon in a programmer’s life.

One of the issue resolution that generics were born to resolve was the above , to make the compiler generate a compile time error for the above case , so that a String CAN’T be passed into the add method. If a programmer does that, it won’t compile and would conveniently lead the developer to the red line in the code above, the place where the illegal cast was done.

Resolution


An obvious question now to an attentive reader would be that, if ONLY an integer would cause the program to normally function, and a String would cause it to collapse. Why couldn’t have we just converted the type of object from Object to Integer. Like this

public class MyWallet {

private Integer object;

MyWallet()

{

}

public void add(Integer object)

{

this.object=object;

}

public Integer get()

{

return this.object;

}

}

This makes sense because at the first place, only the Integer value was supposed to work. So why would we use a datatype of Object to complicate the issue and allow other types like String as well.

Well this is a question of code extensibility. If we use the above approach, now our MyWallet class would ONLY accept integers. Okay fine. Say tomorrow, we needed a Wallet which would accept String as well. We would have to open up our class MyWallet , and add functionality for String as well. Say tomorrow, we need our Wallets to work with Bool , then after a few while we need it to work with our custom made classes etc etc. Cleary we see , that the only thing that is messing around is the data type , rest everything remains same. Yet we have to keep on modifying our MyWallet class over and over again to accommodate new types.

A very attentive reader would have sensed an issue in the above paragraph already. None of that was true. At one instant MyWallet class can only exists for ONE type , because there can be only one “get” method that returns a type from the class. Look at the following


public class MyWallet {

Integer integerArgument;

String stringArgument;

public Integer get()

{

return this.integerArg;

}

public String get()

{

return this.stringArg;

}

}

This overloading would obviously not work since the arguments to both of them are same (void). We may introduce different method names for different types , but then a programmer must know beforehand whether MyWallet is being used for Strings or Integers. And there is no way to communicate that to the compiler. If a developer has filled the MyWallet class with Integers , nothing would stop me if I tried to retrieve strings from it. It would compile , and then since the MyWallet class weren’t use for strings , and I had performed operations on strings , the program would burst.

The last way that would possibly work would be to make separate class for separate types . This would be both visual, and would stop compile time errors.

public class MyWallet ForStrings{

private String object;

MyWallet()

{

}

public void add(String object)

{

this.object=object;

}

public String get()

{

return this.object;

}

}

Similarly we can create MyWalletForInteger etc etc. But you and I both can agree that there can’t be anything uglier then the above architecture on the planet. Not only this is a extreme case of code duplication, this nearly decapitates every OOP rule and messes up everything. We would have tons of senseless code littered across, and keeping track of them, and fishing them out would be a terribly bad thing to perform. Such code duplication is not apparent in the above examples , but in reality it is something to be fear. For example a List collection is a generic collection in Java. It takes in objects and stores them and retrieves them and compares them, amongst many other things. Now the List implementation of java is well above a thousand LOC (LinesOfCode). If we cancel generics out , and do what we suggest above , that is make separate classes for separate types like ListOfStrings , ListOfIntegers , we would have well over a million lines of code that have no reason to exist in our project . We realize that the only thing different is the type, and the operations on them etc are the same. Its time to extract the differences and generalize our classes. This is what generics is all about.

It reminds us of a very important OOP rule which states “Encapsulate the changes”. With generics this is what our MyWallet class would look like

MyWallet With Generics

public class MyWallet {

private T object;

MyWallet()

{

}

public void add(T object)

{

This.object=object;

}

public T get()

{

return this.object;

}

}

The code above is self explanatory and beautiful. We have passed in what we call a “type parameter” as we declared the class. Now whatever we pass for T , our class would start operating over it. This is how we would use our MyWallet now

MyWallet integerWallet = new MyWallet();

Once the above is initialized , we’re free to invoke its get method without any need for a cast

integerWallet.add(new Integer(10));

Integer retrievedInteger= integerWallet.get(); //no cast needed.

Also , if we try to add an incompatible type to MyWallet , it will throw us a compile time error which would be easily corrected.

integerWallet.add(“10”);

MyWalletTest.java:5: add(java.lang.Integer) in MyWallet

cannot be applied to (java.lang.String)

integerWallet.add("10");

Type Erasure

Also to note is that Java deploys a Scheme called Type Erasure. Because of this after a program is compiled all the information about the Type of a class is stripped off. As a result at runtime using reflection we would be unable to obtain the Type information of a class.

In contrast , C# generics doesn’t strip off the Type information of a class , and using reflection we would be able to obtain the Type information of a class at runtime.

The discussion about type erasure is best left as a different topic on a different day


Any questions , comments are really welcomed .
Thanks

Mac VS IP


Authentication

So we have an imei and a sim number, a cnic number and a telephone number and mac and an ip address

Suppose a computer with an IP 192.168.1.2 has to be refered to. A broadcast would be sent all over the network. Whoever will have that 1.2 IP will reply , with its mac address. Now this will be mapped.

Now suppose we dont have mac addresses. A broadcast is sent over in the network , a machine replies that yes it is 1.2. How can you be assured that that is the case ? What identification does 1.2 have of being really who it is.?

Analogies

Just like the case that I may have your phone number , but I do not have your CNIC(or SSN) number. I call you and you tell me you are Mr XYZ. I cannot verify that. So you send your CNIC number to me. I make a mapping between your phone number and CNIC. thats it. Now whenever i'll be calling on the number , i can be sure that its the intended person.

Mac Forging

What if you send me someone elses' CNIC number ? well this is theoricitally impossible. Because each machine has ONE mac, and it is BURNT into the hardware. It doesn't live in the memory so that we may be able to access it and change it. Its inside the hardware, burnt into it.

If somehow we find a way to change a MAC address it'll be a disaster. Supposedly 192.168.1.3 is the person i'd like to talk to ; I send a broadcast . 1.3 replies with a MAC address of lets say a different machine (with ip 1.5) . Now all traffic intended for the machine 1.3 , would be going to the machine whose mac address was provided (1.5) .

This means if I send a file through any software like VYpress to the machine 1.3 , the machine with the IP 1.5 would be actually receiving it.

Mac Security

However you can't get away with this. if you forged the mac you'll get caught . Consider the following. Now suppose someone wants to send a message this time to the machine 1.5. When 1.5 would reply with its mac , it'll be the same as the mac provided by 1.3. This will be the point where the system would detect a forgery and take an action. All this because the machine knows the rule of thumb : No two mac addresses on earth can be the same.

If two machines are coming up with a same MAC , then one of them is lying.

Once this is confirmed then any number and sequence of steps can be taken to identify the lying machine and forcing it to either correct , or disconnecting it from the network. But all this only happened when a message destined for the 1.5 machine came up. Had that not being the case , the machine 1.5 would still keep on receiving information destined for 1.3

Mac Spoofing

The above is a case of Mac spoofing. In which a user steals a mac from a network. The user then escapes from the hand of mac filtering that is applied at some networks. The mac filters maintains a list of mac addresses that would be allowed access to the network. If I were able to spoof on the network through some means and catch a mac , I could illegally enter the network as well by using one of the allowed macs that I caught.

Well What About IP?

IP is a logical addressing scheme. It takes to us from networks to networks. When it reaches the destination network, that network has the EXACT physical address of the machine . So the packets are deliverd then.

Supposedly a machine in USA wants to send a packet to a machine in Pakistan. Now it would have been real ugly to maintin a huge huge list of MAC addresses somewhere. Hence when www.yahoo.com sends a packet to a PC in pakistan, it just has an IP address. When the IP address reaches the network in which the user exists , that network has the exact physical address of the machine mapped with that yahoo was using. Thats how the packet would reach to the exact machine.

IP system is a hiearhical system. An IP address is a logical construct, while a MAC address is a random construct.

If www.yahoo.com would try to use a mac directly , it wont be able too because the MAC address has just gibberish. It doesn't say anything. It was not made for this purpose too. However an IP address, has much to say. IP classes , subnets , and the fact that gateways and routers understand them ; is the reason why www.yahoo.com would use the IP address for finding the client.

Its just like a phone number has logical constructions at times , the first digits for the country , the second for city and the rest for the suburb etc. But comparitively the CNIC number has no such locale information.