Sunday, 22 July 2012

Money Markets

Money

Money is the current medium of exchange. I have seen that often people get confused with money. The money that is in our bank accounts is not real money. Money that is on account of the Central Bank of a country is the Real Money.  All other forms for example, the account balances with the commercial banks, even cash are promises to pay money, but not real money. Like individuals, banks and larger institutions also transact money amongst each other. In these transactions cash is not involved, but real money kept in accounts with the Central Bank of a country is involved.

Money Markets

Money market provides short term finance(for a period less than 1 year). The parties involved in Money Markets are Central Banks, Commercial Banks, FIs, Mutual Funds and Primary Dealers. One of the main differences between money markets and stock markets is that most money market securities trade in very high volume thus limiting accessing individual investors. The easiest way for an individual to access money market is through money market mutual funds. However, some money market instruments like Treasury bills may be purchased directly. Below we will have a look at major money market instruments:

Treasury Bills(T-Bills)

T-Bills are the most liquid money market securities. T-Bills are a way for the US government to raise money from the public. I am refering to the T-Bills issued by the US government, but many governments issue T-Bills in a similar fashion. Treasury Bills are issued through a competitive bidding process. The biggest reason that the T-Bills are so popular is that they one of the few money market instruments that are affordable by individual investors. Another important reason for their popularity is that they are considered to be the safest investment in the world because they are backed by US government. But this safety comes at a cost. They have very low returns. And this is the basic rule in finance: The higher the risk, the higher the return.

Certificate of Deposit

A certificate of deposit is a promissory note issued by a bank. It is a time deposit that restricts holders from withdrawing funds on demand. CDs are similar to saving accounts in that they are insured and hence virtually risk-free. They are different from saving accounts in that CDs have a specific and fixed term(often 1 month, 3 months, 6 months, 1 year). CDs generally give higher rate of return than Bank term deposit.

Commercial Paper

An unsecured, short-term debt instrument issued by a corporation, typically for the financing of accounts receivable, inventories and meeting short-term liabilities. Maturities on commercial paper rarely range any longer than 270 days. Commercial papers are not backed by collateral. Since these are not backed by collateral, only firms with high credit ratings from a recognized rating agency would be able to sell its commercials papers at a reasonable price.

Banker's Acceptance

BA is a promised future payment which is guaranteed by a bank and drawn on a deposit at a bank. A BA specifies the amount of money, date and the person to which the payment is due. Now the holder of the draft can sell it for cash to a buyer who is willing to wait until the matutity date of the funds in the deposit. BAs make the transaction between 2 parties who do not know each other to be more safe because they allow parties to substitute the banks's creditworthiness for that who owes the payment.

Eurodollars

Eurodollars are US dollar denominated deposits at banks outside United States and are thus not under the jurisdiction of Federal Reserve. These are called Eurodollars because most of the initially most of the US dollar reserves outside the United States were in Europe. Eurodollar market is relatively free of regulations and hence banks can operate at lower margins than their counterparts in United States.

Repo

A repurchase(repo) agreement can be seen as a short term swap between cash and securities. If a security holder wants to maintain his long-term position but needs cash for a short term period, he or she can enter into a repo contract whereby the securities are sold together with a binding agreement to repurchase them at a future date.. The effect is to provide the security holder with a short-term loan based on the collateral of the government securities he or she owns.

Friday, 1 June 2012

GC overhead limit exceeded error




Recently I was struggling with a very unusual error in one of the batches in production environment. The error read like:
Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded

Here is the snapshot of the error when I ran it through command prompt:

Explored on this error and in this post I would like to highlight my findings:

This message means that for some reason the garbage collector is taking an excessive amount of time (by default 98% of all CPU time of the process) and recovers very little memory in each run (by default 2% of the heap). This effectively means that your program stops doing any progress and is busy running only the garbage collection at all time. To prevent your application from soaking up CPU time without getting anything done, the JVM throws this Error so that you have a chance of diagnosing the problem.
The rare cases where I've seen this happen is where some code was creating tons of temporary objects and tons of weakly-referenced objects in an already very memory-constrained environment. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. You can turn this off with the command line option -XX:-UseGCOverheadLimit
In my case the data was huge. We had deployed a batch in production which was implemented using stateful framework. But it had to be changed to the stateless code which took around a month. During that time that batch didn’t process any records. So the records had piled up which needs to be processed. When we deployed the stateless code, it gave this error. When I was running this batch process, I had allocated maximum of 1 GB memory to it. Then I removed this limit. Even then it gave this error. So, I had to turn off this feature to get rid of it by the command line option I had mentioned above.

Now the obvious question that comes to the mind is that what happens to the Java process in case of OutOfMemoryError.
And OutOfMemoryError is handled like any other exception:
·         If it is caught, then nothing more happens.
·         If it is not caught, then either the threads or the threads groups uncaught exception handler handles it. This pretty much always leads to the thread being stopped.
However there are two factors that are not really there in other exceptions:
·         OutOfMemoryError is an Error and not an Exception. This means that it's very unlikely to be caught anywhere: You should not try to catch an Error generally (with very few exceptions) and it's not usually done, so the chances of it being handled are rather low.
·         When an OutOfMemoryError happens and no object become eligible for GC because of that, then you'll still have little memory left and chances are that you'll run into the exact same problem again later on.
And if the thread this happens to is the only non-daemon thread (often, but not necessarily, that's the main thread, that executes the main method), then that thread getting killed results in the whole JVM shutting down (which is often perceived as "a crash").
So it will probably kill the thread, and if the memory-issue is not solved, then this can happen to more and more threads.

OutOfMemoryError should be considered unrecoverable and the behavior of the JVM after such an error has been raised is undefined, so there is no point in expending effort to handle it. Any operations done after this exception is thrown by the JVM will have undefined behavior. They may execute, but more likely they will just cause another error to be thrown.

Saturday, 26 May 2012

Mounting partitions in Linux through command line

In this post, I would add a partition in Linux through command line. Your first task should be to know which partitions are already mounted on your system and where they are mounted. So, run the following command which gives you this information:
$ sudo mount


If the partition which you wish to mount is shown, you can navigate to its mount directory. Lets say the mount directory of the partition you wish to mount is /mnt/partition1, then run the following command:
$ cd /mnt/partition1
And you be able to access its file system.

But if the partition you wish to mount is not shown by the command "sudo mount", you will have to mount it first. So, you would like to know the device identifier for the partition. The following command would help to do that:
$ sudo fdisk -l
it is a lowercase L. The identifier will look something like
/dev/sda1
Now you have to create a mount point(you can give any path for it). A mount point is a directory (typically an empty one) in the currently accessible filesystem on which an additional filesystem is mounted (i.e., logically attached). The mount point becomes the root directory of the newly added filesystem, and that filesystem becomes accessible from that directory.
$ sudo mkdir /mnt/ankitpartition
I used the path /mnt/ankitpartition. You can use some other path.

Since you probably want it to be mounted all the time we’ll skip the mount command and go right into the fstab i.e. we would make this mount point default. The default mount points are the directories in which file systems will be mounted automatically when the computer is booted. Default mount points are listed in the file /etc/fstab.
So now we would make this partition default. First open fstab file in a text editor:
$ sudo nano /etc/fstab
You can use any other text editor, but I like nano.
Within the fstab you have to add a line which tells Linux to mount the partition. There should already be some entries which will give you a general guideline about how the line has to look like. Some examples:
mounting a FAT32 partition
/dev/sda2 /mnt/mypartition vfat umask=000,defaults 0 0
mounting a NTFS partition
/dev/sda2 /mnt/mypartition ntfs umask=000,defaults 0 0
To quit nano simply press ctrl + x. It will then ask you if you want to save the changes, press Y, and if you want to save it into the same fstab file, press Enter

And the last step would be:
$ sudo mount -a

Saturday, 28 April 2012

Linux Kernel Mode


There are 2 modes in Linux: Kernel mode and User mode. Kernel mode is at a higher privilege level than user mode. All user programs and the applications running on the machine run in user mode. Only the kernel executes in kernel mode. A program executing in user mode can’t access kernel code, so can’t directly call system calls. This is done for security purposes because if a user program can access the kernel code, he can change it or access the memory which he should not access. So, the kernel assigns itself the highest privilege level: kernel mode. User processes are at the least privilege level: user mode. The kernel is protected by hardware, because programs executed in user mode can’t access the memory that belongs to programs executed in kernel mode.

This protection by hardware has a problem. User processes can’t access any feature provided by the kernel. In other words, user processes can’t make use of the system calls provided by the kernel. Again to cope up with this problem we go take help from the hardware. The only possible way to use system calls is to escalate the privilege level of the user process. So, we make use of interrupts, in this case software interrupt. A software interrupt can be seen as a special jump instruction whose target address is restricted by the kernel. The kernel sets the target address of the software instruction to the special routine that handles the system calls. Now suppose the user wants to use a system call. First of all what is done is that the code corresponding to the system call is put in a register for the kernel to understand which system call the user wants to call. The task of setting the system call code is done by the library procedure and is hidden from the user. After setting the code for the specific system call, a trap to the kernel takes place. Then the dispatcher in the kernel calls the specific system call using the code set in the register. Then a context switch takes place in which it saves the content of the registers of the user program. Then finally the control passes to the kernel procedure which performs its task.

But there is another side of the story. The system call by this hardware approach can become very slow because the software interrupt and the context switch, which takes place in the kernel require heavy and complex operations. This can be gauged by seeing that a system call is on an average about 30 times slower than a simple function call.

So the next question which comes to mind is how to accelerate system call? The obvious way to do this is to execute the user process in kernel mode. Then no software interrupt and context switch is needed. System calls would be just like normal function calls because the user process can access the kernel directly. But this is not as easy as it sounds. There are a lot of issues with this approach, foremost of which is security.

Sunday, 8 April 2012

SOAP protocol

SOAP is a protocol for accessing a Web Service. SOAP is a simple XML-based protocol to let applications exchange information over HTTP. SOAP is designed to be a new protocol for the decentralized, distributed environment, which utilises the power of the Internet and XML to pass typed information between nodes. Originally, SOAP stood for Simple Object Access Protocol, but was later changed simply to SOAP with version 1.2, because it did not directly use Objects. SOAP is a light weight protocol that is platform independent, transport independent and operating system independent.



There are two types of SOAP requests. The first is the Remote Procedure Call (RPC) style request similar to other distributed architectures. This is usually synchronous; the client sends a message and waits to get a response or fault message back from the server. The second type of SOAP request is the document request. In this case, a full XML document is passed to/from the client and server, in side a SOAP message.

RPC

SOAP-RPC is an implementation of a Remote Procedure Call (RPC). In this case, a function on a remote machine is called as if it were a local function. All of the marshalling and unmarshalling of data is handled by SOAP and is performed in XML. RPC-style web services are tightly coupled and interface-driven. The clients invoke the web service by sending parameters and receiving return values. RPC-style web services follow call/response semantics; therefore, they are usually synchronous, which means that the client sends the request and waits for the response until the request is processed completely.


Document

With a document style message the client and/or server passes an XML document as the body of the SOAP message instead of parameters. An example of this is an invoice. The document is marked-up with both XML and a schema, which is common to both the sender and receiver. The sender is the consumer, which makes a function call to the web service with some parameters, and in return the vendor sends back, not data results, but an XML document that contains all of the information that a normal invoice would have, the difference being that it is marked-up with XML, and is machine-readable. Document style messaging has other advantages over a remote procedure call, which is meant to be relatively static, and any changes to the RPC interface would break the contract between the service and the application. Changing the RPC description would cause all of the applications that rely on a specific method signature of SOAP-RPC to break. Good design dictates that the method signature of an RPC message service should never change. With document messaging, the rules are less rigid and many enhancements and changes can be made to the XML schema without breaking the calling application, because what is sent is an XML document rather than a structured return value. Web service applications should be able to use a guaranteed delivery mechanism to improve its reliability, scalability, and performance. Since a document message is usually a self contained XML file, it is better suited for asynchronous processing and can be placed directly into the queue. The reliability of the application is improved because the message queue guarantees the delivery of the message even if the target application is not currently active, performance is improved because the web application simply delivers the document to a queue and is then free to perform other tasks, and scalability is improved because the document is offloaded to one or more instances of an application that handles its processing.

Applications of SOAP

  • Business to Business integration : SOAP allows businesses to develop their applications, and then make those applications available to other companies.
  • Distributed applications : Programs like databases could be stored on one server and accessed and managed by clients across the Internet.
One thing when we think of going for SOAP on our business server is that there are many other ways to do the same thing that SOAP does. But the most important advantage you would get by going for SOAP is that its not constrained by application language(Java, C#, C++, Perl or any other language) or the platform (Windows, Unix, Mac), and this makes it much more versatile than other solutions.


Lets go little deep into SOAP. As we know SOAP does not use objects. To pass anything besides the basic data types in Java to the web service, you must write your own Serialize and Deserialize functions. These are functions written that convert a class or object into XML and back. So it is true that SOAP does not pass objects, but instead passes representations of the data in the objects, so that it can be used to create new objects. Apache SOAP comes with a built-in serialization class called BeanSerializer. This class can take a Java Bean and automatically serialize and deserialize it.


Saturday, 7 April 2012

Artificial Neural Networks

Artificial neural networks are Artificial Intelligence models that try to mimic the brain in the way it stores knowledge and processing information. Artificial Neural Networks which are commonly known as Neural Networks have been motivated from its inception by the recognition that the human brain computes in an entirely different way from the conventional digital computers. The first wave of interest in neural networks emerged after the introduction of simplified neurons by McCulloch and Pith in 1943. These neurons were presented as models of biological neurons that could perform computational tasks.

A Neural Network consists of a pool of simple processing units which communicate by sending signals to each other over a large number of weighted connections. The idea is to create a mathematical function to mimic a neural communication. This can be achieved by the following points:
  • Represent a neuron as a boolean function.
  • Each neuron can have an output capacity of either 1 or 0.
  • Each neuron also has a set of inputs (either 0 or 1), with as associated weight.
  • The neuron can compute a weighted sum over all the input and compare it to some threshold t.
  • If the sum is greater than t, then output 1 else output 0.
This is how we solve a problem by neural networks. In some cases we may require more than 1 neurons to come up with a boolean function, which is mostly the case. To come up with a good function is a tedious task. This single neuron which I am talking about is called a "perceptron" in Neural Network terminology.

Perceptron: 
A perceptron is a simulated neuron that takes the agent's percepts (eg. feature vectors) as input and maps them to the appropriate output value.

percept.jpg 

This can be represented in an equation form as follows:
w1 *  x1 + w2 * x2 + ........  + wn * xn >= t

Perceptron Learning:
Now the most important question which should be haunting you by now. How does the perceptron learn ? Well, a perceptron learns by adjusting its weights in order to minimize the error on the training set. To start off, consider updating the value for a single weight on a single example x with the perceptron learning rule:
wi = wi + error
error = a * ( true value - output) * xi
where a is the learning rate having value from 0 to 1.

Now that we can update a single value on one example, we want to update all weights so that we minimize error on the whole training set. Now this is really an optimization search in weight space, which is the hypothesis space for perceptrons.

Now the question is how do we begin ? Its simple, just initialize all the weights to small random values. Now we train our neural network by supplying input values to it and also giving it the expected output values to adjust its weights. The perceptron training rule allows us to move to the point in weight space that minimizes the error.

This a very brief introduction to neural networks for those who want to get an insight into Neural Networks. Buts there is a lot more to explore and a lot more complexity involved.

Tuesday, 27 March 2012

Network Worm Detection


Worms are self propagating programs that spread by exploiting a latent software vulnerability in some popular network service- such as email, web or terminal access. A computer worm is a malware program that spreads to other computers by replicating itself. Most of the worms are designed to spread and not to affect the systems they pass through. Worms are mostly used for spamming purposes. A very common use of worms is to create zombie computer under the control of the worm author. Such computers are used by spam senders for sending junk email or to cloak their website's address.

I will describe a algorithm to detect such an attack. The basic approach of detection, characterization and containment has not changed over the years. First of all, new worms are detected by intrusion detection systems. Then, after isolating an instance of the worm, skilled security professionals manually characterize a worm signature and finally,this signature is used to contain subsequent infections via updates to anti-virus software. But this approach is insufficient. It requires isolating a new worm and then a skilled professional works on it to decode the sequence, looks for invariant code sequences and then tests the signatures  for uniqueness. But recent reports have shown that effective worm containment can require a reaction time of under 1 minute.

First observation about worms is that some portion of the content in existing worm is invariant. It is typically the code containing the latent host vulnerability. Second observation is that the spreading dynamics of a worm is atypical of Internet applications. Network worms tend to behave quite differently from the popular client-server and peer-to-peer applications deployed on today's networks.

These key behaviours can be exploited to detect and characterize network worms. In all existing worms, some of the program is invariant across every host it infects. Some worms make use of limited polymorphism by encrypting each worm instance independently and /or randomising filler text. In these cases, much of the worm body is variable, but key portions are still invariant(eg. the decryption routine). From these observations, we can conclude that network worms must generate significant traffic to spread and that this traffic will contain common sub string and that this traffic will be directed between a variety of network hosts.


In principle, detecting this traffic pattern is relatively straightforward. For each network packet, the content is extracted and all substrings processed. Each substring is indexed into a prevalence table that increments a count for a given substring each time it is  found. In effect, this table implements a histogram of all observed substrings. To maintain a count of unique source and destination  addresses, each table entry also maintains two lists, containing IP addresses, that are searched and potentially updated each time a  substring count is incremented. Sorting this table on the substring count and the size of the address lists will produce the set of likely  worm traffi c. Better still, the table entries meeting this worm behavior criteria are exactly those containing the invariant substrings of the worm. It is these sub- strings that can be used as signatures to alter the worm out of legitimate network traffic. Network content which is not prevalent or not widely dispersed is sifted out, leaving out the worm content.

This is a very high level view of the algorithm for worm detection which does not scale well.  But this can be a good starting point for understanding the practical worm detection algorithm.