Saturday, December 9, 2023

Number of Ways to Split Array

 


You are given a 0-indexed integer array nums of length n.

nums contains a valid split at index i if the following are true:

  • The sum of the first i + 1 elements is greater than or equal to the sum of the last n - i - 1 elements.
  • There is at least one element to the right of i. That is, 0 <= i < n - 1.

Return the number of valid splits in nums.

 

Example 1:

Input: nums = [10,4,-8,7]

Output: 2

Explanation:

There are three ways of splitting nums into two non-empty parts:

- Split nums at index 0. Then, the first part is [10], and its sum is 10. The second part is [4,-8,7], and its sum is 3. Since 10 >= 3, i = 0 is a valid split.

- Split nums at index 1. Then, the first part is [10,4], and its sum is 14. The second part is [-8,7], and its sum is -1. Since 14 >= -1, i = 1 is a valid split.

- Split nums at index 2. Then, the first part is [10,4,-8], and its sum is 6. The second part is [7], and its sum is 7. Since 6 < 7, i = 2 is not a valid split.

Thus, the number of valid splits in nums is 2.

Example 2:

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

Output: 2

Explanation:

There are two valid splits in nums:

- Split nums at index 1. Then, the first part is [2,3], and its sum is 5. The second part is [1,0], and its sum is 1. Since 5 >= 1, i = 1 is a valid split.

- Split nums at index 2. Then, the first part is [2,3,1], and its sum is 6. The second part is [0], and its sum is 0. Since 6 >= 0, i = 2 is a valid split.

 

Constraints:

  • 2 <= nums.length <= 105
  • -105 <= nums[i] <= 105

 

Solution:

class Solution {

    public int waysToSplitArray(int[] nums) {

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

        int sumSoFar = 0;

        int total = 0;

        int count = 0;

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

            total += nums[i];

        }

 

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

            sumSoFar += nums[i];

            if (sumSoFar >= total-sumSoFar) {

                count += 1;

            }

        }

        return count;

    }

}

 

Test  cases:

[0] => 0

[1] => 0

[0,1] => 0

[1,0] => 1

[0,0,1] => 0

[0,1,0] => 1

[0,1,1] => 1

[1,0,0] => 2

[1,0,1] => 2

[1,1,0] => 2

[1,1,1] => 1

 

 

 

 

 

Thursday, December 7, 2023

 

Applying MicrosoftML rxLogisticRegression algorithm:  

 

While rxNeuralNet is a neural network implementation that helps with multi class classification and regression, Logistic Regression helps with binary outcomes. rxLogisticRegression is a binary and multiclass classification that classifies sentiments from feedback. This is a regular regression model where the variable that determines the category is dependent on one or more independent variables that have a logistic distribution.

 

This form of regression uses statistical measures, is highly flexible, takes any kind of input and supports different analytical tasks. This regression folds the effects of extreme values and evaluates several factors that affect a pair of outcomes.  Regression is very useful to calculate a linear relationship between a dependent and independent variable, and then use that relationship for prediction. Errors demonstrate elongated scatter plots in specific categories. Even when the errors come with different error details in the same category, they can be plotted with correlation. This technique is suitable for specific error categories from an account.   

 

Default detection rates can be boosted, and false positives can be reduced using real-time behavioral profiling as well as historical profiling. Big Data, commodity hardware and historical data going as far back as three years help with accuracy. This enables payment default detection to be almost as early as when it is committed. True real time processing implies stringent response times.

 

The algorithm for the least squares regression can be written as:   

 

1. Set the initial approximation    

 

2. For a set of successive increments or boosts each based on the preceding iterations, do   

 

3. Calculate the new residuals   

 

4. Find the line of search by aggregating and minimizing the residuals   

 

5. Perform the boost along the line of search   

 

6. Repeat 3,4,5 for each of 2.  

 

Conjugate gradient descent can be described with a given input matrix A, b, a starting value x, a number of iterations i-max and an error tolerance  epsilon < 1 in this way:

 

set I to 0        

set residual to b - Ax     

set search-direction to residual.    

And delta-new to the dot-product of residual-transposed.residual.    

Initialize delta-0 to delta-new    

while I < I-max and delta > epsilon^2 delta-0 do:     

    q = dot-product(A, search-direction)    

    alpha = delta-new / (search-direction-transposed. q)     

    x = x + alpha.search-direction    

    If I is divisible by 50     

        r = b - Ax     

    else     

        r = r - alpha.q     

    delta-old = delta-new    

    delta-new = dot-product(residual-transposed,residual)    

    Beta = delta-new/delta-old    

    Search-direction = residual + Beta. Search-direction    

    I = I + 1 

 

Sample application:  

#! /bin/python  
import numpy
import pandas
from microsoftml import rx_logistic_regression, rx_predict
from revoscalepy.etl.RxDataStep import rx_data_step
from microsoftml.datasets.datasets import get_dataset
infert = get_dataset("infert")

import sklearn
if sklearn.__version__ < "0.18":
    from sklearn.cross_validation import train_test_split
else:
    from sklearn.model_selection import train_test_split

infertdf = infert.as_df()
infertdf["isCase"] = infertdf.case == 1
data_train, data_test, y_train, y_test = train_test_split(infertdf, infertdf.isCase)

model = rx_logistic_regression(
    formula=" isCase ~ age + parity + education + spontaneous + induced ",
    data=data_train)
print(model.coef_)   

# RuntimeError: The type (RxTextData) for file is not supported.
score_ds = rx_predict(model, data=data_test,
                     extra_vars_to_write=["isCase", "Score"])                    

# Print the first five rows
print(rx_data_step(score_ds, number_rows_read=5))

 

Wednesday, December 6, 2023

Largest Number At Least Twice of Others

 


There is an integer array nums where the largest integer is unique.

The task is to determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1 otherwise.

 

Example 1:

Input: nums = [3,6,1,0]

Output: 1

Explanation: 6 is the largest integer.

For every other number in the array x, 6 is at least twice as big as x.

The index of value 6 is 1, so we return 1.

Example 2:

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

Output: -1

Explanation: 4 is less than twice the value of 3, so we return -1.

 

Constraints:

  • 2 <= nums.length <= 50
  • 0 <= nums[i] <= 100
  • The largest element in nums is unique.

 

class Solution {

    public int dominantIndex(int[] nums) {

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

        Arrays.sort(nums);

        int max = nums[nums.length-1];

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

            if ( 2 * nums[i] > max) {

                return -1;

            }

        }

        return 1;

    }

}

Test cases: [0]=>1, [0,1,2] => 1, [0,1,0] => 1, [-1,0,1] => 1, [0,0] =>-1, [-4,-3,-2,-1] => 1

https://1drv.ms/w/s!Ashlm-Nw-wnWhNNPo73BVh-_5icutw?e=lPqYlv

Monday, December 4, 2023

 

The following is a case study for an automation involving a web request.

A PowerShell script written to invoke a remote method by sending a web request works find when executed locally on a PowerShell Terminal but fails to run the command when the script is part of an automation workflow aka runbook. The error encountered is “Name or service not known.” even though the remote method is hosted in an app service. If the app service were denying the request, a 403 statuscode might have appeared in the error but this is not the case. The request does not reach the target. The following article explains how to diagnose this situation.

Before we begin diagnosing the specific cmdlet, it is important to check that the associated module is imported. This can be done with `ipmo Microsoft.PowerShell.Utility` directive. It is also necessary to ensure that the execution policy of the script permits the call. This can be relaxed with `Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force -Scope Process` command. Also, the logged in user or identity making the call must have the necessary permissions to do so or assign the web app contributor role to the principal.

First, the automation, by its nature, cannot be interactive, so the parameters must be checked to include an option to progress without involvement. For example, the $progressPreference = “silentlyContinue” may help here.

Second, the parameter to debug the call might yield more information than regular invocation. The ‘-Debug’ parameter, for example, may indicate that the TLS handshake failed which resulted in the call not going through. It could also indicate a timeout in getting a response when the request was valid indicating other reasons why the call could not go through.

When the TLS handshake fails, it might most likely arise from the certificate validation. A caller making a web request can choose to skip the validation when the method is to a target that falls under the control of the owner owning the automation as well as the app service.  A PowerShell method to trust all certificates might be something as simple as:

add-type @"

    using System.Net;

    using System.Security.Cryptography.X509Certificates;

    public class TrustAllCertsPolicy : ICertificatePolicy {

        public bool CheckValidationResult(

            ServicePoint srv, X509Certificate certi,

            WebRequest req, int certificateIssue) {

            return true;

        }

    }

"@

[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

 

A try-catch handler around the request can also indicate not only the exception but also other modules that might be involved in the request from the associated stacktrace. For example,

try {

    Invoke-RestMethod -Method Get -Uri APISERVER/api/v1/namespaces/default/pods/ -Headers $headers

}

catch {

    $_.Exception | Format-List -Force

}

may indicate the error when it would otherwise be omitted from the logs.

It is also possible that the target might not be reachable over the network and this can be diagnosed with:

$DnsCheck = Resolve-DnsName $uri -ErrorAction SilentlyContinue

Similarly, other parameters to the web-request can also help here such as –UseBasicParsing to indicate that this is not a web request from a browser, -Proxy ‘http://w.x.y.z:80’ -ProxyCredential $creds where the credentials are obtained from $creds = New-AzADSpCredential -ServicePrincipalName <ServicePrincipalName> and specifying the method such as with -Method GET.

These are some of the ways in which the web request can be made to succeed.