Thursday, April 17, 2025

 Always pertinent:

Problem: determine if a graph has cycles:

import java.util.*;

import java.lang.*;

import java.io.*;

class Ideone

{

 public static void main (String[] args) throws java.lang.Exception

 {

  int[][] m = new int[5][5]();

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

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

    m[i][j] = 0;

   }

  }

  m[0][1] = 1;

  m[0][2] = 1;

  m[1][0] = 1;

  m[1][3] = 1;

  m[2][0] = 1;

  m[2][3] = 1;

  m[3][1] = 1;

  m[3][2] = 1;

  m[3][4] = 1;

  m[4][3] = 1;

  var vertices = InitializeSingleSource(m, 0);

  var edges = new HashMap<String, String>();

  edges.put("A", "B");

  edges.put("A", "C");

  edges.put("B", "A");

  edges.put("B", "D");

  edges.put("C", "A");

  edges.put("C", "D");

  edges.put("D", "B");

  edges.put("D", "C");

  edges.put("D", "E");

  edges.put("E", "D");

  System.out.println(hasCyclesByBellmanFord(vertices, edges));

 }

 private static List<Vertex> InitializeSingleSource(int[][] m, int start) {

  var vertices = new ArrayList<Vertex>();

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

   var v = new Vertex();

   v.id = String.valueOf(Character.valueOf('A' + i));

   v.d = Integer.MAX_VALUE;

   if (i == start) { v.d = 0; }

   v.parent = null;

  }

  return vertices

 }

 private static Vertex getVertex(List<Vertex> vertices, String id){

  for (int i = 0; i < vertices.size(); i++){

   if (vertices.get(i).id.equals(id)){

    return vertices.get(i);

   }

  }

  return null;

 }

 // A ->C <-D ->E

 // ->B->

 private static boolean hasCyclesByBellmanFord(List<Vertex> vertices, Map<String, String> edgeMap) {

  boolean result = false;

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

   for(var entry: edgeMap.entrySet()) {

    var u = getVertex(entry.getKey());

    var v = getVertex(entry.getValue());

    relax(u, v);

   }

  }

  for (var entry: edgeMap.entrySet()) {

   var u = getVertex(entry.getKey());

   var v = getVertex(entry.getValue());

   if (u != null &&

    v != null &&

    v.d > u.d + 1) {

    result = true;

    return result;

   }

  }

  return result;

 }

 private static void Relax(Vertex u, Vertex v) {

  if (u == null || v == null) { return; }

  if (v.d > u.d + 1) {

   v.d = u.d + 1;

   v.parent = u;

  }

 }

 class Vertex {

  public String id;

  public Vertex parent;

  public Integer d;

 }

}


Wednesday, April 16, 2025

 Secure-by-design

The boundary between infrastructure and application engineering is one where the concerns for security are played differently. Application engineering focuses on architecture with boundaries such that the some of the resources are considered within trust boundary. The infrastructure engineering implements security with network perimeter protection and defense-in-depth strategy such that even the internal or hidden-from-world resources enjoy a certain level of protection. Both sides cannot deny the need to upskill and leverage the tools available. Developers must be trained in secure coding and infrastructure engineers must hold them true to it. Proficiency in using approved tools and establishing and maintaining effective oversight and administration go hand in hand.

With a sprawl in digital landscape of resources. tools, frameworks and platforms used to host data and run code, organizations often find it hard to benchmark their security against industry standards. “Embracing security and resilience by design” is indeed a challenge and progress to meet it must be tracked. CISA has published pivotal guidelines on the subject. One of the techniques frequently used is the Secure Code Warrior’s “Trust Score” technology which opens a new frontier of actionable security insights and benchmarking.

Cybersecurity is a discipline, and it is dynamic. While it was a $2 billion industry in the 90’s dominated by transaction systems, it is now over $2 trillion with an insatiable demand for products, services and AI applications. Virtually every company writes code in some way. Organizations have grappled with bringing security upfront into SDLC amidst cultural resistance and disagreements while having AppSec professionals deplete with a high rate of burnout. Movements like “shift left” have attempted to correct this. But accountability continues to be a sticking point at all levels and scopes. Case in point is the CrowdStrike introduced defect that affected Airlines industry. Oversight and management of software development processes must ensure Secure-by-Design is front-of-mind and achievable for each deployment.

Some of the tenets include: “Provide secure defaults for developers” with the default route during software development as one that is “paved road” or “well-lit path” and “Foster a software developer workforce that understands security” by training them on the best practices and including security education into the hired skillset. Developers need to be enabled through continuous precision learning pathways and tools to suit their tech stack and to share the responsibility for security.


Tuesday, April 15, 2025

 This is a summary of the book titled “The Yellow Pad” written by Robert E. Rubin and published by Penguin Press in 2023. The author is a former Goldman Sachs Executive and US Secretary of the Treasury who discusses how to navigate difficult, controversial decisions saying that he learned it requires adhering to specific principles. He also found that one must always recognize the unpredictable human element, since no event ever unfolds exactly as planned. He brings his knowledge and experience to this framework of principles. A prisoner’s insights made a lasting impact on him. In his work, he learned that risk management demands acknowledging the remotest possibilities. Mental toughness enables strong leaders to overcome bumps in the road and great leaders are curious, authentic, and true to their beliefs. A retrospective view provides clarity and fosters more effective decision-making.

He was impressed by the forthrightness of prisoners about their crimes and the importance of pause, assessment, and weighing the possible repercussions of their actions. He believed that making informed decisions amid intense upheaval requires special skill and discipline. Rubin emphasized the importance of understanding one's emotional biases and regulating them during risky crunch times. He also compared the late 20th century to the time when Vice President Al Gore warned of the dangers of global warming. Rubin and Henry Paulson, former treasury secretary under President George W. Bush, approached the Securities and Exchange Commission to advocate for financial establishments to openly acknowledge the possible costs of global warming. They believed that if more leaders around the world had thought about the issue like Al Gore, the world today would be a safer place.

Mental toughness is crucial for strong leaders to overcome challenges and maintain confidence in their decision-making abilities. They are resilient and embrace optimism, which is important within organizations. Successful leaders are known for their resilience, especially in response to public criticism. They are also known for their energetic curiosity, which leads them to take a skeptical approach and search for answers beyond obvious conclusions. Authenticity is a character trait that serves leaders well, as it allows them to explore the world around them. Being true to oneself requires consistency, even when it means disagreeing with others' opinions. Traditional management often overlooks the human element, as seen in the case of Lawrence Bossidy's management philosophy. Rubin prefers to focus on people's individuality and uniqueness, rather than specific rules and detailed lists of do's and don'ts. Despite their skepticism, leaders like Rubin can be talented and perceptive, making them valuable assets in their organizations.

Good executives prioritize the best interests of their organizations, ignoring personal feelings and fostering empathetic and patient decision-making. They credit their employees for department successes, accept blame when things go wrong, and are open to feedback from everyone. Organizational culture influences employee success, and leaders must avoid deviating from their foundational values. Success accrues upward, reflecting well on the leader. Analyzing past actions helps make informed decisions moving forward. In some cases, carefully considered decisions can still generate negative results. Intellectual openness creates an environment where people can work with leaders to make the best decisions. However, organizations often assign blame, leaving employees without valuable input. Chastising, blaming, or unfairly punishing people for making honest mistakes can fuel an unhealthy culture. Rubin seldom states his negative judgments of anyone's actions in public, as long as the people who made poor decisions undertake unflinching reviews of how their actions led to unsatisfactory outcomes.


Monday, April 14, 2025

 Comparision between CNN-LSTM and Logistic Regression

Deep Learning has shown superior performance in object detection and image classification in drone imageries. Logistic Regression shows superior prediction with drone telemetry data. While they serve different purposes, they can be compared on a common use case for predicting deviation from trajectory and compensation based on past orientations and current. The cost function in the CNN-LSTM is a mean squared error. CNN-LSTM uses the vectorized output of edge-detected and gaussian-smoothed images captured sequentially from video to predict the next steering angle of the drone. But the same data can be emitted as telemetry along with additional telemetry from edge detections, trajectory and squared errors and their corresponding vectors can then be run through Logistic Regression as shown below:Sample usage of Logistic Regression:

#! /bin/python

import matplotlib.pyplot as plt

import pandas

import os

here = os.path.dirname(__file__) if "__file__" in locals() else "."

data_file = os.path.join(here, "data", "flight_errors", "data.csv")

data = pandas.read_csv(data_file, sep=",")

# y is the last column and the variable we want to predict. It has a boolean value.

data["y"] = data["y"].astype("category")

print(data.head(2))

print(data.shape)

data["y"] = data["y"].apply(lambda x: 1 if x == 1 else 0)

print(data[["y", "X1"]].groupby("y").count())

try:

    from sklearn.model_selection import train_test_split

except ImportError:

    from sklearn.cross_validation import train_test_split

train, test = train_test_split(data)

import numpy as np

from microsoftml import rx_fast_trees, rx_predict

features = [c for c in train.columns if c.startswith("X")]

model = rx_fast_trees("y ~ " + "+".join(features), data=train)

pred = rx_predict(model, test, extra_vars_to_write=["y"])

print(pred.head())

from sklearn.metrics import confusion_matrix

conf = confusion_matrix(pred["y"], pred["PredictedLabel"])

print(conf)

def train_test_hyperparameter(trainA, trainB, **hyper):

    # Train a model

    features = [c for c in train.columns if c.startswith("X")]

    model = rx_fast_trees("y ~ " + "+".join(features), data=trainA, verbose=0, **hyper)

    pred = rx_predict(model, trainB, extra_vars_to_write=["y"])

    conf = confusion_matrix(pred["y"], pred["PredictedLabel"])

    return (conf[0,0] + conf[1,1]) / conf.sum()

trainA, trainB = train_test_split(train)

hyper_values = [5, 10, 15, 20, 25, 30, 35, 40, 50, 100, 200]

perfs = []

for val in hyper_values:

    acc = train_test_hyperparameter(trainA, trainB, num_leaves=val)

    perfs.append(acc)

    print("-- Training with hyper={0} performance={1}".format(val, acc))

import matplotlib.pyplot as plt

fig, ax = plt.subplots(1, 1)

ax.plot(hyper_values, perfs, "o-")

ax.set_xlabel("num_leaves")

ax.set_ylabel("% correctly classified")

tries = max(zip(perfs, hyper_values))

print("max={0}".format(tries))

model = rx_fast_trees("y ~ " + "+".join(features), data=train, num_leaves=tries[1])

pred = rx_predict(model, test, extra_vars_to_write=["y"])

conf = confusion_matrix(pred["y"], pred["PredictedLabel"])

print(conf)


Sunday, April 13, 2025

Emerging trends and regulations in UAV swarms

The units in a full-fledged, safe and autonomous swarm are comprised of drones and when the entire swarm is homogeneous, the adherence to Federal Aviation Administration (FAA)'s Small UAS Rule (Part 107) is sufficient to clear.  This regulation mandates the following from the drones:

  • Drone Weight: Must weigh less than 55 pounds, including payload.
  • Visual Line of Sight (VLOS): The drone must remain within the operator's unaided visual line of sight.
  • Daylight Operations: Flights are allowed during daylight or twilight (with anti-collision lighting).
  • Maximum Altitude: Cannot exceed 400 feet above ground level unless within 400 feet of a structure.
  • Maximum Speed: Limited to 100 mph (87 knots).
  • Airspace Restrictions: Operations in controlled airspace require prior FAA authorization.
  • No Flying Over People: Unless they are directly involved in the operation.
  • No Moving Vehicles: Cannot operate from a moving vehicle unless in a sparsely populated area.
  • Weather Visibility: Minimum visibility of 3 miles from the control station.
  • Pilot Certification: Operators must hold a Remote Pilot Certificate or be supervised by someone who does.
  • Registration: All drones must be registered with the FAA.

For example, Amazon's drone delivery system, known as Prime Air, is designed to deliver packages weighing up to 5 pounds within 30 minutes. The drones are fully electric and incorporate advanced aerospace standards to ensure safety and reliability such as  Part 135 Air Carrier Certificate from the FAA as well as the FAA Part 107. The drones are equipped with a sophisticated sense-and-avoid system that enables them to detect and navigate around obstacles, both static (like chimneys) and dynamic (like other aircraft). This system uses proprietary algorithms for object detection and decision-making, ensuring safe operations even in unexpected situations. The algorithms leverage a diverse suite of object detection technologies to identify obstacles and adjust flight paths accordingly. During the delivery descent, the drones can detect and avoid smaller obstacles like trampolines or clotheslines that might not be visible in satellite imagery. An automated drone-management system is being developed to plan the flight paths and ensure there are safe distances between the aircraft and other aircraft in the area, and that all aviation regulations are complied with.

The autonomous drone delivery system features a deep learning autonomous drone model built using CNN-LSTM algorithms. It includes functionalities like online purchasing, drone delivery processing, and real-time location tracking. CNN-LSTM algorithms combine Convolutional Neural Networks (CNNs) and Long Short-Term Memory (LSTM) networks to handle tasks involving spatial and temporal data.CNNs are excellent for extracting spatial features from data, such as images or spectrograms. They use convolutional layers to identify patterns like edges, textures, or shapes. LSTMs are a type of Recurrent Neural Network (RNN) designed to capture temporal dependencies in sequential data. They excel at learning long-term relationships, making them ideal for tasks like time-series analysis or speech recognition.CNN layers process spatial data to extract features. These features are then passed to LSTM layers, which analyze the temporal relationships between them. This combination allows the model to understand both spatial and temporal aspects of the data, making it highly effective for tasks like video analysis, activity recognition, and speech emotion detection. This technique can help with generating textual descriptions of video sequences, identifying actions in a sequence of images and classifying emotions from audio spectrograms.

Amazon's CNN-LSTM predictor makes use of Gaussian and Edge detection preprocessing functions from image processing libraries for Steering Angle Dataset exploration.  Yolov3 bounding boxes architecture is used to find bounding boxes of cars, people, and trees in the image dataset. These bounding boxes were used by their probability model to calculate the probability of collision. Weight determination functions were used to calculate the probability of colliding into any given object. A pilot script is used to fly the drone.


Saturday, April 12, 2025

 Emerging Trends of AI in Autonomous Business: 


The digital business era is maturing, with industry-leading enterprises seeking the next technology-enabled business growth curve. Autonomous business is a style of business partly governed and majority-operated by self-learning software agents, providing smart products and services to machine-customer-prevalent markets in a programmable economy. Executive leaders should factor autonomous business concepts into their long-range business strategy cycle, identify early "land grabs" needed to secure a competitive foothold, and pay attention to the possible arrival of machine customers in markets. The concept of autonomous business is still emerging, and its contours may assume a different market term in the future. It is characterized by a style of business partly governed and majority-operated by self-learning software agents, providing smart products and services to machine-customer-prevalent markets. Examples of autonomous business include fingerprint recognition door locks, people-tracking camera drones, voice assistants and chatbots. 


Operating in a programmable economy involves organizations trading with customers and other entities via blockchain decentralized ledgers, using smart contracts and digital tokens for value exchanges. This evolution of autonomous business will not be fundamentally dehumanizing, but it will lead to a four-day workweek in advanced economies, but not mass unemployment and societal crises. The definition of autonomous business is indicative rather than absolute, and it follows from prior evolutionary stages of digital and information-technology-enabled business capability and strategic value focus. Autonomous business builds on the prior phases, which will continue to grow and add value, even if their progress rate slows as autonomous business matures. It will rely heavily on golden thread business technology capacities, such as composability, that have helped weave the previous eras and continue to evolve and advance. 


The next era, "metaversal business," is expected to emerge from the integration of people into cyberspace, blurring the boundary between humans and machines. However, widespread deep immersion in cyberspace is unlikely, and direct interfacing is unlikely before the 2040s. Autonomous business will become a significant macro business technology concept in industries like mining, financial services, automotive, aerospace, defense, smart cities, medicine, research, higher education, and entertainment. It will depend on technologies that are already available and rapidly advancing, and will involve machine-controlled operations, augmented governance, and interaction with customers and other businesses through blockchain-enabled mechanisms. The programmable economy, based on distributed and decentralized digital resources, supports the production and consumption of goods and services, enabling innovation, entrepreneurship, and value exchange among humans and machines. 


#codingexercise: https://1drv.ms/w/c/d609fb70e39b65c8/EYMCYvb9NRtOtcJwdXRDUi0BVzUEyGL-Rz2NKFaKj6KLgA?e=fBM3eo

Friday, April 11, 2025

 #codingexercise

Problem: A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:

Every adjacent pair of words differs by a single letter.

Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.

sk == endWord

Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].

 

Example 1:

Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]

Output: [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]]

Explanation: There are 2 shortest transformation sequences:

"hit" -> "hot" -> "dot" -> "dog" -> "cog"

"hit" -> "hot" -> "lot" -> "log" -> "cog"


Example 2:

Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]

Output: []

Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.


 

Constraints:

1 <= beginWord.length <= 5

endWord.length == beginWord.length

1 <= wordList.length <= 500

wordList[i].length == beginWord.length

beginWord, endWord, and wordList[i] consist of lowercase English letters.

beginWord != endWord

All the words in wordList are unique.

The sum of all shortest transformation sequences does not exceed 105.

class Solution {

    public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {

        List<List<String>> results = new ArrayList<List<String>>();

        var q = new LinkedList<String>();

        var s = new HashSet<String>(wordList);

        q.add(beginWord);

        var result = new ArrayList<String>();

        combine(beginWord, endWord, s, results, result);

    

        var minOpt =  results.stream().filter(x -> x.get(0).equals(beginWord)).mapToInt(x -> x.size()).min();

        if (minOpt.isPresent()) {

            var min = minOpt.getAsInt();

            results = results.stream().filter(x -> x.size() == min).collect(Collectors.toList());

        }

        

        return results;

    }



    private static void combine(String top, String endWord, HashSet<String> s,  List<List<String>> results, List<String> result)

    {

            if (top.equals(endWord)) {

                return;

            }

            result.add(top);

            char[] chars = top.toCharArray();

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

            {

                for (char c = 'a'; c <= 'z'; c++)

                {

                    char temp = chars[i];

                    if (temp != c) {

                        chars[i] = c;

                    }



                    String candidate = new String(chars);

                    if (s.contains(candidate) && !result.contains(candidate)) {

                        var clone = new ArrayList<String>(result);

                        if (candidate.equals(endWord)) {

                            clone.add(candidate);

                            results.add(clone);

                        } else {

                            combine(candidate, endWord, s, results, clone);

                        }

                    }

                    chars[i] = temp;

                }

            }

            result.remove(top);

    }

}

Test cases:

1.

Input

beginWord =

"hit"


endWord =

"cog"


wordList =

["hot","dot","dog","lot","log","cog"]


Output

[["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]]


Expected

[["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]]


2.

Input

beginWord =

"hit"


endWord =

"cog"


wordList =

["hot","dot","dog","lot","log"]


Output

[]


Expected

[]