Thursday, July 4, 2024

One of the convenient automations uses a well-known algorithm.

String matching algorithms: 


Void PrintMatch(String text, string pattern) 



Regex r = new Regex(pattern, options); 


Int[] gnums = r.GetGroupNumber(); 


Match m = r.Match(text); 


While (m.Success) 



Group g = m.Groups[gnums[i]]; 


CaptureCollection cc = g.Captures; 


For (int j = 0; j < cc.Count; j++) 



capture c = cc[j]; 


Console.WriteLine(“\t\tCapture{0} = [{1}] Index={2} and Length={3}”, j, c,c.Index, c.Length); 



m = m.NextMatch(); 



}


Wednesday, July 3, 2024

 A self organizing map algorithm for scheduling meeting times as availabilities and bookings.  A map is a low-dimensional representation of a training sample comprising of elements e. It is represented by nodes n. The map is transformed by a  regression operation to modify the nodes position one element from the model (e) at a time. With preferences translating to nodes and availabilities as elements, this allows the map to start getting a closer match to the sample space with each epoch/iteration.

from sys import argv


import numpy as np


from io_helper import read_xyz, normalize

from neuron import generate_network, get_neighborhood, get_boundary

from distance import select_closest, euclidean_distance, boundary_distance

from plot import plot_network, plot_boundary


def main():

    if len(argv) != 2:

        print("Correct use: python src/main.py <filename>.xyz")

        return -1


    problem = read_xyz(argv[1])


    boundary = som(problem, 100000)


    problem = problem.reindex(boundary)


    distance = boundary_distance(problem)


    print('Boundary found of length {}'.format(distance))



def som(problem, iterations, learning_rate=0.8):

    """Solve the xyz using a Self-Organizing Map."""


    # Obtain the normalized set of timeslots (w/ coord in [0,1])

    timeslots = problem.copy()

    # print(timeslots)

    #timeslots[['X', 'Y', 'Z']] = normalize(timeslots[['X', 'Y', 'Z']])


    # The population size is 8 times the number of timeslots

    n = timeslots.shape[0] * 8


    # Generate an adequate network of neurons:

    network = generate_network(n)

    print('Network of {} neurons created. Starting the iterations:'.format(n))


    for i in range(iterations):

        if not i % 100:

            print('\t> Iteration {}/{}'.format(i, iterations), end="\r")

        # Choose a random timeslot

        timeslot = timeslots.sample(1)[['X', 'Y', 'Z']].values

        winner_idx = select_closest(network, timeslot)

        # Generate a filter that applies changes to the winner's gaussian

        gaussian = get_neighborhood(winner_idx, n//10, network.shape[0])

        # Update the network's weights (closer to the timeslot)

        network += gaussian[:,np.newaxis] * learning_rate * (timeslot - network)

        # Decay the variables

        learning_rate = learning_rate * 0.99997

        n = n * 0.9997


        # Check for plotting interval

        if not i % 1000:

            plot_network(timeslots, network, name='diagrams/{:05d}.png'.format(i))


        # Check if any parameter has completely decayed.

        if n < 1:

            print('Radius has completely decayed, finishing execution',

            'at {} iterations'.format(i))

            break

        if learning_rate < 0.001:

            print('Learning rate has completely decayed, finishing execution',

            'at {} iterations'.format(i))

            break

    else:

        print('Completed {} iterations.'.format(iterations))


    # plot_network(timeslots, network, name='diagrams/final.png')


    boundary = get_boundary(timeslots, network)

    plot_boundary(timeslots, boundary, 'diagrams/boundary.png')

    return boundary


if __name__ == '__main__':

    main()


Tuesday, July 2, 2024

 This is a summary of the book titled “Decisions about Decisions” written by Cass R Sunstein and published by Cambridge UP in 2023. He studies how people think and proposes a set of useful decision-making strategies, including schemes that eliminate routine decisions, digs out relevant information, corrects unconscious biases and frees up by delegating to experts or algorithms. Since decision making involves emotions, it must be engineered to be straightforward. Information plays a complex role in decision making. Sometimes our beliefs are based on our decision to believe. Computer-based algorithms is ever-increasing second order decision making.

Decision-making can evoke strong emotions, which influence judgment. People have devised strategies to mitigate the emotional stress of making decisions, such as "second-order" strategies. These strategies include leaving the choice up to chance, setting rules that predetermine options, and breaking problems into smaller steps. Experts in economics, politics, and psychology view decision-making as a straightforward process, but also use second-order strategies to overcome obstacles.

There are three main types of second-order strategies: "high-low" strategies, which involve establishing protocols for routine issues, "low-low" strategies, which minimize the burdens faced throughout the decision-making process, "low-high" strategies, which delegate the choice to someone else, and "high-high" strategies, which produce high burdens both during preparation and decision-making.

Information plays a complex role in decision-making, as people often avoid irrelevant or potentially useful information. Decision-makers assess information's instrumental value, which enhances autonomy or power, and its "affective value," which evokes positive emotions.

People seek information for curiosity and to make life richer and more meaningful. Emotional reactions to good and bad news influence their decision to find news credible. People make internal predictions about the impact of new information on their feelings, but these predictions can be influenced by bias and cognitive quirks. People believe some ideas because they make them feel good, while others avoid information that contradicts their beliefs. People's willingness to hear bad news depends on whether they believe it can improve their condition. Many beliefs stem from a decision to believe, either consciously or unconsciously. Climate change illustrates the complex relationship between information and belief, with people responding differently to new information. Research on acceptance of beliefs about climate change demonstrates how people with different beliefs respond to new information, with those who strongly believe in anthropocentric climate change employing strategies of "asymmetrical updating."

Climate change is a growing threat, with people who strongly believe in its danger more accepting of bad news. Those less certain about its dangers use an "opposite asymmetry" and modify their beliefs when they encounter good news. A moderate belief in climate change gives the same weight to both good and bad news. People change their beliefs when the outcome of a new belief holds more value for them than the payoff for clinging to an old belief. Holding certain beliefs can lead to external and internal outcomes, either positive or negative. External outcomes include tangible consequences like financial rewards, while internal outcomes are cognitive or affective consequences. Policymakers should consider all possible outcomes when predicting or influencing people's beliefs. Fact-based efforts to counter "fake news" may fail as correcting inaccurate information threatens people's sense of well-being.

Consumer decisions are influenced by social dynamics, with people choosing products for both their inherent value and social value. Social goods include events consumed in groups or private, while exclusivity goods increase in value if only a limited number of people can enjoy them. Governments often promote and fund solidarity goods that enhance societal well-being, such as educational programming, sports teams, and public resources.

Using computer-based algorithms is a growing "second-order" decision-making strategy, but it can lead to prediction problems. Algorithms can be more effective than human beings at forecasting future conditions, but current offense bias can affect judgment. Algorithms can help judges avoid acting based on this bias.

Experts' judgment can falter due to availability bias, as they often rely on recent comparable situations, leading to mental shortcuts rather than thorough consideration of relevant statistics.

Previous book summary: BookSummary116.docx

Summarizing Software: https://1drv.ms/w/s!Ashlm-Nw-wnWhOYMyD1A8aq_fBqraA?e=aIsxa8    


Monday, July 1, 2024

 This is a summary of the book “Flip-flops and microwaved fish” written by Peter Yawitz and published by River Grove Books in 2022. The author hosts the podcast “Advice from someone else’s Dad.” and writes about workplace etiquette and that’s sure to help everyone. He illuminates unspoken rules of the office and provides handy advice such as get to know your co-workers, present yourself professionally, use small talk to avoid giving too much information, write clearly with good grammar, organize your material before meetings and take notes, practice and prepare to deliver impressive presentations, value diverse teams, muster your best manners at shared meals, respect personal boundaries and privacy, remain professional in any conflict and know when you need to take a break or quit.

To navigate a new workplace, it's essential to get to know your co-workers and learn about their communication styles. Direct communicators are preferred by businesses, but it may be better to support or encourage their ideas. Alternatively, a firm approach can be used when dealing with passive-aggressive colleagues.

Present yourself professionally, as it can determine how your co-workers and boss assess your value. Control your voice to enhance your message, such as observing others' interactions, speaking clearly, maintaining punctuality, dressing appropriately, maintaining a relaxed posture, and making eye contact. Avoid filler words and avoid filler words when speaking.

Use small talk to reduce anxiety and appear more approachable. Ask about the weather, their commute, sports, hobbies, and avoid close-ended questions. In a business setting, keep politics, sex, religion, or ethnicity out of the conversation.

Remember to modify your words and speaking style depending on your audience and their responses. Rephrasing certain details can help you maintain a professional tone and avoid misunderstandings.

To effectively communicate with co-workers, it is essential to write clearly and with good grammar. Develop an agreed-upon system for communication, organize data, focus on the target audience, clarify the context, and lay out what you need to say. Maintain a polite, helpful, specific, and kind tone while writing. Use active voice for better flow and maintain proper grammar.

Organize material before meetings and take notes to improve meeting productivity and efficiency. Adhere to rules such as avoiding meetings unless absolutely necessary, creating a plan with deadlines, assigning tasks to specific people, maintaining a moderate agenda, and agreeing on conduct rules. Arrive prepared, ready to listen, and take notes.

Practice and prepare to deliver impressive presentations by defining a clear goal, focusing on your specific audience, keeping content relevant, and including stories that connect emotionally to your message. Start with an introduction, avoid distracting language, and keep your message simple. Anticipate questions and prepare appropriate answers.

Speaking in front of people for the first time can produce anxiety, but take deep breaths, trust in your memory, and remember that you judge yourself more than your audience. The more you present, the easier it becomes, and you can move on to the next office challenge – working and presenting as a team.

To create a successful team, prioritize clear objectives, use a variety of personalities, and avoid micromanaging. Maintain good table manners and avoid gossiping about co-workers. When eating together, be thankful for free food and avoid expensive or time-consuming meals. Respect personal boundaries and privacy by keeping certain accounts private and others public for work. Avoid discussing religion, sex, politics, marital issues, or finances, and be cautious about what you say at office parties.

Remain professional in any conflicts, keeping a level head and holding emotions in check. Stick to the rules of basic human kindness and find ways to compromise within the situation. Ideally, companies should post a set of rules of conduct, but many don't, so create a standard of conflict resolution for your team. Start by sticking to facts and finding ways to compromise within the situation. Imagine the conflict from the other person's perspective to better understand and resolve it.

Addressing conflicts as they arise helps resolve touchy issues and improve relationships. Avoid involving yourself in conflicts that can't be avoided and focus on the most important issues. Seek HR attention for harassment, discrimination, or health issues. Take breaks when needed and have a plan in place. If you feel like a raise is due, present your accomplishments and data. Be smart when asking for a raise and avoid rudeness. If conflicts or difficult corporate cultures persist, quit gracefully, maintaining your networks and maintaining professional connections.

Previous book summaries: BookSummary115.docx 

Summarizing Software: SummarizerCodeSnippets.docx    


Sunday, June 30, 2024

 #codingexercise 

Get the max sum level in a binary tree

int GetMaxLevel(Node root, Node delimiter)

{

List<Integer> nodes = new ArrayList<>() :

if (root == null) return -1;

var q = new Queue<Node>();

q.Enqueue(root);

q.Enqueue(delimiter);

Nodes.add(root):

Nodes.add(delimiter);

var node = q.Dequeue();

while (node)

{

if (node == delimiter) {q.Enqueue(delimiter); nodes.add(delimiter);}

else{

if (node.left) {

      q.Enqueue(node.left) ;

      nodes.add(node.left) :

if (node.right) 

      q.Enqueue(node.right);

      nodes.add(node.right);

}

node = q.Dequeue();

}

var levels = nodes.split(delimiter);

int max  = INT_MIN;

int result =  0;

for (int level = 0; level < levels.Count; level++)

   if (levels[level].Sum > max)

          result = level;

return result;

}

     5

1 3 6 8

 2.    7

Result: 1


Saturday, June 29, 2024

 This is the summary of a book titled: “Becoming a changemaker” written by Alex Budak in 2022. Changemakers look optimistically towards the possibilities of future and empower themselves to lead the change. We must stop waiting for permission to do so in these times when changes are happening all around us and at a rapid pace. This book helps us assess our strengths and weaknesses to do so.

Changemakers are individuals who disrupt the status quo and identify opportunities at the intersection of disciplines. They are not afraid to challenge the status quo, take smart risks, and combine multiple perspectives to find the best solutions. They embrace hope and take action to create a brighter future. Changemakers cultivate "learned optimism," which means navigating challenges with the hope of creating a brighter future. They compartmentalize setbacks and recognize that adversity is temporary. To become a changemaker, one must commit to becoming one themselves, seek and collaborate with other changemakers, and assist others on their journeys. To assess their progress, one can take the Changemaker Index self-assessment annually, which measures five dimensions: "Changemaker awareness," "Changemaker mindset," "Changemaker leadership," "Changemaker action," and "Changemaker effectiveness." By assessing these dimensions, one can measure their progress and contribute to a broader impact on society.

To foster a changemaker's mindset, become a humble, flexible servant leader who is not afraid to fail. Humility is a significant strength, as it leads to less employee turnover, greater satisfaction, diverse managers, and larger profit margins. Humility is also less inclined to believe fake news, deal with uncertainty, and admit mistakes. To be a changemaker, embrace failure and prioritize the interests of those served above one's own. Develop a broad vision and be patient in achieving change, aiming to serve a compelling picture of the change over the next few decades.

To become a successful changemaker, one must have the courage to take action, even when feeling vulnerable. The "changemaker impact equation" helps determine the necessity of action by multiplying actions by leadership and mindset. Develop the art of agency, which allows for frustration and hopelessness while knowing that even inaction is an action. Take small steps to get your project rolling and view obstacles with a fresh perspective. Channel your courage into action by finding people who believe in your message and act as early champions. Break down your goals into manageable blocks using the Changemaker Canvas.


For example, write a concise, clear vision for your desired change, identify your core problem, and understand the Four S's of change. Test your ideas using the lean start-up model and plan strategies to ensure resilience. Collaborate with collaborators, such as "doers" and "evangelists," and embrace the appropriate mindset and leadership approach. Put everything learned into action by leveraging strengths like optimism and the desire to serve.

Previous book summary: BookSummary114.docx

Summarizing Software: SummarizerCodeSnippets.docx    

 


Friday, June 28, 2024

 This is a continuation of IaC shortcomings and resolutions. In Azure, a storage account without private endpoints can be accessed by compute resources that do not have public IP addresses through the use of Azure's internal networking capabilities. Here's how it works:

1. Virtual Network (VNet): Both the storage account and the compute resources reside within an Azure VNet, which is a private network within Azure.

2. Service Endpoints: While private endpoints are not used, we can enable service endpoints for Azure Storage within the VNet. This allows us to secure our storage account so that it can only be accessed from specific subnets within the VNet.

3. Network Security Groups (NSGs): NSGs are used to control inbound and outbound traffic to network interfaces (NIC), VMs, and subnets. We can configure NSGs to allow traffic between the compute resources and the storage account within the VNet.

4. Azure Bastion: For secure, remote access to the compute resources from outside the VNet, we can use Azure Bastion, which provides RDP and SSH connectivity via the Azure portal without the need for public IP addresses.

5. VPN Gateway or ExpressRoute: To connect to the Azure VNet from on-premises networks securely, we can use a VPN Gateway or ExpressRoute with private peering. This allows on-premises compute resources to access the Azure storage account as if they were part of the same local network.

6. DNS Configuration: Proper DNS configuration is necessary to resolve the names of the storage account for the compute resources within the Azure VNet. Azure provides DNS services that can be used for name resolution within VNets. A compute resource from a different virtual network can reach the storage account via the private endpoint, provided the necessary dns configuration is in place and the virtual networks are peered or there is line-of-sight private ip routing between the caller and the callee.

7. Outbound Connectivity: If the compute resources need to access the internet, we can configure outbound connectivity using Azure NAT Gateway or Load Balancer outbound rules, even if the compute resources don't have public IP addresses.

By configuring the VNet, NSGs, and DNS settings correctly, and using service endpoints, we can ensure that compute resources without public IP addresses can securely access an Azure storage account without private endpoints. This setup maintains the security and isolation of our resources within Azure while allowing necessary communication between them.