Thursday, March 21, 2024

 

In Azure public cloud, a virtual network (VNet) is a representation of your own network in the cloud. It allows you to securely connect Azure resources and extend your on-premises network to the cloud. A VNet is isolated and provides network-level segmentation and security. It also enables you to control inbound and outbound traffic using network security groups and virtual network service endpoints.

Peering is a feature in Azure that allows you to connect virtual networks together, both within the same region or across different regions. This enables resources in different virtual networks to communicate with each other using private IP addresses. There are two types of peering available in Azure:

  1. VNet peering: This allows you to connect virtual networks within the same region or different regions, as long as they belong to the same Azure subscription or different subscriptions within the same Azure Active Directory tenant. VNet peering is transitive, meaning that if VNet A is peered with VNet B, and VNet B is peered with VNet C, then VNet A can communicate with VNet C directly, without the need for a separate peering.
  2. Global VNet peering: This allows you to connect virtual networks across different Azure regions, regardless of whether they belong to the same subscription or Azure Active Directory tenant. Global VNet peering is also transitive, enabling communication between virtual networks in different regions.

Peering in Azure provides several benefits, including:

  • Reduced latency: With peering, you can achieve lower latency by establishing direct connections between virtual networks instead of going through public internet gateways.
  • Improved network performance: Peered virtual networks can communicate with each other at higher network speeds compared to traffic going through gateways.
  • Simplified network architecture: Peering allows you to create a flat network topology by connecting virtual networks together, simplifying network management and reducing the need for complex routing configurations.
  • Enhanced security: Peering enables secure communication between virtual networks using private IP addresses, ensuring that traffic remains within the Azure backbone network and is not exposed to the public internet.

Overall, virtual network and peering in Azure public cloud provide powerful capabilities for building and connecting networks in a secure and scalable manner..

 

Wednesday, March 20, 2024

 

3 ways to normalize xyz coordinates:

1)       

import pandas as pd

from sklearn import preprocessing

 

# Create a sample dataframe with XYZ coordinates

df = pd.DataFrame.from_dict({

    'X': [10.5, 20.3, 15.7, 8.9],

    'Y': [30.2, 25.1, 18.6, 22.0],

    'Z': [12.0, 14.8, 11.2, 9.5]

})

 

# Normalize the XYZ coordinates using min-max scaling

min_max_scaler = preprocessing.MinMaxScaler()

normalized_xyz = min_max_scaler.fit_transform(df)

 

# Create a new dataframe with the normalized values

normalized_df = pd.DataFrame(normalized_xyz, columns=['X', 'Y', 'Z'])

 

print(normalized_df)

 

2)       

 

import pandas as pd

import numpy as np

 

# Create a sample dataframe with XYZ coordinates

df = pd.DataFrame({

    'X': [10.5, 20.3, 15.7, 8.9],

    'Y': [30.2, 25.1, 18.6, 22.0],

    'Z': [12.0, 14.8, 11.2, 9.5]

})

 

# Calculate L2 norm for each row

row_l2_norms = np.linalg.norm(df[['X', 'Y', 'Z']].values, axis=1)

 

# Normalize the coordinates by dividing each row by its L2 norm

normalized_xyz = df[['X', 'Y', 'Z']].div(row_l2_norms, axis=0)

 

print(normalized_xyz)

 

3)      By hand

def normalize_xyz(coordinates):

    # Find the minimum and maximum values for each coordinate

    min_x = min(coord[0] for coord in coordinates)

    max_x = max(coord[0] for coord in coordinates)

    min_y = min(coord[1] for coord in coordinates)

    max_y = max(coord[1] for coord in coordinates)

    min_z = min(coord[2] for coord in coordinates)

    max_z = max(coord[2] for coord in coordinates)

 

    # Normalize each coordinate

    normalized_coords = []

    for x, y, z in coordinates:

        norm_x = (x - min_x) / (max_x - min_x)

        norm_y = (y - min_y) / (max_y - min_y)

        norm_z = (z - min_z) / (max_z - min_z)

        normalized_coords.append((norm_x, norm_y, norm_z))

 

    return normalized_coords

 

# Example usage

xyz_coordinates = [(10.5, 30.2, 12.0), (20.3, 25.1, 14.8), (15.7, 18.6, 11.2), (8.9, 22.0, 9.5)]

normalized_xyz = normalize_xyz(xyz_coordinates)

 

print(normalized_xyz)


#codingexercise 

Subarray Sum equals K 

Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals tok. 

A subarray is a contiguous non-empty sequence of elements within an array. 

Example 1: 

Input: nums = [1,1,1], k = 2 

Output: 2 

Example 2: 

Input: nums = [1,2,3], k = 3 

Output: 2 

Constraints: 

·        1 <= nums.length <= 2 * 104 

·        -1000 <= nums[i] <= 1000 

·        -107 <= k <= 107 

 

class Solution { 

    public int subarraySum(int[] nums, int k) { 

        if (nums == null || nums.length == 0) return -1; 

        int[] sums = new int[nums.length];    

        int sum = 0; 

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

            sum += nums[i]; 

            sums[i] = sum; 

        } 

        int count = 0; 

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

            for (int j = i; j < nums.length; j++) { 

                int current = nums[i] + (sums[j] - sums[i]); 

                if (current == k){ 

                    count += 1; 

                } 

            } 

        } 

        return count; 

    } 

} 

 

[1,3], k=1 => 1 

[1,3], k=3 => 1 

[1,3], k=4 => 1 

[2,2], k=4 => 1 

[2,2], k=2 => 2 

[2,0,2], k=2 => 4 

[0,0,1], k=1=> 3 

[0,1,0], k=1=> 2 

[0,1,1], k=1=> 3 

[1,0,0], k=1=> 3 

[1,0,1], k=1=> 4 

[1,1,0], k=1=> 2 

[1,1,1], k=1=> 3 

[-1,0,1], k=0 => 2 

[-1,1,0], k=0 => 3 

[1,0,-1], k=0 => 2 

[1,-1,0], k=0 => 3 

[0,-1,1], k=0 => 3 

[0,1,-1], k=0 => 3 

 

 

 

 

 


Tuesday, March 19, 2024

 

This is a continuation of articles on Infrastructure-as-code shortcomings to address deployment routines. One of the most frequently encountered situations is when a resource is deployed with a configuration that does not permit subsequent changes in place. This could be at any level such as from the vnet that a resource is hosted on along with its private endpoint and zone to a key in a keyvault that must be changed. Some errors encountered in such situations and their resolutions are now called out.

First, if a resource cannot be updated in place, it is widely assumed that it must be deleted and recreated. The setup and teardown are not onerous for an IaC based deployment which is by definition, idempotent and repeatable. However, it is also seldom known that delete might not always imply that another can be created with the same name.  Take for instance keys in a keyvault that is enabled for soft-delete. Even when the keys are deleted and no longer appearing in the list of keys, it still lingers.  This persists for 90 days. A new key with the same name cannot be created and a name change is required. When the name changes, all upstream usages also change which can be quite pervasive.

Second, taking backups also suffers from similar concern. A backup of a key in a keyvault can be downloaded and restored with but if the resource is enabled with soft-delete, then the restoration for a backup also fails. In this case, a new key is not created but the old key is restored and yet the problem is similar. Backups and restores are not limited to keyvaults and can span other data stores such as databases. How the resource is configured such as if soft-delete or purge protection which is similar to a lock of an item in a recycle bin, is enabled.

Third, another popular use case is when there is an interim state of deployment when resources are dual-homed. For example, moving a resource from one vnet to another, is often attempted with a private endpoint added to the destination vnet. For a certain period of time, the resource has addressability in both networks until the old one is decommissioned. It is also perfectly fine for a resource to have multiple private endpoints. However, the point that escapes attention often is that the old one cannot be deleted and lingers resulting in the interim state becoming a permanent solution.  To add to this complexity, the private endpoints do not solve all addressability concerns and often disable public IP connectivity.  Traffic flow from different virtual networks might not have the same gateway and dedicated outbound subnets can only be one per resource. In these cases, new deployments and migration of workloads offer a simpler alternative.


Monday, March 18, 2024

 

This is a summary of the book “The Humour Code: a global search for what makes things funny.” written by Peter McGraw and Joel Warner and published by Simon and Schuster in 2014. Comedians and common people alike explore what makes something funny, yet there is no science behind it. As journalists, the authors have traveled far and wide to decipher the secret of humour. Their journey has taken them to “clown brigade” in a Peruvian slum, found humour amid the strife of Intifada, and the Japanese hermetic humour. This has reinforced the assumption that humour and laughter are mystery. Business minded people might find insights into funny ads and folks dealing with customers might find the serious side of funny. Humour can ease tensions and increase trust. It can also be divisive and make bigotry more acceptable. Laughter enhances physical health, so why not try this?

In their journey to understand why people laugh, they investigated an epidemic of contagious laughter in Tanzania, met comedy directors in Japan, portrayed Boy George's dog in an improv theater skit in Los Angeles, and examined the fallout from newspaper cartoons mocking the prophet Mohammad in Denmark. Despite the existence of laughter in entertainment, marketing, and daily life, science has never definitively explained its evolution or why people find certain things funny. Humor is a delicate operation built on shared knowledge, assumptions, and innuendo. Philosophers like Aristotle and Plato proposed the "superiority theory," which suggests people laugh at the "misfortunes of others." Sigmund Freud theorized that jokes and laughter serve as escape valves for repressed emotions, but this does not explain why puns are funny. Philosopher Blaise Pascal's "incongruity theory" and Arthur Koestler's "benign violation" theory explain why people laugh when tickling them.

Humor has evolved as a social signal, a refined version of primates' panting during play-fights. Research by neuroscientist and psychologist Robert Provine supports this notion, finding that laughter is part of conversational repertoire and not a spontaneous outburst. Humor has two distinct types: spontaneous laughter, which appeared between two and four million years ago, and intentional laughter, which has been imitated intentionally to take advantage of its social-bonding effects.

Humor fosters positive feelings, which marketers exploit, spending upward of $60 billion on humorous ads in 2008. However, no definitive evidence proves that humor motivates people to buy products being advertised. Marketers face the danger that gags in their ads may keep viewers from taking their messages seriously. Instead, humorous advertising should use a "wedding toast" approach, starting with attention-grabbing jokes and then putting all kidding aside.

People laugh in good times and bad, and humor thrives in demanding situations. Humor can help endure tricky situations and protect brands, as seen when the USS Pueblo crew used humor to survive capture by North Korea.

Humor and coping mechanisms are linked, with humor serving as a psychological buffer and a defense mechanism against further trauma. It develops in infants between 10 and 20 weeks of age, but some experts argue that humor may not always be beneficial eventually, as it may discourage social change. For example, the "laughtivists" in Serbia used humor to reduce the fear barrier and lead to a revolt against dictator Slobodan Milošević.

However, humor can also be a double-edged sword. It can ease tensions and bring people together, but it can also divide and stir up conflict. Racist, sexist, and homophobic jokes can underscore differences, validate negative stereotypes, and ostracize whole groups of people. In 1979, Norman Cousins used comedy films as part of treatment for a patient with degenerative joint disease, highlighting the importance of humor in medicine. The idea that humor can boost health caught on. Laughter can play a crucial role in coping mechanisms and social change, but it is important to recognize the potential dangers and drawbacks of humor in various cultures.

Although, humor, as a form of laughter, has been used to promote health and wellbeing in various ways, including training health professionals and practicing "laughter yoga" in 72 countries and with some proponents arguing that humor can boost immune-system function, stave off illnesses, and decrease heart-disease risk, no definitive evidence has been found. Instead, humor is seen as an essential tool for human connection and can enhance emotional health. Psychologists like Steve Wilson see humor as an "adjunctive therapy" that can help main therapies work better. Humor also provides a perspective on difficulties and the whimsical side of life.

Previous book summary: BookSummary67.docx

Summarizing Software: SummarizerCodeSnippets.docx.   

Sunday, March 17, 2024

 

Given a non-empty array of N integers describing elevation along x-axis starting at 0 and  defining peaks as co-ordinates where the elevation is greater than adjacents, find the maximum number of flags that can be put on peaks such that the distance between any two co-ordinates is no less than K.

    public static boolean[] getPeaks(int[] A) {

        boolean[] peaks = new boolean[A.length];

        for (int i = 1; i < A.length-1; i++) {

            if (A[i] > A[i-1] && A[i] > A[i+1]) {

                peaks[i] = true;

            } else {

                peaks[i] = false;

            }

        }

        return peaks;

    }

    public static int[] nextPeaks(int[] A) {

        int[] next = new int[A.length];

        boolean[] peaks = getPeaks(A);

        next[A.length-1] = -1;

        if (peaks[A.length-1]) next[A.length-1] = A.length-1;

        for (int i = next.length-2; i >= 0; i--) {

             if (peaks[i]) {

                 next[i] = i;

             } else {

                 next[i] = next[i+1];

             }

        }

        return next;

    }

    public static int countMaxFlagsOnPeaks(int[] A, int K) {

        int[] next = nextPeaks(A);

        int i = 1;

        int result = 0;

        for (int I =0; I < A.length; i++)

            int pos = i;

            int num = 0;

            while (pos < A.length && num < i) {

                int n = next[pos];

                if (n == -1) {

                    break;

                }

               If (n == pos && pos + 1 < next.length && next[pos+1] != -1 && next[pos+1] – pos  >=K) {

                num += 1;

               }

               // if bidirectional

               // If (n == pos && pos -1 >= 0 && pos - next[pos-1]  >= K) {

                // num +=1;

               // }

                pos = next[pos+1];

            }

            result = Math.max(result, num);

            System.out.println("i=" + i + " num=" + num + " result=" + result);

            // i+=1;

        }

        return result;

    }

A:          1,5,3,4,3,4,  1,  2,  3,  4,  6,  2

K:           1

peaks:0,1,0,1,0,1,  0,  0,  0,  0,  1,  0

next:    1,1,3,3,5,5,10,10,10,10,10,-1

i=1 num=3 result=3

i=3 num=3 result=3

i=5 num=3 result=3

i=10 num=3 result=3

3