Showing posts with label One post a day keeps the coronavirus away. Show all posts
Showing posts with label One post a day keeps the coronavirus away. Show all posts

Tuesday, May 19, 2020

Monday, May 18, 2020

Java: Selection Sort


The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from the unsorted part and putting it at the beginning.
The algorithm maintains two subarrays in a given array.

1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.

In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.
Following example explains the above steps:

arr[] = 64 25 12 22 11

Find the minimum element in arr[0...4]and place it at beginning
11 25 12 22 64

Find the minimum element in arr[1...4]and place it at beginning of arr[1...4]
11 12 25 22 64

Find the minimum element in arr[2...4] and place it at beginning of arr[2...4]
11 12 22 25 64
Find the minimum element in arr[3...4] and place it at beginning of arr[3...4]
11 12 22 25 64


public class SelectionSort {

    void sort(int arr[])
    {
        int n = arr.length;

        // One by one move boundary of unsorted subarray         
        for (int i = 0; i < n-1; i++)
        {
            // Find the minimum element in unsorted array 
            int min_idx = i;
            for (int j = i+1; j < n; j++)
                if (arr[j] < arr[min_idx])
                    min_idx = j;

            // Swap the found minimum element with the first element
                      
            int temp = arr[min_idx];
            arr[min_idx] = arr[i];
            arr[i] = temp;
        }
    }
    // Prints the array     
   void printArray(int arr[])
    {
        int n = arr.length;
        for (int i=0; i            System.out.print(arr[i]+" ");
        System.out.println();
    }

    // Driver code to test above 
   public static void main(String args[])
    {
        SelectionSort ob = new SelectionSort();
        int arr[] = {64,25,12,22,11};
        System.out.println("input array");
        ob.printArray(arr);
        ob.sort(arr);
        System.out.println("Sorted array");
        ob.printArray(arr);
    }
}

Sunday, May 17, 2020

Java: Bubble Sort

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order.

Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.

Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.

Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )





public class BubbleSort {
    void bubbleSort(int arr[])
    {
        int n = arr.length;
        for (int i = 0; i < n-1; i++)
            for (int j = 0; j < n-i-1; j++)
                if (arr[j] > arr[j+1])
                {
                    // swap arr[j+1] and arr[i] 
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
    }

    /* Prints the array */     
   void printArray(int arr[])
    {
        int n = arr.length;
        for (int i=0; i 
          System.out.print(arr[i] + " ");
          System.out.println();
    }

    // Driver method to test above 
    public static void main(String args[])
    {
        BubbleSort ob = new BubbleSort();
        int arr[] = {64, 34, 25, 12, 22, 11, 90};
        System.out.println("Input array");
        ob.printArray(arr);

        ob.bubbleSort(arr);
        System.out.println("Sorted array");
        ob.printArray(arr);
    }

}

Saturday, May 16, 2020

Python: Binary Search

Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.

The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Log n).

class BinarySearch(object) :

    def binarySearch(self, A, K):

        # Returns index of x in arr if present, else -1 
    def binarySearch(arr, l, r, x):

       # Check base case             
       if r >= l:
                print("r,l:",r,", ",l)
                mid = round(l + (r - l) / 2)

                # If element is present at the middle itself 
                if arr[mid] == x:
                    return mid

                # If element is smaller than mid, then it can only 
                # be present in left subarray 
                elif arr[mid] ==  x:
                    print("search left side of the array: arr[mid] is ", arr[mid])
                    return binarySearch(arr, l, mid - 1, x)

                    # Else the element can only be present in right subarray                 
                else:
                    print("search right side of the array: arr[mid] is  ", arr[mid])
                    return binarySearch(arr, mid + 1, r, x)

            else:
                # Element is not present in the array 
                return -1

        result = binarySearch(A, 0, len(A)-1, K)
        return result

def main():
    x = BinarySearch()
    A = [10, 7, 8, 9, 1, 5]
    k = 1    #output = 8    #A =[7, 10, 4, 3, 20, 15]
    A.sort()
    print("array is: ",A)
    print("element ",k, " of array ", A, " is index ", x.binarySearch(A,k))

if __name__ == '__main__':
    main()

Friday, May 15, 2020

Python Convert 12 Hour to 24 Hour Time

For computation purposes, 24 hour time works better. Here is a function to convert the 12 Hour time String to 24 hour time string.
def time_convert_12_24(self,str_time):
    
    time_arr = str_time.split()  # split by space    n = time_arr[0].count(':')
    time_str : str ='' 
    if n == 1 :
       #5:30        
       time_str = time_arr[0]+':00'     
    elif n == 0 :
       #5 
       time_str = time_arr[0]+':00:00'     
    else :
       time_str = time_arr[0]
    #change 12:00 am to 00:00
    if time_arr[1].upper() == 'AM' and time_str[:1] == "12":
        "00" + time_str[2:-2]
    # add 12 hour to PM hours
    if time_arr[1].upper() == 'PM' :
        str_part = time_str.split(':')
        if int(str_part[0]) != 12 :
            return str(int(str_part[0]) + 12) +':'+str_part[1] + ':'+ str_part[2]
        else :
            return time_str
    else :
        return time_str

Wednesday, May 13, 2020

Interesting Q & A






Kids will know and thank the one who has saved their lives when they grow up.

Wednesday, April 01, 2020

Added A Column To Every Table In The Same Schema In PostgresSQL

Sometime, we may find out that we need to add a column to every table in the same schema or same database. For example, we want to add an audit column. The following query is for that.


do $$
declare
    addcolumn record;
    dm_schema VARCHAR(8) := ‘sales_dm';
begin
for addcolumn in
select
      'ALTER TABLE '|| dm_schema ||'.'|| T.targettable ||  ' ADD COLUMN  IF NOT EXISTS last_modified_timestamp timestamp  NULL' as sqlscript
   from
      (
        select tablename as targettable from  pg_tables where schemaname = dm_schema 
      ) t
loop
execute addcolumn.sqlscript;
end loop;
end;
$$;

Monday, March 23, 2020

Get Date OF Week From Datetime

The following function reture weekday in differe format from a day.  
 
def getWeekDayChar(self,date_time : datetime,rt_type : str ) -> str :

    ''' 
     :param date_time: datetime     
     :param rt_type: 'i' = number, 'l' = long form, 's' = short form     
     :return: week date in spefified format 
    ''' 
  
    week_date_dict : dict = {0: ('Monday','Mon'), 1:('Tuesday','Tus'),2 : ('Wendsday', 'Wed'),
                             3:('Thursday','Thu'), 4: ('Friday','Fri') ,
                             5 :('Saturday','Sat')   ,6:('Sunday','Sun')}

    week_date_num : int = date_time.weekday()

    if rt_type == 'i' :
        return week_date_num
    elif rt_type == 'l' :
        return week_date_dict(week_date_num)(0)
    elif rt_type == 's' :
        return week_date_dict(week_date_num)(1)
    else :
        return None

Sunday, March 22, 2020

Retrieve JWT Authentication Access Token Using HttpsURLConnection


In JWT Authentication, a token is used to access the API interfaces.  In general, it will be a two-step authentication process. First, it will authenticate the user using the user's credentials such as login id, password, client id, and secret keys. Following is a method on how to get the access token uses HTTPS protocol.

    public JwtAuthenticationResponse getHttpsAuthToken(String hostName, int port,     
                                                                    String   userName, String userPassword,
                                                            String grantType, String clientId, String clientSecret,
                                                               String urlPath) 
        HttpsURLConnection httpConn = null;
        final int BUFFER_SIZE = 4096;
        // Create a trust manager that does not validate certificate chains (should be removed in prod env)
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        }
        };
        try {
            // Install the all-trusting trust manager
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            // Create all-trusting host name verifier
            HostnameVerifier allHostsValid = new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };

            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

        } catch (NoSuchAlgorithmException e) {

            logger.debug(String.format("Cannot connect to Hybris server:  %s ;", e.toString()));
            throw new RuntimeException(e);

        } catch (KeyManagementException e) {
            logger.debug(String.format("Cannot connect to Hybris server:  %s ;", e.toString()));
            throw new RuntimeException(e);

        }

        String url;
url = "https://"+hostName + ":"+String.valueOf(port)+"/services/oauth2/token";
        logger.debug("get authendication using: " + url);

        InputStream inputStream;

        try {

            StringBuilder data = new StringBuilder ( );

            data.append ("grant_type=" + grantType);
            data.append ("&client_id=" + clientId);
            data.append ("&client_secret=" + clientSecret);

            if (userId != null && !userId.equals ("undefined")) {
                data.append ("&username=" + userId);
            }
            if (userPassword != null && !userPassword.equals ("undefined")) {
                data.append ("&password=" + userPassword);
            }

           String auth = clientId + ":" + clientSecret;
            byte[] encodedS = Base64.encodeBase64 (auth.getBytes ( ));

            String authHeader = "Basic " + new String (encodedS);

            // Create a byte array of the data to be sent
            byte[] encodedAuth = data.toString ( ).getBytes ("UTF-8");
            String authId = userId + ":" + userPassword;
            byte[] encodedId = Base64.encodeBase64 (authId.getBytes ( ));
            String authHeaderId = "Basic " + new String (encodedId);

            // Setup the Request
            URL request = new URL (url);
            httpConn = (HttpsURLConnection) request.openConnection ( );
            httpConn.setRequestMethod ("POST");
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConn.setRequestProperty("Content-Length", "" + encodedAuth.length);
            httpConn.setRequestProperty("Content-Length", "" + encodedAuth.length);
            httpConn.setRequestProperty("Authorization", authHeaderId);
            httpConn.setUseCaches (false);
            httpConn.setDoOutput (true);

            // Write data
            OutputStream postStream = httpConn.getOutputStream ( );
            postStream.write (encodedAuth);
            postStream.flush ( );
            postStream.close ( );
            // For POST only - END
            int responseCode = httpConn.getResponseCode ( );
            String response;
            if (responseCode == 200) {
                inputStream = httpConn.getInputStream ( );
                ObjectMapper mapper = new ObjectMapper ( );
                JsonNode jsonMap = mapper.readTree (inputStream);
                String token = jsonMap.get ("access_token").toString ( ).replaceAll ("\"", "");
                String tokenType = jsonMap.get ("token_type").toString ( ).replaceAll ("\"", "");
                String refreshToken = null;
                return new JwtAuthenticationResponse (jsonMap.get ("access_token").toString ( ));
            } else {
                inputStream = httpConn.getErrorStream ( );
                try (Scanner scanner = new Scanner (inputStream)) {
                    scanner.useDelimiter ("\\Z");
                    response = (scanner.next ( ));
             }

            String exceptionMsg = "Response Code " + String.valueOf (responseCode) + ". " +
                                                  response;
                throw new UserDefinedException (exceptionMsg);
            }
        } catch (IOException | UserDefinedException e) {

            logger.debug(String.format("Cannot connect to server:  %s ;", e.toString()));
            throw new RuntimeException(e);
        }
    }

Saturday, March 21, 2020

Enable Logging In Python

Python’s logging module is part of the Python Standard Library. The logging module’s basicConfig() method 
is the quickest way to configure the desired behavior of your logger. However,  applications use file-based or 
dictionary-based logging configuration requires a slightly different configuration.

One simple way to set up file-based logging is to use a config file and fileConfig module to read the log configuration properties. 

The log config file will have a format like the one below:

[loggers]
keys=root,pipeline

[handlers]
keys=fileHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=fileHandler

[logger_pipeline]
level=DEBUG
handlers=fileHandler
qualname=pipeline
propagate=0

[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=simpleFormatter
args=('./log/pipeline.log','a')

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=

To make it a bit simple to enable logging inside the application, a utility module can be created to handle the logging.

import logging
from logging.config import fileConfig
class AppLogger():
   #ensure a singleton. We only want one log per applcation.
   __instance = None

   #create a static methold to get a logger instance.
   # The staticmethod() built-in function returns a static method for a given function.
   @staticmethod
   def get_applog():
       if AppLogger.__instance is None:
           AppLogger()

       return AppLogger.__instance

   def __init__(self):
       if AppLogger.__instance is not None:
           raise Exception("Only one application log should be activated at a time")
       AppLogger.__instance = AppLogger.create_applogger()

   @staticmethod
   def create_applogger():
       fileConfig('./config/applog_config.cfg', disable_existing_loggers=False)
       logger = logging.getLogger('pipeline')
       return logger

Now, in any of the modules within the application, we can involve the logger by calling the log module.

from util.log import AppLogger

Logger = AppLogger.get_applog()

class TestClass() :

    def  a_fuction():
       try:
           # codes here
       
       except Exception as e:
           Logger.error(“Error occurred {0}“.format(str(e))

         finally:
           #do something

The Python documention provides good reference on how to implement logging: