Sunday, 27 December 2015

When to use SOAP instead of REST

With SOAP you have a contract between the two parties.
With REST you'll have to implement such contract yourself in your code.
For me SOAP is like a strongly typed language. REST is like PHP : quick to get something going.
As for performance related to the size of the message that needs to be transported: People often assume that with SOAP huge amounts of very verbose XML needs to be transported. Technically this is true but in modern days the two endpoints will most likely use gzip compression and/or FastInfoset. This greatly reduces the size of the message, possibly to the size of compressed JSON. However some people argue that JSON is still somewhat faster to parse than is XML. This is possibly true but I believe the difference in parsing speed for most use cases is negligible. I've also seen tests where FastInfoset parsing outperforms JSON parsing. All in all arguments need to be reviewed in the light of the current state of affairs, not the way the world looked in 2005.
I recently had to implement a web service where the request could become very large (several megabytes) and the reply even bigger. This works well with SOAP. Contrary with REST the conceptual idea is that you embed the request as part of URL and such approach of course only works for very small amount of request data. REST camp will say that you have two choices: (1) You embed your large data in a the body of a POST request but this is not really a 'true' REST way of doing things or you (2) change your design so that you send many questions rather than a single big question but such solution will of course create a lot more network overhead because of the roundtrip.
I stayed with SOAP for this particular service.
REST is fine and possibly the optimal choice for most scenarios but there are certainly cases where SOAP is a better fit, IMHO.



One of the major benefits of SOAP is that you have a WSDL service description. You can pretty much discover the service automatically and generate a useable client proxy from that service description (generate the service calls, the necessary data types for the methods and so forth). Note that with version 2.0, WSDL supports all HTTP verbs and can be used to document RESTful services as well, but there is a less verbose alternative in WADL (Web Application Description Language) for that purpose.
With RESTful services, message security is provided by the transport protocol (HTTPS), and is point-to-point only. It doesn’t have a standard messaging system and expects clients to deal with communication failures by retrying. SOAP has successful/retry logic built in and provides end-to-end reliability even through SOAP intermediaries.
One of the major benefits of RESTful API is that it is flexible for data representation, for example you could serialize your data in either XML or JSON format. RESTful APIs are cleaner or easier to understand because they add an element of using standardised URIs and gives importance to HTTP verb used (i.e. GET, POST, PUT and DELETE).
RESTful services are also lightweight, that is they don’t have a lot of extra xml markup. To invoke RESTful API all you need is a browser or HTTP stack and pretty much every device or machine connected to a network has that.

Tuesday, 22 September 2015

Find Longest common Sub-sequence in two strings in O(n) time


public class DebugTest {
public static void main(String[] args) {
char X[] = "AGGTAB".toCharArray();
char Y[] = "GXTXAYB".toCharArray();
System.out.println(findLCS_dp1(X, Y));
X = "XMJYAUZ".toCharArray();
Y = "MZJAWXU".toCharArray();
System.out.println(findLCS_dp1(X, Y));
}
public static int findLCS_dp1(char[] a, char[] b){
int m = b.length;
int n= a.length;
int[] lcs = new int[n+1];
for(int i=1;i<=n;i++){
int prevMatchedValueAtIndexJ = lcs[0];
for(int j=1; j<=m; j++){
int temp = lcs[j] ;
if(a[i-1] == b[j-1])
lcs[j] = 1 + prevMatchedValueAtIndexJ;
else
lcs[j] = Math.max(lcs[j-1], lcs[j]);
prevMatchedValueAtIndexJ = temp;
}
}
return lcs[m];
}
}

Saturday, 1 November 2014

Transpose, Rotate by +90, Rotate by -90 a matrix.

#include <stdio.h>
#include <stdlib.h>

void displayMatrix(unsigned int const *p, unsigned int row, unsigned int col);
void rotate(unsigned int *pS, unsigned int *pD, unsigned int row, unsigned int col);

int main()
{
    // declarations
    unsigned int image[][4] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}};
    unsigned int *pSource;
    unsigned int *pDestination;
    unsigned int m, n;

    // setting initial values and memory allocation
    m = 3, n = 4, pSource = (unsigned int *)image;
    pDestination = (unsigned int *)malloc(sizeof(int)*m*n);

    // process each buffer
    displayMatrix(pSource, m, n);

    rotate(pSource, pDestination, m, n);

    displayMatrix(pDestination, n, m);

    free(pDestination);

    getchar();
    return 0;
}

void displayMatrix(unsigned int const *p, unsigned int r, unsigned int c)
{
    unsigned int row, col;
    printf("\n\n");

    for(row = 0; row < r; row++)
    {
        for(col = 0; col < c; col++)
        {
            printf("%d\t", *(p + row * c + col));
        }
        printf("\n");
    }

    printf("\n\n");
}

void rotate(unsigned int *pS, unsigned int *pD, unsigned int row, unsigned int col)
{
    unsigned int r, c;
    for(r = 0; r < row; r++)
    {
        for(c = 0; c < col; c++)
        {
            //*(pD + (col-c-1)*row + r) = *(pS + r * col + c);    //rotate by -90
     
          // *(pD + c*row+ (row-r-1)) = *(pS + r * col + c);   //rotate by +90
       
          *(pD + c*row+ r) = *(pS + r * col + c);                  //transpose
        }
    }
}

Friday, 24 October 2014

Minimum no. of comparisons required for finding 2nd minimum element

second smallest of n elements can be found with n + logn -2 in worst case..
Lets check out how?

See the pair-wise comparison below

1  2  3  4  5  6  7  8
 \/    \/    \/    \/
 1      3    5      7
   \  /        \  /
     1          5
        \   /
          1

1 is the smallest, it took n-1 = 7 comparisons. Now compare all the numbers which 1 was compared to (compare 2,3,5).

2  3   5
 \/   /
  2  /
   \/
   2

2 is the second smallest. It took lg(n)-1 = 2 comparisons.
So total is (n-1)+(logn-1) = n+logn-2 comparisons.

Wednesday, 22 October 2014

Why manhole cover are round

  • A round manhole cover cannot fall through its circular opening, whereas a square manhole cover could fall in if it were inserted diagonally in the hole.
  • Circular covers don’t need to be rotated or precisely aligned when placing them on the opening.
  • A round manhole cover is easily moved and rolled.
  • Human beings have a roughly circular cross-section.
  • Round tubes are the strongest shape against the compression of the earth around them, so the cover of the tube would naturally be round as well.
  • It’s easier to dig a circular hole.
  • Round castings are much easier to manufacture using a lathe.

Monday, 20 October 2014

Thread vs Process

Processes are the abstraction of running programs: A binary image, virtualized memory, various kernel resources, an associated security context, and so on. Threadsare the unit of execution in a process: A virtualized processor, a stack, and program state. Put another way, processes are running binaries and threads are the smallest unit of execution schedulable by an operating system's process scheduler.

A process contains one or more threads. In single-threaded processes, the process contains one thread. You can say the thread is the process—there is one thing going on. In multithreaded processes, the process contains more than one thread—there's more than one thing going on.

The two primary virtualized abstractions in modern operating systems are virtualized memory and a virtualized processor. Both afford the illusion to running processes that they alone consume the machine's resources. Virtualized memory gives processes a unique view of memory that seamlessly maps back to physical RAM or on-disk storage (swap space). A virtualized processor lets processes act as if they alone run on a processor, when in fact multiple processes are multitasking across multiple processors.

Virtualized memory is associated with the process and not the thread. Thus, threads share one memory address space. Conversely, a distinct virtualized processor is associated with each thread. Each thread is an independent schedulable entity.

What's the point? We obviously need processes. But why introduce the separate concept of a thread and allow multithreaded processes? There are four primary benefits to multithreading:

  • Programming abstraction. Dividing up work and assigning each division to a unit of execution (a thread) is a natural approach to many problems. Programming patterns that utilize this approach include the reactorthread-per-connection, and thread pool patterns. Some, however, view threads as an anti-pattern. The inimitable Alan Cox summed this up well with the quote, "threads are for people who can't program state machines."
  • Parallelism. In machines with multiple processors, threads provide an efficient way to achieve true parallelism. As each thread receives its own virtualized processor and is an independently-schedulable entity, multiple threads may run on multiple processors at the same time, improving a system's throughput. To the extent that threads are used to achieve parallelism—that is, there are no more threads than processors—the "threads are for people who can't program state machines" quote does not apply.
  • Blocking I/O. Without threads, blocking I/O halts the whole process. This can be detrimental to both throughput and latency. In a multithreaded process, individual threads may block, waiting on I/O, while other threads make forward progress. Asynchronous & non-blocking I/O are alternative solutions to threads for this issue.
  • Memory savings. Threads provide an efficient way to share memory yet utilize multiple units of execution. In this manner they are an alternative to multiple processes.

The cost of these benefits of threading are increased complexity in the form of needing to manage concurrency through mechanisms such as mutexes and condition variables. Given the growing trend toward processors sporting multiple cores and systems sporting multiple processors, threading is only going to become a more important tool in system programming.