Wednesday, May 22, 2024

 This is a continuation of previous articles on IaC shortcomings and resolutions. With the example of Azure Front Door, we were explaining the use of separate origin groups for logical organization of backend and front-end endpoints. This section talks about route configuration.

A route is the primary directive to Azure Front Door to handle traffic. The route settings define an association between a domain and an origin group.  Features such as Pattern-to-match and rulesets enable granular control over traffic to the backend resources.

A routing rule is composed of two major parts, the “left-hand-side” and the “right-hand-side”. Front Door matches the incoming request to the left-hand side of the route while the right-hand side defines how the request gets processed. On the left-hand side, we have the HTTP Protocols, the domain, and the path where these properties are expanded out so that every combination of a protocol, domain and path is a potential match set. On the right-hand side, we have the routing decisions. If caching is not enabled, the requests are routed directly to the backend.

Route matching is all about the “most-specific-request” that matches with the “left-hand-side”. The order of match is always protocol first, followed by the domain and then the path. The Match is always a yes or a no. Yes, there is a route with an exact match on the frontend host or no there is no such match. In the case of a “No”, a bad request error gets sent. After the host matching comes path matching. A similar logic to frontend hosts is used to match the request path. The only difference is that between a yes or a no, an approximate match based on wild card pattern is allowed. And as always, a failed match returns a bad request error.

One of the key differences between an application gateway and Front Door is this hybrid custom-domain and path-based routing combination matching as described above. Application gateway can be either custom-domain based or path-based routing in most deployments but FrontDoor by its nature to being global across different regional resource types, allows for both custom-domain and path-based matches. 

The anycast behavior from FrontDoor requires a comprehensive test matrix to avoid any unpredictability with low-latency choices made by default. For a choice of host and path, there can be four test cases at least even for a “/*” path. Predictability also involves trying those requests from various regions.

Thus, separate endpoints, routing and host header all play a role in determining the responses from the Azure Front Door. 

Previous articles: https://1drv.ms/w/s!Ashlm-Nw-wnWhO4RqzMcKLnR-r_WSw?e=kTQwQd 


#codingexercise

#codingexercise

Position eight queens on a chess board without conflicts:

    public static void positionEightQueens(int[][] B, int[][] used, int row) throws Exception {

        if (row == 8) {

            if (isAllSafe(B)) {

                printMatrix(B, B.length, B[0].length);

            }

            return;

        }

        for (int k = 0; k < 8; k++) {

            if ( isSafe(B, row, k) && isAllSafe(B)) {

                B[row][k] = 1;

                positionEightQueens(B, used, row + 1);

                B[row][k]  = 0;

            }

        }

    }

    public static boolean isSafe(int[][] B, int p, int q) {

        int row = B.length;

        int col = B[0].length;

        for (int i = 0; i < row; i++) {

            for (int j = 0; j < col; j++) {

                if (i == p && j == q) { continue; }

                if (B[i][j] == 1) {

                    boolean notSafe = isOnDiagonal(B, p, q, i, j) ||

                            isOnVertical(B, p, q, i, j) ||

                            isOnHorizontal(B, p, q, i, j);

                    if(notSafe){

                        return false;

                    }

                }

             }

        }

        return true;

    }

    public static boolean isAllSafe(int[][] B) {

        for (int i = 0; i < B.length; i++) {

            for (int j = 0; j < B[0].length; j++) {

                if (B[i][j]  == 1 && !isSafe(B, i, j)) {

                    return false;

                }

            }

        }

        return true;

    }

    public static boolean isOnDiagonal(int[][] used, int r1, int c1, int r2, int c2) {

        boolean result = false;

        int row = used.length;

        int col = used[0].length;

        for (int k = 0; k < 8; k ++) {

            if (r2 - k >= 0 &&  c2 - k >= 0 && r1 == r2 - k && c1 == c2 - k) {

                return true;

            }

            if (r2 + k < row && c2 + k < col && r1 == r2 + k && c1 == c2 + k) {

                return true;

            }

            if (r2 - k >= 0 && c2 + k < col && r1 == r2 - k && c1 == c2 + k) {

                return true;

            }

            if (r2 + k < row  && c2 - k >= 0 && r1 == r2 + k && c1 == c2 - k) {

                return true;

            }

        }

        return result;

    }

    public static boolean isOnVertical(int[][] used, int r1, int c1, int r2, int c2) {

        boolean result = false;

        int row = used.length;

        int col = used[0].length;

        for (int k = 0; k < 8; k++) {

            if (c2 - k >= 0  && c1 == c2 - k && r1 == r2 ) {

                return true;

            }

            if (c2 + k < row && c1 == c2 + k && r1 == r2) {

                return true;

            }

        }

        return result;

    }

    public static boolean isOnHorizontal(int[][] used, int r1, int c1, int r2, int c2) {

        boolean result = false;

        int row = used.length;

        int col = used[0].length;

        for (int k = 0; k < 8; k++) {

            if (r2 - k >= 0  && r1 == r2 - k && c1 == c2 ) {

                return true;

            }

            if (r2 + k < row && r1 == r2 + k && c1 == c2) {

                return true;

            }

        }

        return result;

    }


Sample output:

1 1 2 1 1 1 1 1

1 1 1 1 1 2 1 1

1 1 1 2 1 1 1 1

1 2 1 1 1 1 1 1

1 1 1 1 1 1 1 2

1 1 1 1 2 1 1 1

1 1 1 1 1 1 2 1

2 1 1 1 1 1 1 1




Tuesday, May 21, 2024

 

 

This is the summary of the book titled “The Cybersecurity playbook – How every leader and Employee can contribute to a culture of security.” written by Allison Cerra and published by Wiley in 2019. The author draws upon years of fighting hacking and cybercrimes to produce a practical checklist for employees at all levels and disciplines such that the mindset for cybersecurity becomes part of the culture. These good habits can thwart attacks and boost preparedness. She calls on product designers to build security into network connected products from the ground up. She calls on human resources to increase awareness, capabilities, and resilience. Security breaches must be clearly communicated, and the response plan must be detailed. Since risk management is part of the cybersecurity initiatives, the finance office must also be involved. CISOs or the Chief Information Security Officer can co-ordinate and maintain the ultimate responsibility.

Corporate cybersecurity relies heavily on employee good habits, as one in five security breaches involves a negligent employee's mistake. Key practices include creating strong passwords, changing them frequently, and not reusing them. Employees should be familiar with common hacker tactics, such as phishing emails, and should check with IT security before using cloud services and tools. Encrypted thumb drives, reporting suspicious emails, and never leaving sensitive information unattended are essential.

Convincing employees to adopt these practices is challenging, as those responsible for cybersecurity often operate in the shadows. CISOs and their teams must weave safe practices and habits into the organization's culture to prepare for attacks and minimize damage. Cybersecurity preparedness requires the combined efforts of all parts of the organization, led by a CISO. The talent market for cybersecurity professionals is also struggling, with new techniques appearing daily.

Cybercriminals organize online communities on the Dark Web, sharing information and strategies. CEOs and board members must recognize that cybersecurity is a continuous escalating battle with measures and countermeasures, and no single tool can solve the problem.

Cybersecurity is a crucial investment for businesses, and it should be prioritized in every board meeting. The CISO should present and update the board on strategic risk management, explaining how the firm is protecting its most important assets. Regular updates from the CISO can help earmark security budgets for protecting these assets. Product designers must build security into network-connected products and devices from the ground up, as recent hacker attacks have highlighted the need for greater risk in every adoption of technology. Developers should make security a priority in product design, building security features as requirements and assigning accountability for continuous security monitoring and upkeep throughout the product life cycle.

Human resources play a crucial role in building cybersecurity awareness, capabilities, and resilience. A talent shortage in IT security talent is prevalent, with HR professionals sourcing candidates from atypical places and with less obvious credentials, such as women. HR should lead the charge in training employees in good cybersecurity practices, adjust reward programs, review personnel access to sensitive data, add questions to job interviews, and ensure every executive has at least one cybersecurity-related metric in their performance plan.

Developing and practicing a detailed communications and response plan to major security breaches is essential. Hacker stealth is a frightening aspect of cybersecurity, and firms should report breaches immediately to reduce damage and serve customers ethically. Preparing ahead of a breach involves scenario planning, developing a full communications plan, and preparing responses for tough questions.

CISOs must reframe their conversations with CFOs from a focus on ROI to one of risk management, estimating financial damage and potential avoidance of losses. CFOs should hold CISOs accountable for their past resource use and training.

CFOs and CISOs must ensure the corporate supply chain adheres to IT security standards, including outsourcing partners, suppliers, and new products or platforms. CISOs must balance policing employees with preventing a free-for-all that puts the firm at risk. They must translate threats to strategy and risks, ensuring that potential attacks put revenue and strategic objectives at risk. CISOs should also share phishing test results and maintain basic security best practices. AI is a weapon in both the company's cybersecurity arsenal and its enemies' arsenals. They must work closely with CIOs, agreeing on metrics, penetration testing schedules, and planned purchases. AI can automate threat detection but also results in more false positives, requiring resources to investigate. Organizations must develop a "sixth sense" for detecting threats and breaches, which can only be achieved when cybersecurity infuses the culture.

Previous book summary: BookSummary94.docx

Summarizing Software: SummarizerCodeSnippets.docx 


#codingexercise

Given a string of digits, count the number of subwords (consistent subsequences) that are anagrams of any palindrome.

Public class solution {

Public static int getSubWords(String digits) {

    Int count = 0;

    for (int k = 1; k < digits.length; k++) {

           for (int I = 0; I <digits.length; I++) {

                Int end = I + k;

                If (end < digits.length) {

                     String word = digits.substring(words, I, end);

                      If (isAnagram(word)) { 

                          count++;

                      }

                }

           }

    }

    return count;

}

Public boolean isAnagram(String word) {

        Map<Char, Integer> charMap = new HashMap<>();

        for (int I = 0; I < word.length; I++) {

               If (charMap.containsKey(word.charAt(I))) {

                    charMap[word.charAt(i)] = charMap.get(word.charAt(I)) + 1;

               } else {

                    charMap.put(word.charAt(I), 1);

               }

        }

        If (charMap.size() %2 == 1) {

            // count of only one element must be odd 

            return charMap.values().stream().filter(x-> x%2 == 1).count() == 1;

        }

        Else { 

             // count of all elements must be even

             return charMap.values().stream().filter(x -> x%2 == 0).count() == charMaps.size();

        }

}

}

test:

14641

2


 

Monday, May 20, 2024

 Given an integer array arr of distinct integers and an integer k.


A game will be played between the first two elements of the array (i.e. arr[0] and arr[1]). In each round of the game, we compare arr[0] with arr[1], the larger integer wins and remains at position 0 and the smaller integer moves to the end of the array. The game ends when an integer wins k consecutive rounds.


Return the integer which will win the game.


It is guaranteed that there will be a winner of the game.

class Solution {

    public int getWinner(int[] arr, int k) {

        int win = 0;

        if (arr == null || arr.length < 2) { return Integer.MIN_VALUE; }

        if (k > arr.length){ 

            int max = Integer.MIN_VALUE;

            for (int i = 0; i < arr.length; i++) {

                if (arr[i] > max) {

                    max = arr[i];

                }

                return max;

            }

        }

        for (int i = 0; i < arr.length * arr.length; i++) {

            if (win >= k) { 

                break; 

            } 

            if (arr[0] > arr[1]) {

                win++;

                int temp = arr[1];

                for (int j = 2; j < arr.length; j--) {

                    arr[j-1] = arr[j];

                }

                arr[arr.length - 1] = temp;

                continue;

            }

            win = 1;

            int temp = arr[0];

            for (int j = 1; j < arr.length; j--) {

                arr[j-1] = arr[j];

            }

            arr[arr.length - 1] = temp;

        }

        return arr[0];

    }

}


Arr: 2,8,5,6,6 k=3

8,5,6,6,2

8,6,6,2,5

8,6,2,5,6

8


Sunday, May 19, 2024

 Given a string of digits, count the number of subwords (consistent subsequences) that are anagrams of any palindrome.

Public class solution {

Public static int getSubWords(String digits) {

    Int count = 0;

    for (int k = 1; k < digits.length; k++) {

           for (int I = 0; I <digits.length; I++) {

                Int end = I + k;

                If (end < digits.length) {

                     String word = digits.substring(words, I, end);

                      If (isAnagram(word)) { 

                          count++;

                      }

                }

           }

    }

    return count;

}

Public boolean isAnagram(String word) {

        Map<Char, Integer> charMap = new HashMap<>();

        for (int I = 0; I < word.length; I++) {

               If (charMap.containsKey(word.charAt(I))) {

                    charMap[word.charAt(i)] = charMap.get(word.charAt(I)) + 1;

               } else {

                    charMap.put(word.charAt(I), 1);

               }

        }

        If (charMap.size() %2 == 1) {

            // count of only one element must be odd 

            return charMap.values().stream().filter(x-> x%2 == 1).count() == 1;

        }

        Else { 

             // count of all elements must be even

             return charMap.values().stream().filter(x -> x%2 == 0).count() == charMaps.size();

        }

}

}

test:

14641

2


Saturday, May 18, 2024

 Error Correction for Drone flight path management

With the popularity of modular composition, many industries are taking advantage of a fleet of functional units that can collectively function as a whole and eliminate the risks of the monoliths that used to serve the purpose earlier. Fleet refers to many drones, bots or other software automations that are capable of a specific function such as moving from point A to point B in space. 

While single remote-controlled units can follow the handlers' commands in real-time, the fleet usually operates according to a program. Centralized logic maps an initial state to a final state and issues command to each drone to move from the starting point to the ending point. It is easy for software to map initial co-ordinates for each drone in a formation on land and command them to move to a final co-ordinate in the sky to form a specific arrangement. 

Autonomous drone fleet formation avoids the need for a centralized controller that plots determines the final co-ordinates and non-overlapping flight path for each unit. The suggestion is that the computation for the final position from the initial position for each unit does not need to be performed at the controller and that logic can be delegated to the autonomous units. For example, if we wanted to change a fleet forming the surface of a sphere to a concentric plane of Saturn-like rings, then the final co-ordinates of each unit must be distinct, and its determination is not restricted to processing at the controller. While autonomous decisions are made by individual drones, they must remain within the overall trajectory tolerance space for the entire fleet. This can be achieved with the popular neural net for softmax classification. The goodness of fit for a formation or sum of squares of errors of F-score are other alternative measures. This is not a one-time adjustment to the formation but a continuous feedback-loop circuit where the deviation is monitored, and suitable error corrections are performed. Correction can also be translated as optimization problems where the objective function is maximized. It is common to describe optimization problems in local versus global optimization. Local optimization involves finding the optimal solution for a specific region of the search space while global optimization involves finding the optimal solutions on problems  that contain local optima. In some cases, joint local and global optimization recommendations can be computed and applied. The choice of algorithms for local search include Nelder-Mead algorithm, BFGS algorithm, and Hill-Climbing algorithm.  Global optimization algorithms include Genetic algorithm, Simulated Annealing, and Particle Swarm Optimization. The sum of square errors is almost independent of space-time variables and gives a quantitative measure that works well as the objective function to optimization problems. Therefore, the sum of the squares and the simulated annealing algorithm are good general-purpose choices that are applicable to drone formations. The formation is singleton otherwise the divisions can be treated like formations with cohesion and separation. The relationship between cohesion and separation is written as TSS = SSE + SSB where TSS is the total sum of squares. SSE is the sum of squared error and SSB is the between group sum of squares, the higher the total SSB, the more separated the formations are. Minimizing SSE (cohesion) automatically results in maximizing SSB (separation). Formation can be ranked and processed based a Silhouette co-efficient that combines both cohesion and separation.  This is done in three steps. 

For the I'th object, calculate its average distance to all other objects in formation and call it ai 

For the I'th object, and any formation not containing the object, calculate the object's average distance to all the objects in the given formation. Use the minimum value and call it bi 

For the I'th object, the silhouette coefficient is given by (bi-ai)/max (ai, bi)

Sample python implementation: 

#! /usr/bin/python 

def determining_replacement_for_team(nodes): 

                              Return formation_centroids_of_top_formations(nodes) 

 

def batch_formation_repeated_pass(team, nodes) 

                    team_formation = classify(team, nodes) 

                    proposals = gen_proposals(team_formation) 

                    formations = [(FULL, team_formation)] 

                     For proposal in proposals: 

                                             Formation = get_formation_proposal(proposal, team, nodes) 

                                              formations += [(proposal, formation)] 

                     Selections = select_top_formations(formations) 

                     Return team_from(selections) 

 

Def select_top_formations(threshold, formations, strategy = goodness_of_fit): 

                     return formations_greater_than_goodness_of_fit_weighted_size(threshold, formations)


def annealingoptimize(domain,costf,T=10000.0,cool=0.95,step=1): 

     # Initialize the values randomly 

     vec=[float(random.randint(domain[i][0],domain[i][1])) 

          for i in range(len(domain))] 

     while T>0.1: 

          # Choose one of the indices 

          i=random.randint(0,len(domain)-1) 

          # Choose a direction to change it 

          dir=random.randint(-step,step) 

          # Create a new list with one of the values changed 

          vecb=vec[:] 

          vecb[i]+=dir 

          if vecb[i]<domain[i][0]: vecb[i]=domain[i][0] 

          elif vecb[i]>domain[i][1]: vecb[i]=domain[i][1] 

          # Calculate the current cost and the new cost 

          ea=costf(vec) 

          eb=costf(vecb) 

          p=pow(math.e,(-eb-ea)/T) 

          # Is it better, or does it make the probability 

          # cutoff? 

          if(eb<ea or random.random( )<p): 

               vec=vecb 

          # Decrease the temperature 

          T=T*cool 

     return vec 

#codingexercise

Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array.
Return the minimum number of patches required.
class Solution {
    public int minPatches(int[] nums, int n) {
        int count = 0;
        int[] sums = new int[n+1]; 
        Arrays.fill(sums, 0);
        sums[0] = 1;
        List<Integer> elements = new ArrayList<>(nums);
        while(!allOnes(sums)){
            List<List<Integer>> combinations = new ArrayList<>();
            List<Integer> selection = new ArrayList<Integer>();
            combine(elements, selection, 0, 0, combinations);
            for (int i = 0; i < combinations.size(); i++) {
                int sum = combinations.get(i).stream().sum();
                if (sum <= n && sums[sum] != 1) {
                    sums[sum] = 1; 
                } 
            }
            addLowestMissingNumber(elements);
            count++;
        }
        return count;
    }
}


Friday, May 17, 2024

 This is a continuation of previous articles on IaC shortcomings and resolutions. With the example of Azure Front Door, we were explaining the use of separate origin groups for logical organization of backend and front-end endpoints. This section talks about route configuration.

A route is the primary directive to Azure Front Door to handle traffic. The route settings define an association between a domain and an origin group.  Features such as Pattern-to-match and rulesets enable granular control over traffic to the backend resources.

A routing rule is composed of two major parts, the “left-hand-side” and the “right-hand-side”. Front Door matches the incoming request to the left-hand side of the route while the right-hand side defines how the request gets processed. On the left-hand side, we have the HTTP Protocols, the domain, and the path where these properties are expanded out so that every combination of a protocol, domain and path is a potential match set. On the right-hand side, we have the routing decisions. If caching is not enabled, the requests are routed directly to the backend.

Route matching is all about the “most-specific-request” that matches with the “left-hand-side”. The order of match is always protocol first, followed by the domain and then the path. The Match is always a yes or a no. Yes, there is a route with an exact match on the frontend host or no there is no such match. In the case of a “No”, a bad request error gets sent. After the host matching comes path matching. A similar logic to frontend hosts is used to match the request path. The only difference is that between a yes or a no, an approximate match based on wild card pattern is allowed. And as always, a failed match returns a bad request error.

One of the key differences between an application gateway and Front Door is this hybrid custom-domain and path-based routing combination matching as described above. Application gateway can be either custom-domain based or path-based routing in most deployments but FrontDoor by its nature to being global across different regional resource types, allows for both custom-domain and path-based matches. 

The anycast behavior from FrontDoor requires a comprehensive test matrix to avoid any unpredictability with low-latency choices made by default. For a choice of host and path, there can be four test cases at least even for a “/*” path. Predictability also involves trying those requests from various regions.

Thus, separate endpoints, routing and host header all play a role in determining the responses from the Azure Front Door. 

#codingexercise 

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. 

Node reverse(Node master, Node start, Node end) {

If (start == null) return null;

If (start.next == null) return start;

Node tail = start;

Node prev = end;

Node cur = start;

Node next = cur.next;

While (next && cur != end) {

Cur.next = prev;

Prev = cur;

Cur = next;

Next = cur.next;

}

if (cur != end) {

     cur.next = prev;

     prev = cur;

     cur = next;

}

if (master != null) {

     master.next = prev;

} else {

    master = prev;

}

Return tail;

}

public Node reverse(Node head, int k) {

Node start = head;

Node end = head;

Node master = null;

while (end != null) {

    int count = 0;

    while (count < k && end != null) {

       end = end.next;

       count++;     

    }

    if (count == k) {

        Node last = master;

        master = reverse(master, start, end); 

         if (start == head) {

         head = master;

         }

         if (last != null) {

              last.next = master;

         } 

         while(master.next != end)  {

              master = master.next;

         }

         start = master.next;

         end = start;

    }

}

return head;

}


Thursday, May 16, 2024

 

This is a continuation of previous articles on IaC shortcomings and resolutions. With the example of Azure Front Door, we were explaining the use of separate origin groups for logical organization of backend and front-end endpoints. This section talks about route configuration.

A route is the primary directive to Azure Front Door to handle traffic. The route settings define an association between a domain and an origin group.  Features such as Pattern-to-match and rulesets enable granular control over traffic to the backend resources.

A routing rule is composed of two major parts, the “left-hand-side” and the “right-hand-side”. Front Door matches the incoming request to the left-hand side of the route while the right-hand side defines how the request gets processed. On the left-hand side, we have the HTTP Protocols, the domain, and the path where these properties are expanded out so that every combination of a protocol, domain and path is a potential match set. On the right-hand side, we have the routing decisions. If caching is not enabled, the requests are routed directly to the backend.

Route matching is all about the “most-specific-request” that matches with the “left-hand-side”. The order of match is always protocol first, followed by the domain and then the path. The Match is always a yes or a no. Yes, there is a route with an exact match on the frontend host or no there is no such match. In the case of a “No”, a bad request error gets sent. After the host matching comes path matching. A similar logic to frontend hosts is used to match the request path. The only difference is that between a yes or a no, an approximate match based on wild card pattern is allowed. And as always, a failed match returns a bad request error.

One of the key differences between an application gateway and Front Door is this hybrid custom-domain and path-based routing combination matching as described above. Application gateway can be either custom-domain based or path-based routing in most deployments but FrontDoor by its nature to being global across different regional resource types, allows for both custom-domain and path-based matches.

The anycast behavior from FrontDoor requires a comprehensive test matrix to avoid any unpredictability with low-latency choices made by default. For a choice of host and path, there can be four test cases at least even for a “/*” path. Predictability also involves trying those requests from various regions.

Thus, separate endpoints, routing and host header all play a role in determining the responses from the Azure Front Door.

Previous articles: https://1drv.ms/w/s!Ashlm-Nw-wnWhO4RqzMcKLnR-r_WSw?e=kTQwQd