Saturday, 30 April 2016

How to implement Merge sort ?


Merge sort - O(n log n)
  • Divide and Conquer
    • Divide into 2 parts
      • Divide each part into 2 sub-parts recursively
    • Merge parts in reverse order

  • Example
    • Divide array of 8 numbers to 2 sub arrays
    • Divide each subarray again into 2 (4 sub arrays)
    • Divide each subarray again into 2 (8 sub arrays)
    • Merge into 4 subarrays
    • Merge into 2 subarrays
    • Merge into 1 array


27 10 12 25 34 16 15 31
27  10  12   25   | 34   16  15  31
27  10 | 12   25   | 34   16  | 15  31

-------------------------------------------------------
27 | 10 | 12 | 25 | 34 | 16 | 15 | 31
-------------------------------------------------------
10 27 | 12 25 | 16 34 | 15 31
10 12 27 25 | 15 16 31 34
10 12 15 16 25 27 31 34

is it possible to open multiple PuTTY sessions in a same window ?


use Multi tab PuTTY

  • It can open multiple tabs of PuTTY to work on multiple platform in same window
  • allows to save login / password apart from hostname so you do not have them manually
  • You will get all the saved session on Home page and side menu.


Download link

What are the usage of PuTTY tool ?


Functions provided by PuTTY

  • Save hosts and preferences for reuse
  • Command-line SCP and SFTP clients, called "pscp" and "psftp" respectively.
  • Port forwarding with SSH (Local / remote / dynamic port forwarding)
  • IPv6 support
  • Public-key authentication support (no certificate support)
  • Supports 3DES, AES, Arcfour, Blowfish, DES
  • Support for local serial port connections
  • No installation required


Friday, 29 April 2016

What is Insertion sort and how it works ?


Insertion sort - Complexity O(n^2)
  • Insert the element at right place in the left part (for one index per pass)
  • Repeat from index 1 to n-1
    • Compare element with all its previous items until we receive a lesser value
      • Swap if current element is less than previous one
Java code
// Loop from 1 to n-1
for (int i=1; i ‹ array.length; i++) {
   int element = array[i];
   // Loop through previous elements till first element or lower item found
   int j = i;
   while (j > 0 && array[j-1] > element) {
        array[j] = array[j-1];   // Swap - first part
        j--;
   }
   array[j] = element;   // Swap - second part
}

Example
29, 20, 73, 34, 30 
20, 29, 73, 34, 30 
20, 29, 73, 34, 30 
20, 29, 34, 73, 30 
20, 29, 
30, 34, 73

Highlighted are swapped during each pass

How to implement different Sorting algorithms ?


Sorting Algorithms

Bubble sort O(n^2)
  • Bubble up the minimum values during each pass
  • Repeat below steps n times
    • Compare each element with its next item till end (inner loop)
      • Swap, if X th element is greater than X+1 th element
          
Selection sort O(n^2)
  • Divide array into 2 parts = Sorted and Unsorted
  • Select the minimum from unsorted for swap
  • Repeat below steps n-1 times
    • Select the minimum element from unsorted part with element  (inner loop)
    • Swap it with element at (last index - 1) of sorted array  

                
  

Insertion sort - O(n^2)
  • Insert the element at right place in the left part (for one index per pass)
  • Repeat from index 1 to n-1
    • Compare element with all its previous items until we receive a lesser value
      • Swap if current element is less than previous one
          
Merge sort - O(n log n)
  • Divide and Conquer
    • Divide into 2 subarrays
    • Sort each one
    • Merge them into one
  • Example
    • Divide array of 8 numbers to 2 sub arrays
    • Divide each subarray again into 2 (4 sub arrays)
    • Divide each subarray again into 2 (8 sub arrays)
    • Merge into 4 subarrays
    • Merge into 2 subarrays
    • Merge into 1 array
     Merge-sort-example-300px.gif

How to implement Selection sort ?


Selection sort - Complexity O(n^2)

Algorithm

  • Repeat below steps n-1 times (from back side)
    • Find min in unsorted sub-array
      • If found, swap with current element with min element

Java code

int i, j, minIdx, temp;

// n-1 passes (from back side)

for ( i = array.length - 1; i > 0; i - - )  {

    minIdx = 0;   // Assume first element is min
    
// Locate smallest element between positions 1 and i

    for(j = 1; j <= i; j ++) {

           if( array[ j ] < arrayminIdx ] )

              minIdx= j;   
    }

    // Swap smallest found with element in position i

    temp = arrayminIdx ];

    arrayminIdx ] = array[ i ];

    array[ i ] = temp; 

}


Execution during all n-1 passes

84  69  76  86  94  91



84  69  76  86  94  91

84  91  76  86  94  69

84  91  76  86  94  69
84  91  94  86  76  69

84  91  94  86  76  69
86  91  94  84  76  69

86  91  94  84  76  69
86  91  94  84  76  69


94  91  86  84  76  69
94  91  86  84  76  69

94  91  86  84  76  69

ORANGE highlight indicates unsorted array to find min element.
BLUE highlight indicates sorted array (having items arranged)
YELLOW highlight indicates swapping items.

Thursday, 28 April 2016

What is the use of telnet command ?


telnet command is used to check if a port is open in your network.

telnet [Domain_name or IP] [Port]

Example
telnet myapp-beta-final.com 80


In Windows : If a  blank screen  appears without an error message, means connection is successful, Otherwise not.

If telnet service is not available, enable it :

  • Go to Control panel > Programs > Turn Windows features on or off
  • Enable Telnet Client
  • Click OK


In Linux : You will get status Connected. You can exit by pressing Ctrl + ]
Trying 10.106.200.116...
Connected to myapp-beta-final.com.

Escape character is '^]'.

What are different types of keys in SSL ?


1. PRIVATE KEY
  • contains the identity information of the server, along with a key value
  • must be safe and password protected, as it is used in handshaking. 


2. PUBLIC KEY (Public certificates)
  • tightly associated to the private key
  • created from the private key using CSR (Certificate Signing Request)
    • After creating a private key, you create a CSR, which is sent to your Certificate Authority (CA)
    • The CA returns a signed certificate, which has information about the server identity and about CA.


3. ROOT CERTIFICATES
  • CA Certificate which is simply a Self-signed Certificate
  • represents an entity which issues certificate (Certificate Authority or CA)

How to configure to use SSL certificate through Apache Axis ?


Axis Configuration for SSL

Set a Socket Secure Factory, at application startup

  AxisProperties.setProperty(
       "axis.socketSecureFactory",
       "com.genius.utils.CustomSSFactory");


Create Socket Secure Factory class

1. Import following APIs :
import java.security.KeyStore;
import java.security.cert.X509Certificate;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import org.apache.axis.components.net.JSSESocketFactory;
import org.apache.axis.components.net.SecureSocketFactory;


2.   Create class by extending JSSESocketFactory and implementing SecureSocketFactory
public class CustomSSLFactory extends JSSESocketFactory
        implements SecureSocketFactory

3.  Override a parameterized constructor, to set attributes :
public CustomSSLFactory(Hashtable attributes) {
        super(attributes);
}

4.  Override method initFactory to set sslFactory :
protected void initFactory() throws IOException {
        try {
               SSLContext context = getContext();
               sslFactory = context.getSocketFactory();
        } catch (Exception e) {
               e.printStackTrace();
        }
}
  

5.  Override method getContext to return the SSL context :
protected SSLContext getContext() throws Exception {
   . . . . .
}
              
 

Details of getContext method

Use 2 constants for keystore location and password :
private static String MY_KEYSTORE_PASSWORD = "passwd";
private static String RESOURCE_PATH_TO_KEYSTORE = "/usr/bin/certificate.P12";


Check if password is in correct format :
char[] keystorepass = MY_KEYSTORE_PASSWORD.toCharArray();

if (StringUtils.isBlank(new String(keystorepass))) {
    throw new Exception("Could not read password for configured keystore!");
}


Load the keystore :
KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(new FileInputStream(new File(RESOURCE_PATH_TO_KEYSTORE)),
                     MY_KEYSTORE_PASSWORD.toCharArray());


Check intialization of key manager factory :
KeyStore keyStore = ks;
KeyManagerFactory kmf = KeyManagerFactory.getInstance(
                    KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, keystorepass);


Check initialization of Trust manager factory :
TrustManagerFactory tmf =  TrustManagerFactory.getInstance(
                             TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);


Initialize the X509 Trust manager :
X509TrustManager tm = new X509TrustManager() {
  public X509Certificate[] getAcceptedIssuers() {
               return null;
  }

  public void checkClientTrusted(X509Certificate[] certs, String authType) {
  }

  public void checkServerTrusted(X509Certificate[] certs, String authType) {
  }
};


Initialize Key Manager Factory and Key managers
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
                               KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(keyStore, keystorepass != null ? keystorepass : null);
KeyManager[] keymanagers = kmfactory.getKeyManagers();



Initialize SSL context with Key managers and Trust managers (X509)
sslContext.init(keymanagers, new TrustManager[]{tm}, null);


Return the SSL context

return sslContext;

How to do Bubble sort in Java ?



Bubble sort - Complexity O(n^2)

Algorithm
  • Repeat below steps n times
    • Compare array[0] & array[1]
      • If array[0] > array [1] swap it
    • Compare array[1] & array[2]
      • If array[1] > array[2] swap it
    • ....



Java code
int n = array.length;
int temp = 0;


for (int i=0; i < n; i++){   // n passes
   for (int j=1; j < (n-i); j++){
         if (array[j-1] > array[j]){
              // swap
              temp = array[j-1];
              array[j-1] = array[j];
              array[j] = temp;
         }
   }

}

Complexity : O(n2)


Execution during all n passes
4, 2, 9, 6, 23, 12, 34,  0,  1


2, 4, 6, 9, 12, 23, 0, 1, 34, 2, 4, 6, 9, 12, 0, 1, 23, 34, 2, 4, 6, 9, 0, 1, 12, 23, 34, 2, 4, 6, 0, 1, 9, 12, 23, 34, 2, 4, 0, 1, 6, 9, 12, 23, 34, 2, 0, 1, 4, 6, 9, 12, 23, 34, 0, 1, 2, 4, 6, 9, 12, 23, 34, 0, 1, 2, 4, 6, 9, 12, 23, 34, 0, 1, 2, 4, 6, 9, 12, 23, 34, 0, 1, 2, 4, 6, 9, 12, 23, 34, - See more at: http://www.java2novice.com/java-interview-programs/bubble-sort/#sthash.DV55ntRH.dpuf
2, 4, 6, 9, 12, 23,  0,  1, 34
2, 4, 6, 9, 12,  0,  1, 23, 34
2, 4, 6, 9,  0,  1, 12, 23, 34
2, 4, 6, 0,  1,  9, 12, 23, 34
2, 4, 0, 1,  6,  9, 12, 23, 34
2, 0, 1, 4,  6,  9, 12, 23, 34
0, 1, 2, 4,  6,  9, 12, 23, 34
0, 1, 2, 4,  6,  9, 12, 23, 34
0, 1, 2, 4,  6,  9, 12, 23, 34
0, 1, 2, 4,  6,  9, 12, 23, 34

Highlighted are swapped during each pass.


4, 2, 9, 6, 23, 12, 34, 0, 1
4, 2, 9, 6, 23, 12, 34, 0, 1