问:
Multidimensional Array as Variables to save in dB
I have a multidimensional array

```<code>output_querys =  array(2) { [0]=> array(5) { ["ID"]=> string(1) "2" ["Code"]=> string(6) "AWS001" ["BCode"]=> string(4) "B001" ["Des"]=> string(4) "loan" ["subCat"]=> string(3) "SWA" } [1]=> array(5) { ["ID"]=> string(1) "4" ["Code"]=> string(6) "AWS002" ["BCode"]=> string(4) "B002" ["Des"]=> string(3) "tax" ["subCat"]=> string(3) "PJA" } }

</code>```

I want to get this to a variable and then save into dB.I have tried all the methods that has mentioned in related problems nothing worked.
Errors I got
1.trying non-object
2.Illegal string offset

what I was trying to do is

```<code>foreach($output_querys as $output_query){
  $Pv_ID = $output_query->ID;
   $Pv_Code = $output_query->Code;
      $Pv_Description = $output_query->Des;

    $data_final = array(id => $Pv_ID, code => $Pv_Code, des => $Pv_Description);

      }
      db->insert(abc, $data_final);
</code>```

what is the problem here??.even i tried with json encode and still shows the "Illegal string offset"

```<code>        $Pv_ID= json_decode($output_query['ID']);

        $Pv_Code = json_encode($output_query['Code'],true);

        $Pv_Description = json_encode($output_query['Des'],true);

</code>```

答:
I tried your given array and code

```<code>    <?php
  $output_querys = array(
    0 => array(
            "ID" => "2",
            "Code" => "AWS001",
            "BCode" => "B001",
            "Des" => "loan",
            "subCat" => "SWA"
    ),
    1 => array(
            "ID" => "4",
            "Code" => "AWS002",
            "BCode" => "B002",
            "Des" => "tax",
            "subCat" => "PJA"
        )
);
  foreach($output_querys as $output){
    print_r($output['Code']); echo "\n";

  }
?>
</code>```

It is working fine on my end. Here's the working example

I think you need to do this as well, if you want to insert 1 by 1 then move the insert in foreach loop

```<code>foreach($output_querys as $output_query){
  $Pv_ID = $output_query->ID;
   $Pv_Code = $output_query->Code;
      $Pv_Description = $output_query->Des;

    $data_final = array(id => $Pv_ID, code => $Pv_Code, des => $Pv_Description);
     db->insert(abc, $data_final);
      }

</code>```

Body:
I have a multidimensional array

output_querys =  array(2) { [0]=> array(5) { ["ID"]=> string(1) "2" ["Code"]=> string(6) "AWS001" ["BCode"]=> string(4) "B001" ["Des"]=> string(4) "loan" ["subCat"]=> string(3) "SWA" } [1]=> array(5) { ["ID"]=> string(1) "4" ["Code"]=> string(6) "AWS002" ["BCode"]=> string(4) "B002" ["Des"]=> string(3) "tax" ["subCat"]=> string(3) "PJA" } }

I want to get this to a variable and then save into dB.I have tried all the methods that has mentioned in related problems nothing worked.
Errors I got
1.trying non-object
2.Illegal string offset

what I was trying to do is

foreach($output_querys as $output_query){
  $Pv_ID = $output_query->ID;
   $Pv_Code = $output_query->Code;
      $Pv_Description = $output_query->Des;

    $data_final = array(id => $Pv_ID, code => $Pv_Code, des => $Pv_Description);

      }
      db->insert(abc, $data_final);

what is the problem here??.even i tried with json encode and still shows the "Illegal string offset"

        $Pv_ID= json_decode($output_query['ID']);

        $Pv_Code = json_encode($output_query['Code'],true);

        $Pv_Description = json_encode($output_query['Des'],true);

Body:
I tried your given array and code

    <?php
  $output_querys = array(
    0 => array(
            "ID" => "2",
            "Code" => "AWS001",
            "BCode" => "B001",
            "Des" => "loan",
            "subCat" => "SWA"
    ),
    1 => array(
            "ID" => "4",
            "Code" => "AWS002",
            "BCode" => "B002",
            "Des" => "tax",
            "subCat" => "PJA"
        )
);
  foreach($output_querys as $output){
    print_r($output['Code']); echo "\n";

  }
?>

It is working fine on my end. Here's the working example

I think you need to do this as well, if you want to insert 1 by 1 then move the insert in foreach loop

foreach($output_querys as $output_query){
  $Pv_ID = $output_query->ID;
   $Pv_Code = $output_query->Code;
      $Pv_Description = $output_query->Des;

    $data_final = array(id => $Pv_ID, code => $Pv_Code, des => $Pv_Description);
     db->insert(abc, $data_final);
      }


来源: stackexchange

问:
Trying to import scikit-learn to PyCharm on Mac M1
I wanted to install the sklearn package in PyCharm. However, I always got the same error (below is an extract):

```<code>pip install scikit-learn  # input

Collecting scikit-learn
  Using cached scikit-learn-1.0.2.tar.gz (6.7 MB)
  Installing build dependencies ... error
  error: subprocess-exited-with-error

  × pip subprocess to install build dependencies did not run successfully.
  │ exit code: 1
  ╰─> [148 lines of output]
      Ignoring numpy: markers 'python_version == "3.7" and platform_machine != "aarch64" and platform_system != "AIX" and platform_python_implementation != "PyPy"' don't match your environment
      Collecting setuptools<60.0
        Using cached setuptools-59.8.0-py3-none-any.whl (952 kB)
      Collecting wheel
        Using cached wheel-0.37.1-py2.py3-none-any.whl (35 kB)
      Collecting Cython>=0.28.5
        Using cached Cython-0.29.27-py2.py3-none-any.whl (983 kB)
      Collecting oldest-supported-numpy
        Using cached oldest_supported_numpy-2022.1.30-py3-none-any.whl (3.9 kB)
      Collecting scipy>=1.1.0
        Using cached scipy-1.8.0.tar.gz (38.3 MB)
        Installing build dependencies: started
        Installing build dependencies: finished with status 'done'
        Getting requirements to build wheel: started
        Getting requirements to build wheel: finished with status 'done'
        Preparing metadata (pyproject.toml): started
        Preparing metadata (pyproject.toml): finished with status 'error'
        error: subprocess-exited-with-error

        × Preparing metadata (pyproject.toml) did not run successfully.
        │ exit code: 1
        ╰─> [116 lines of output]
            setup.py:482: UserWarning: Unrecognized setuptools command ('dist_info --egg-base /private/var/folders/bh/bybj2bp10dvdq7ljmr_697mw0000gn/T/pip-modern-metadata-h78sgevf'), proceeding with generating Cython sources and expanding templates
              warnings.warn("Unrecognized setuptools command ('{}'), proceeding with "

raise NotFoundError(msg)
            numpy.distutils.system_info.NotFoundError: No BLAS/LAPACK libraries found. Note: Accelerate is no longer supported.
            To build Scipy from sources, BLAS & LAPACK libraries need to be installed.
            See site.cfg.example in the Scipy source directory and
            https://docs.scipy.org/doc/scipy/reference/building/index.html for details.
            [end of output]

        note: This error originates from a subprocess, and is likely not a problem with pip.
      error: metadata-generation-failed
</code>```

So I tried to Google the solution and learned that there are certain problems with Python on a M1 Mac. What I tried:

I tried to use a solution from another stack overflow question, but I guess I wasn't smart enough to follow the steps, so it didn't really help

I tried to follow instructions on the scikit official site, but again, I didn't understand what to do with miniforge installers:

The recently introduced macos/arm64 platform (sometimes also known as
macos/aarch64) requires the open source community to upgrade the build
configuration and automation to properly support it.

At the time of writing (January 2021), the only way to get a working
installation of scikit-learn on this hardware is to install
scikit-learn and its dependencies from the conda-forge distribution,
for instance using the miniforge installers

I also tried to install the package with Miniforge. I managed to install the package in a virtual environment, but I still couldn't import sklearn to my project:

```<code>conda list scikit-learn  # input

# packages in environment at /opt/homebrew/Caskroom/miniforge/base/envs/test_env:
#
# Name                    Version                   Build  Channel
scikit-learn              1.0.2            py39hef7049f_0    conda-forge
</code>```

I also tried lots of other things I found on the Web, but nothing helped, unfortunately

I feel like I've done a lot of unnecessary stuff so far, but  I'd still really like to solve this problem. My Python version is 3.10 (I also tried 3.9 in a virtual environment) and my PyCharm version is 2021.2.2

答:
I think the easiest approach is to create a conda environment from PyCharm. Go to the python interpreter settings and create a new conda environment from there. Then, install packages with conda inside that environment, all from inside PyCharm.

Technically speaking, you're never installing anything into PyCharm, but into a python installation, which can again either be a virtualenv or a conda env (env as in environment). If you manage to point PyCharm to the correct python executable, you should be good. On the other hand if you're conda/pip installing into some other environment in the terminal, you'll just be confused. Since I don't have an M1 Mac I can't say exactly where you went wrong, though.

ContentLicense: CC BY-SA 4.0

Body:
I wanted to install the sklearn package in PyCharm. However, I always got the same error (below is an extract):

pip install scikit-learn  # input

Collecting scikit-learn
  Using cached scikit-learn-1.0.2.tar.gz (6.7 MB)
  Installing build dependencies ... error
  error: subprocess-exited-with-error

  × pip subprocess to install build dependencies did not run successfully.
  │ exit code: 1
  ╰─> [148 lines of output]
      Ignoring numpy: markers 'python_version == "3.7" and platform_machine != "aarch64" and platform_system != "AIX" and platform_python_implementation != "PyPy"' don't match your environment
      Collecting setuptools<60.0
        Using cached setuptools-59.8.0-py3-none-any.whl (952 kB)
      Collecting wheel
        Using cached wheel-0.37.1-py2.py3-none-any.whl (35 kB)
      Collecting Cython>=0.28.5
        Using cached Cython-0.29.27-py2.py3-none-any.whl (983 kB)
      Collecting oldest-supported-numpy
        Using cached oldest_supported_numpy-2022.1.30-py3-none-any.whl (3.9 kB)
      Collecting scipy>=1.1.0
        Using cached scipy-1.8.0.tar.gz (38.3 MB)
        Installing build dependencies: started
        Installing build dependencies: finished with status 'done'
        Getting requirements to build wheel: started
        Getting requirements to build wheel: finished with status 'done'
        Preparing metadata (pyproject.toml): started
        Preparing metadata (pyproject.toml): finished with status 'error'
        error: subprocess-exited-with-error

        × Preparing metadata (pyproject.toml) did not run successfully.
        │ exit code: 1
        ╰─> [116 lines of output]
            setup.py:482: UserWarning: Unrecognized setuptools command ('dist_info --egg-base /private/var/folders/bh/bybj2bp10dvdq7ljmr_697mw0000gn/T/pip-modern-metadata-h78sgevf'), proceeding with generating Cython sources and expanding templates
              warnings.warn("Unrecognized setuptools command ('{}'), proceeding with "

raise NotFoundError(msg)
            numpy.distutils.system_info.NotFoundError: No BLAS/LAPACK libraries found. Note: Accelerate is no longer supported.
            To build Scipy from sources, BLAS & LAPACK libraries need to be installed.
            See site.cfg.example in the Scipy source directory and
            https://docs.scipy.org/doc/scipy/reference/building/index.html for details.
            [end of output]

        note: This error originates from a subprocess, and is likely not a problem with pip.
      error: metadata-generation-failed

So I tried to Google the solution and learned that there are certain problems with Python on a M1 Mac. What I tried:

I tried to use a solution from another stack overflow question, but I guess I wasn't smart enough to follow the steps, so it didn't really help

I tried to follow instructions on the scikit official site, but again, I didn't understand what to do with miniforge installers:

The recently introduced macos/arm64 platform (sometimes also known as
macos/aarch64) requires the open source community to upgrade the build
configuration and automation to properly support it.

At the time of writing (January 2021), the only way to get a working
installation of scikit-learn on this hardware is to install
scikit-learn and its dependencies from the conda-forge distribution,
for instance using the miniforge installers

I also tried to install the package with Miniforge. I managed to install the package in a virtual environment, but I still couldn't import sklearn to my project:

conda list scikit-learn  # input

# packages in environment at /opt/homebrew/Caskroom/miniforge/base/envs/test_env:
#
# Name                    Version                   Build  Channel
scikit-learn              1.0.2            py39hef7049f_0    conda-forge

I also tried lots of other things I found on the Web, but nothing helped, unfortunately

I feel like I've done a lot of unnecessary stuff so far, but  I'd still really like to solve this problem. My Python version is 3.10 (I also tried 3.9 in a virtual environment) and my PyCharm version is 2021.2.2


问:
Hi, I am new to coding and currently building an MVC and I have a CS0161 ERROR and I cant seem to fix it. Any help appreciated
```<code>namespace Funko626.Controllers
{
    public class FunkoController : Controller
    {
        private readonly IFunkoRepository _funkoRepository;
        private readonly IBrandRepository _brandRepository;

        public FunkoController(IFunkoRepository funkoRepository, IBrandRepository brandRepository)
        {
         _funkoRepository = funkoRepository;
         _brandRepository = brandRepository;
        }

        public ViewResult List()
        {
            FunkoListViewModel funkoListViewModel = new()
            {
                Funkos = _funkoRepository.AllFunkos,

                CurrentBrand = " "
            };
            return View(funkoListViewModel);
        }
       //I think it's this part of the code with 'int id' but cant be sure.
        public IActionResult Details(int id)
        {
            var funko = _funkoRepository.GetFunkoById(id);
            if(funko == null)
                return NotFound();
        }

    }
}
</code>```

Severity  Code    Description Project File    Line    Suppression State
Error CS0161  'FunkoController.Details(int)': not all code paths return
a
value Funko626    C:\Users\bidde\source\repos\Funko626\Controllers\FunkoController.cs 29  Active

答:
CS0161 is about the most obvious error you'll get in programming. It says

A method that returns a value must have a return statement in all code paths

Which means, in English, that if your method returns something then every code path must return that thing

So what's wrong here:

```<code>public IActionResult Details(int id)
{
    var funko = _funkoRepository.GetFunkoById(id);
    if(funko == null)
         return NotFound();
}
</code>```

if funko is NOT null then nothing is returned. Fix it by returning something below the if condition. Usually this might look something like:

```<code>public IActionResult Details(int id)
{
    var funko = _funkoRepository.GetFunkoById(id);
    if(funko == null)
         return NotFound();

    // we found a funko!
    return Ok(funko);
}
</code>```

Body:
namespace Funko626.Controllers
{
    public class FunkoController : Controller
    {
        private readonly IFunkoRepository _funkoRepository;
        private readonly IBrandRepository _brandRepository;

        public FunkoController(IFunkoRepository funkoRepository, IBrandRepository brandRepository)
        {
         _funkoRepository = funkoRepository;
         _brandRepository = brandRepository;
        }

        public ViewResult List()
        {
            FunkoListViewModel funkoListViewModel = new()
            {
                Funkos = _funkoRepository.AllFunkos,

                CurrentBrand = " "
            };
            return View(funkoListViewModel);
        }
       //I think it's this part of the code with 'int id' but cant be sure.
        public IActionResult Details(int id)
        {
            var funko = _funkoRepository.GetFunkoById(id);
            if(funko == null)
                return NotFound();
        }

    }
}

Severity  Code    Description Project File    Line    Suppression State
Error CS0161  'FunkoController.Details(int)': not all code paths return
a
value Funko626    C:\Users\bidde\source\repos\Funko626\Controllers\FunkoController.cs 29  Active

Body:
CS0161 is about the most obvious error you'll get in programming. It says

A method that returns a value must have a return statement in all code paths

Which means, in English, that if your method returns something then every code path must return that thing

So what's wrong here:

public IActionResult Details(int id)
{
    var funko = _funkoRepository.GetFunkoById(id);
    if(funko == null)
         return NotFound();
}

if funko is NOT null then nothing is returned. Fix it by returning something below the if condition. Usually this might look something like:

public IActionResult Details(int id)
{
    var funko = _funkoRepository.GetFunkoById(id);
    if(funko == null)
         return NotFound();

    // we found a funko!
    return Ok(funko);
}


问:
Delaying a function for transition duration
How can I make this script delay for 350 miliseconds while waiting for the css3 transition to end?

```<code>    <script type="text/javascript">
        $(document).ready(function() {
            var last = "";
            $("#thumbs a").click(function() {
                event.preventDefault();
                var graphic = $(this).attr("href");
                if(last != graphic) {
                    $("#placeholder").before( "<img src=\"" + graphic + "\" />" );
                    $("#mask").css("marginTop","-=450px");
                    last = graphic;
                }
            });
        });
    </script>
</code>```

Basically, when you click, it should check to see if its been clicked within the last 350 miliseconds, and if it has, do nothing.

I've heard of the transitionend function, but I couldn't figure out how to implement it.

答:
I would do something like this:</p>

```<code>var clickable = true;
var timer;
$('#thumbs a').click(function(event){
    event.preventDefault();
    if(clickable){
      do stuff!
    }else{
        clearTimeout(timer);
    }
    clickable = false;
    timer = setTimeout(function(){
        clickable = true;
    }, 350);

});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How can I make this script delay for 350 miliseconds while waiting for the css3 transition to end?

Basically, when you click, it should check to see if its been clicked within the last 350 miliseconds, and if it has, do nothing.

I've heard of the transitionend function, but I couldn't figure out how to implement it.

Body:
I would do something like this:

var clickable = true;
var timer;
$('#thumbs a').click(function(event){
    event.preventDefault();
    if(clickable){
      do stuff!
    }else{
        clearTimeout(timer);
    }
    clickable = false;
    timer = setTimeout(function(){
        clickable = true;
    }, 350);

});


问:
What is the difference between types String and string?
Does anyone know the difference between String and string in TypeScript? Am I correct in assuming that they ought to be the same?

```<code>var a: String = "test";
var b: string = "another test";
a = b;
b = a; // this gives a compiler error!
</code>```

Current version of the compiler says:

```<code>Type 'String' is not assignable to type 'string'.
  'string' is a primitive, but 'String' is a wrapper object.
     Prefer using 'string' when possible.
</code>```

Is that a bug?

答:
Based on my personal reference

string is a type in JavaScript.

String; in JavaScript, all the strings are represented as an instance of String class. Read this short article to learn a bit more about the String class

Prefer the string over the String

Body:
Does anyone know the difference between String and string in TypeScript? Am I correct in assuming that they ought to be the same?

var a: String = "test";
var b: string = "another test";
a = b;
b = a; // this gives a compiler error!

Current version of the compiler says:

Type 'String' is not assignable to type 'string'.
  'string' is a primitive, but 'String' is a wrapper object.
     Prefer using 'string' when possible.

Is that a bug?


问:
Mongoose: findOneAndUpdate doesn't return updated document
Below is my code

```<code>var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

var Cat = mongoose.model('Cat', {
    name: String,
    age: {type: Number, default: 20},
    create: {type: Date, default: Date.now}
});

Cat.findOneAndUpdate({age: 17}, {$set:{name:"Naomi"}},function(err, doc){
    if(err){
        console.log("Something wrong when updating data!");
    }

    console.log(doc);
});
</code>```

I already have some record in my mongo database and I would like to run this code to update name for which age is 17 and then print result out in the end of code.

However, why I still get same result from console(not the modified name) but when I go to mongo db command line and type "db.cats.find();". The result came with modified name.

Then I go back to run this code again and the result is modified.

My question is:  If the data was modified, then why I still got original data at first time when console.log it.

答:
```<code>export function newDocumentOnUpdatePlugin(schema) {
  schema.pre(
    ['update', 'findOneAndUpdate', 'updateOne', 'updateMany'],
    function (next) {
      this.setOptions({ new: true });
      next();
    },
  );
}
</code>```

I have created this plugin if anyone need this functionality across the whole app and want to avoid repetition. Just use this as a global plugin

Body:
Below is my code

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

var Cat = mongoose.model('Cat', {
    name: String,
    age: {type: Number, default: 20},
    create: {type: Date, default: Date.now}
});

Cat.findOneAndUpdate({age: 17}, {$set:{name:"Naomi"}},function(err, doc){
    if(err){
        console.log("Something wrong when updating data!");
    }

    console.log(doc);
});

I already have some record in my mongo database and I would like to run this code to update name for which age is 17 and then print result out in the end of code.

However, why I still get same result from console(not the modified name) but when I go to mongo db command line and type "db.cats.find();". The result came with modified name.

Then I go back to run this code again and the result is modified.

My question is:  If the data was modified, then why I still got original data at first time when console.log it.

Body:
export function newDocumentOnUpdatePlugin(schema) {
  schema.pre(
    ['update', 'findOneAndUpdate', 'updateOne', 'updateMany'],
    function (next) {
      this.setOptions({ new: true });
      next();
    },
  );
}

I have created this plugin if anyone need this functionality across the whole app and want to avoid repetition. Just use this as a global plugin


问:
Azure private link to AKS with private endpoint to another AKS cluster
I have a situation where my AKS cluster is already in place, two AKS clusters are there & they are internally available within their security zones only. I don't want to go via internet to access the internal resources within the cluster from another cluster.

I was exploring private link service & endpoint, any suggestions?

Both clusters are in different VNets.

答:
You can host your private AKS clusters in a VNET and integrate your AKS clusters with private endpoint

Then you can communicate between your AKS clusters with private endpoints

If your AKS clusters are placed in different VNETs, you can do VNET peering between these VNETs

Then you would be able to communicate between your AKS clusters using the private endpoints


问:
Azure Automation Job runs fine manually but fails when triggered by webhook
I've got an Automation Account in Azure that runs a Powershell runbook.
It runs perfectly fine when I trigger it via the portal, manually specifying the inputs

I've created a webhook with the same input settings. I call it from CURL like

 curl -d '' https://800b2bec-b1ae-4fa1-ba30-8c7d32096828.webhook.ae.azure-automation.net/webhooks?[redactedtoken]

The webhook shows as triggered successfully in the portal, however the job fails with no visible error.

There is no output, even though the first line in my powershell function is Write-Output "Hello"

There are no exception messages, no logs at all.

Any idea how I might get more information as to what might be going wrong?

I've updated the Az modules and enabled verbose logging in the runbook.

Full source below, if it helps.

```<code>Param(
 [string]$resourceGroup,
 [string]$VMName,
 [string]$method,
 [string]$UAMI
)
Write-Output "Hello"
$automationAccount = "AlsAutomation"

# Ensures you do not inherit an AzContext in your runbook
Disable-AzContextAutosave -Scope Process | Out-Null

# Connect using a Managed Service Identity
try {
        $AzureContext = (Connect-AzAccount -Identity).context
    }
catch{
        Write-Output "There is no system-assigned user identity. Aborting.";
        exit
    }

# set and store context
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription `
    -DefaultProfile $AzureContext

if ($method -eq "SA")
    {
        Write-Output "Using system-assigned managed identity"
    }
elseif ($method -eq "UA")
    {
        Write-Output "Using user-assigned managed identity"

        # Connects using the Managed Service Identity of the named user-assigned managed identity
        $identity = Get-AzUserAssignedIdentity -ResourceGroupName $resourceGroup `
            -Name $UAMI -DefaultProfile $AzureContext

        # validates assignment only, not perms
        if ((Get-AzAutomationAccount -ResourceGroupName $resourceGroup `
                -Name $automationAccount `
                -DefaultProfile $AzureContext).Identity.UserAssignedIdentities.Values.PrincipalId.Contains($identity.PrincipalId))
            {
                $AzureContext = (Connect-AzAccount -Identity -AccountId $identity.ClientId).context

                # set and store context
                $AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext
            }
        else {
                Write-Output "Invalid or unassigned user-assigned managed identity"
                exit
            }
    }
else {
        Write-Output "Invalid method. Choose UA or SA."
        exit
     }

# Get current state of VM
$status = (Get-AzVM -ResourceGroupName $resourceGroup -Name $VMName `
    -Status -DefaultProfile $AzureContext).Statuses[1].Code

Write-Output "`r`n Beginning VM status: $status `r`n"

# Start or stop VM based on current state
if($status -eq "Powerstate/deallocated")
    {
        Start-AzVM -Name $VMName -ResourceGroupName $resourceGroup -DefaultProfile $AzureContext
    }
elseif ($status -eq "Powerstate/running")
    {
        Stop-AzVM -Name $VMName -ResourceGroupName $resourceGroup -DefaultProfile $AzureContext -Force
    }

# Get new state of VM
$status = (Get-AzVM -ResourceGroupName $resourceGroup -Name $VMName -Status `
    -DefaultProfile $AzureContext).Statuses[1].Code

Write-Output "`r`n Ending VM status: $status `r`n `r`n"

Write-Output "Account ID of current context: " $AzureContext.Account.Id
</code>```

答:
We have tested this in our local environment it is working fine, Below statements are based on the analysis.

In our local environment, We have created a Powershell runbook running with different PowerShell Versions 7.1 & Version 5.1.

Using the above share Script & webhook URI, when we are trying to invoke the runbook (PowerShell version 7.1)  using the `Invoke-webRequest method it is continuously failing.

Alternatively, We have tried to invoke the runbook (PowerShell version 5.1)  using the Invoke-webRequest method it is working fine.

We would suggest you to use Powershell Version 5.1 instead of 7.1 in your Runbook.

Here is the sample Output for reference:

Body:
I've got an Automation Account in Azure that runs a Powershell runbook.
It runs perfectly fine when I trigger it via the portal, manually specifying the inputs

I've created a webhook with the same input settings. I call it from CURL like

 curl -d '' https://800b2bec-b1ae-4fa1-ba30-8c7d32096828.webhook.ae.azure-automation.net/webhooks?[redactedtoken]

The webhook shows as triggered successfully in the portal, however the job fails with no visible error.

There is no output, even though the first line in my powershell function is Write-Output "Hello"

There are no exception messages, no logs at all.

Any idea how I might get more information as to what might be going wrong?

I've updated the Az modules and enabled verbose logging in the runbook.

Full source below, if it helps.

Param(
 [string]$resourceGroup,
 [string]$VMName,
 [string]$method,
 [string]$UAMI
)
Write-Output "Hello"
$automationAccount = "AlsAutomation"

# Ensures you do not inherit an AzContext in your runbook
Disable-AzContextAutosave -Scope Process | Out-Null

# Connect using a Managed Service Identity
try {
        $AzureContext = (Connect-AzAccount -Identity).context
    }
catch{
        Write-Output "There is no system-assigned user identity. Aborting.";
        exit
    }

# set and store context
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription `
    -DefaultProfile $AzureContext

if ($method -eq "SA")
    {
        Write-Output "Using system-assigned managed identity"
    }
elseif ($method -eq "UA")
    {
        Write-Output "Using user-assigned managed identity"

        # Connects using the Managed Service Identity of the named user-assigned managed identity
        $identity = Get-AzUserAssignedIdentity -ResourceGroupName $resourceGroup `
            -Name $UAMI -DefaultProfile $AzureContext

        # validates assignment only, not perms
        if ((Get-AzAutomationAccount -ResourceGroupName $resourceGroup `
                -Name $automationAccount `
                -DefaultProfile $AzureContext).Identity.UserAssignedIdentities.Values.PrincipalId.Contains($identity.PrincipalId))
            {
                $AzureContext = (Connect-AzAccount -Identity -AccountId $identity.ClientId).context

                # set and store context
                $AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext
            }
        else {
                Write-Output "Invalid or unassigned user-assigned managed identity"
                exit
            }
    }
else {
        Write-Output "Invalid method. Choose UA or SA."
        exit
     }

# Get current state of VM
$status = (Get-AzVM -ResourceGroupName $resourceGroup -Name $VMName `
    -Status -DefaultProfile $AzureContext).Statuses[1].Code

Write-Output "`r`n Beginning VM status: $status `r`n"

# Start or stop VM based on current state
if($status -eq "Powerstate/deallocated")
    {
        Start-AzVM -Name $VMName -ResourceGroupName $resourceGroup -DefaultProfile $AzureContext
    }
elseif ($status -eq "Powerstate/running")
    {
        Stop-AzVM -Name $VMName -ResourceGroupName $resourceGroup -DefaultProfile $AzureContext -Force
    }

# Get new state of VM
$status = (Get-AzVM -ResourceGroupName $resourceGroup -Name $VMName -Status `
    -DefaultProfile $AzureContext).Statuses[1].Code

Write-Output "`r`n Ending VM status: $status `r`n `r`n"

Write-Output "Account ID of current context: " $AzureContext.Account.Id


问:
sentence_transformers how to create text Python
I am new to language model training and was hoping someone would explain how to actually produce text from a trained model. Any sample code I find online is just model training and printing out embeddings. I don't understand the significance of the embeddings. My goal is to print out text. So for example I have this sample code below. Can I use the model created by this code to actually paraphrase input text rather than just print the embeddings?

```<code>from sentence_transformers import SentenceTransformer
sentences = ["This is an example sentence", "Each sentence is converted"]

model = SentenceTransformer('sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2')
embeddings = model.encode(sentences)
print(embeddings)
</code>```

For Example I would love to achieve something like this:

"This is an example sentence"

Gets converted to

"This sentence is an example"

or

"Jack was going to school"

to

"Jack was on his way to school"

Or something similar

答:
The point of the embeddings (and training objective of the sentence-transformer models, generally) is to recognize paraphrased sentences. Note that these are discriminative models, not generative ones!

This means, a model will be able to tell you when two sentences are likely paraphrased (which can be done by looking at the similarity of the two embeddings), but you are not able to actually generate a paraphrase given a singular input. For that, you will have to look at sequence-to-sequence models, which are not part of sentence-transformers. In particular, their documentation states even states on their page that

SentenceTransformers is a Python framework for state-of-the-art sentence, text and image embeddings. [...]

To directly answer your question then: No, you cannot use this model (or framework) to actually paraphrase an input text.

Body:
I am new to language model training and was hoping someone would explain how to actually produce text from a trained model. Any sample code I find online is just model training and printing out embeddings. I don't understand the significance of the embeddings. My goal is to print out text. So for example I have this sample code below. Can I use the model created by this code to actually paraphrase input text rather than just print the embeddings?

from sentence_transformers import SentenceTransformer
sentences = ["This is an example sentence", "Each sentence is converted"]

model = SentenceTransformer('sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2')
embeddings = model.encode(sentences)
print(embeddings)

For Example I would love to achieve something like this:

"This is an example sentence"

Gets converted to

"This sentence is an example"

or

"Jack was going to school"

to

"Jack was on his way to school"

Or something similar


问:
React Typescript input onChange event type?
I'm trying to get text from a input element, setting it to state and then rendering it back into the input box. However I think my event typing is wrong? I've searched online and tried implementing many solutions but none have worked so far. Any help is appreciated.

my component:

```<code>import React, { ChangeEvent, ChangeEventHandler, useState } from "react";

export default function Unidirectionflow() {
  const [state4, setState4] = useState("");
  const [state5, setState5] = useState("");

  let handleChange4 = (e: React.FormEvent<HTMLInputElement>): void => {
    setState3((e.target as HTMLInputElement).value);
  };

  let handleChange5 = (event: ChangeEvent<HTMLInputElement>) => {
    setState5(event.currentTarget.value);
  };

  return (
    <main>
      <input type="text" value={state4} onChange={() => handleChange4} />
      <input type="text" value={state5} onChange={() => handleChange5} />
    </main>
  );
}

</code>```

Typescript input onchange event.target.value

React TypeScript: Correct Types for onChange

Can't type in React TextField Input

https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/forms_and_events/

答:
onChange={handleChange}
See if this can help you!</p>

Body:
I'm trying to get text from a input element, setting it to state and then rendering it back into the input box. However I think my event typing is wrong? I've searched online and tried implementing many solutions but none have worked so far. Any help is appreciated.

my component:

import React, { ChangeEvent, ChangeEventHandler, useState } from "react";

export default function Unidirectionflow() {
  const [state4, setState4] = useState("");
  const [state5, setState5] = useState("");

  let handleChange4 = (e: React.FormEvent<HTMLInputElement>): void => {
    setState3((e.target as HTMLInputElement).value);
  };

  let handleChange5 = (event: ChangeEvent<HTMLInputElement>) => {
    setState5(event.currentTarget.value);
  };

  return (

      <input type="text" value={state4} onChange={() => handleChange4} />
      <input type="text" value={state5} onChange={() => handleChange5} />

  );
}

Typescript input onchange event.target.value

React TypeScript: Correct Types for onChange

Can't type in React TextField Input

https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/forms_and_events/


问:
Filter into Foreign Keys on Django-Rest Datatables
I have a datatable for Order model which contains some fields from User model and is implemented using serializer as following

serializers.py

```<code># customer order detail serializer
class CustomerOrderSerializer(serializers.ModelSerializer):
    first_name = serializers.ReadOnlyField(source='user.first_name')
    last_name = serializers.ReadOnlyField(source='user.last_name')

    def __init__(self, *args, **kwargs):
        remove_fields = kwargs.pop('remove_fields', None)
        super(CustomerOrderSerializer, self).__init__(*args, **kwargs)

        if remove_fields:
            for field_name in remove_fields:
                self.fields.pop(field_name)

    class Meta:
        model = Order
        fields = ['id', 'amount', 'order_status', 'created', 'first_name', 'last_name']
        read_only_fields = ['issue_date', 'first_name', 'last_name']
</code>```

In views.py

```<code>class OrderList(generics.ListAPIView):
    queryset = Order.objects.order_by('-created')
    serializer_class = CustomerOrderSerializer
</code>```

I am successfully able to get first_name & last_name fields as in datatable format as shown

However, my requirements is to filter/search in datatable on fields first_name & last_name which are from different model User

when I try to filter on those fields I get Following error:

```<code>Cannot resolve keyword 'first_name' into field. Choices are: ..., .., ..., ..
</code>```

Can anyone help me understand, How we can filter on foreign key fields in django-rest datatables

答:
You can use SearchFilter.doc

from rest_framework import filters

class OrderList(generics.ListAPIView):
    queryset = Order.objects.order_by('-created')
    serializer_class = CustomerOrderSerializer
    filter_backends = [filters.SearchFilter]
    search_fields = ['user__first_name', 'user__last_name']
```

After that, you can search first name & last name by ?search=foo query parameter.

Body:
I have a datatable for Order model which contains some fields from User model and is implemented using serializer as following

serializers.py

# customer order detail serializer
class CustomerOrderSerializer(serializers.ModelSerializer):
    first_name = serializers.ReadOnlyField(source='user.first_name')
    last_name = serializers.ReadOnlyField(source='user.last_name')

    def __init__(self, *args, **kwargs):
        remove_fields = kwargs.pop('remove_fields', None)
        super(CustomerOrderSerializer, self).__init__(*args, **kwargs)

        if remove_fields:
            for field_name in remove_fields:
                self.fields.pop(field_name)

    class Meta:
        model = Order
        fields = ['id', 'amount', 'order_status', 'created', 'first_name', 'last_name']
        read_only_fields = ['issue_date', 'first_name', 'last_name']

In views.py

class OrderList(generics.ListAPIView):
    queryset = Order.objects.order_by('-created')
    serializer_class = CustomerOrderSerializer

I am successfully able to get first_name & last_name fields as in datatable format as shown

However, my requirements is to filter/search in datatable on fields first_name & last_name which are from different model User

when I try to filter on those fields I get Following error:

Cannot resolve keyword 'first_name' into field. Choices are: ..., .., ..., ..

Can anyone help me understand, How we can filter on foreign key fields in django-rest datatables

Body:
You can use SearchFilter.doc

from rest_framework import filters

class OrderList(generics.ListAPIView):
    queryset = Order.objects.order_by('-created')
    serializer_class = CustomerOrderSerializer
    filter_backends = [filters.SearchFilter]
    search_fields = ['user__first_name', 'user__last_name']

After that, you can search first name & last name by ?search=foo query parameter.


问:
I have base class which implemented IClientValidatable
I have base class(CompareAttribute) which implemented IClientValidatable

```<code>[AttributeUsage(AttributeTargets.Property)]
public class NotContainsAttribute : CompareAttribute
{
}
</code>```

I want to override method IEnumerable<ModelClientValidationRule> GetClientValidationRules

but i can't do that because it is not virtual(cannot override inherited member, because it is not marked virtual, abstract, or override).

So i just declare my own method in my NotContainsAttribute class

```<code>public new IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
}
</code>```

After i run the program all working like expected but i get warning in compile time that my class hides inherited member, (Warning "NotContainsAttribute" hides inherited member Use the new keyword if hiding was intended.)

But if I use new keyword

```<code>public new IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationNotContains (this.FormatErrorMessage(metadata.GetDisplayName()), CompareAttribute.FormatPropertyForClientValidation(this.OtherProperty));
            yield break;
        }
</code>```

In such case my method not used, base class method used instead.

I want my method to be used, without new keyword i get it used but why compiler saying that i need to use new keyword if hiding was intended?

I understand that if hiding was intended means that if you want to hide base method and use your method insteard mark it with new keyword but on practice it is really hiding my method.

May be some one may clarify that and is it good practice to declare method with the same name if that method in base class not allowed to be overridden but really you need to override it?

答:
I don't think your assessment of the situation is correct: If the base class method is not marked as virtual then your method implementation will be hiding it by default.

From MSDN:

If the method in the derived class is not preceded by new or override
  keywords, the compiler will issue a warning and the method will behave
  as if the new keyword were present.

You just get a compiler warning because often this is not what the intention of the programmer is and it gives you a chance to correct this common mistake - usually you want to override a base class implementation. It should not make a difference whether or not you mark your method with new - this just makes it explicit that you are in fact hiding the base class method.

Also note that hiding a base class method will not allow this method to be used in a polymorphic fashion: object references typed as the base class that point to an instance of your derived class will use the base class method instead:

```<code>CompareAttribute foo = new NotContainsAttribute();
foo.GetClientValidationRules(..) // will call base class method
</code>```

So your method only will be called if you call the method on an object reference with type NotContainsAttribute :

```<code>NotContainsAttribute bar = new NotContainsAttribute();
bar.GetClientValidationRules(..) // will call your method
</code>```

Also see "Versioning with the Override and New Keywords (C# Programming Guide)" and "Polymorphism, Method Hiding and Overriding in C#"  as a reference.

Body:
I have base class(CompareAttribute) which implemented IClientValidatable

[AttributeUsage(AttributeTargets.Property)]
public class NotContainsAttribute : CompareAttribute
{
}

I want to override method IEnumerable<ModelClientValidationRule> GetClientValidationRules

but i can't do that because it is not virtual(cannot override inherited member, because it is not marked virtual, abstract, or override).

So i just declare my own method in my NotContainsAttribute class

public new IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
}

After i run the program all working like expected but i get warning in compile time that my class hides inherited member, (Warning "NotContainsAttribute" hides inherited member Use the new keyword if hiding was intended.)

But if I use new keyword

public new IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationNotContains (this.FormatErrorMessage(metadata.GetDisplayName()), CompareAttribute.FormatPropertyForClientValidation(this.OtherProperty));
            yield break;
        }

In such case my method not used, base class method used instead.

I want my method to be used, without new keyword i get it used but why compiler saying that i need to use new keyword if hiding was intended?

I understand that if hiding was intended means that if you want to hide base method and use your method insteard mark it with new keyword but on practice it is really hiding my method.

May be some one may clarify that and is it good practice to declare method with the same name if that method in base class not allowed to be overridden but really you need to override it?

Body:
I don't think your assessment of the situation is correct: If the base class method is not marked as virtual then your method implementation will be hiding it by default.

From MSDN:

If the method in the derived class is not preceded by new or override
  keywords, the compiler will issue a warning and the method will behave
  as if the new keyword were present.

You just get a compiler warning because often this is not what the intention of the programmer is and it gives you a chance to correct this common mistake - usually you want to override a base class implementation. It should not make a difference whether or not you mark your method with new - this just makes it explicit that you are in fact hiding the base class method.

Also note that hiding a base class method will not allow this method to be used in a polymorphic fashion: object references typed as the base class that point to an instance of your derived class will use the base class method instead:

CompareAttribute foo = new NotContainsAttribute();
foo.GetClientValidationRules(..) // will call base class method

So your method only will be called if you call the method on an object reference with type NotContainsAttribute :

NotContainsAttribute bar = new NotContainsAttribute();
bar.GetClientValidationRules(..) // will call your method

Also see "Versioning with the Override and New Keywords (C# Programming Guide)" and "Polymorphism, Method Hiding and Overriding in C#"  as a reference.


问:
Right way to apply pre-trained scikit-learn model to dask array?
I have a scikit-learn model, which has  already been trained. It takes 8 features as an input.
Now I would like to apply that model to an arbitrary big dask array (of shape (n_samples, 8))  and write the result to disk.
I fail at applying my model to a dask array and getting back a dask array.

Setup:

```<code>import dask.array as da
from dask import delayed

# pre-trained classifier/model already exists
# I will refer to this model as "clf"

# test data
X = da.full((100,8), 0)

# this works fine, but returns a numpy array...
y_predicted = clf.predict(X)
</code>```

What I have tried

```<code># 1. intention: apply classifier to each row (features)
y_predicted = da.apply_along_axis(clf.pedict, 1, X)
# fails with
# AttributeError: 'RandomForestClassifier' object has no attribute 'pedict'

# 2. apply blocks
y_predicted = da.map_blocks(clf.predict, X)
# quickly runs out of memory, process killed

# 3. write a delayed function that returns a dask array
@delayed
def predict_delayed(da_array):
    return da.from_array(clf.predict(da_array))

y_predicted = predict_delayed(X)
y_predicted.compute()
#  fails with TypeError: Expected sequence or array-like, got <class 'method'>
</code>```

I have spent quite some time on this and I am quite clueless on how to proceed.
Any suggestions?

答:
I finally figured it out, here is a minimal reproducible example:

import dask.array as da
from dask import delayed

from sklearn.ensemble import RandomForestClassifier as RF

n_samples = 1000
# random training data
X_train = da.random.random((n_samples,8))
y_train = da.random.randint(0, 2, n_samples)

rf = RF(random_state = 42, n_estimators=50)
rf.fit(X_train, y_train)

# some data to predict on
X_new = da.random.random((n_samples,8))

# 1. option: delayed function
@delayed
def predict_delayed(da_array: da.array) -> da.array:
    return da.from_array(rf.predict(da_array))

y_predicted = predict_delayed(X_new)

# 2. option: map_blocks
# (key was here to supply drop_axis and dtype arguments)
y_predicted = da.map_blocks(rf.predict, X_new, dtype="i8", drop_axis=1)
```

Body:
I have a scikit-learn model, which has  already been trained. It takes 8 features as an input.
Now I would like to apply that model to an arbitrary big dask array (of shape (n_samples, 8))  and write the result to disk.
I fail at applying my model to a dask array and getting back a dask array.

Setup:

import dask.array as da
from dask import delayed

# pre-trained classifier/model already exists
# I will refer to this model as "clf"

# test data
X = da.full((100,8), 0)

# this works fine, but returns a numpy array...
y_predicted = clf.predict(X)

What I have tried

# 1. intention: apply classifier to each row (features)
y_predicted = da.apply_along_axis(clf.pedict, 1, X)
# fails with
# AttributeError: 'RandomForestClassifier' object has no attribute 'pedict'

# 2. apply blocks
y_predicted = da.map_blocks(clf.predict, X)
# quickly runs out of memory, process killed

# 3. write a delayed function that returns a dask array
@delayed
def predict_delayed(da_array):
    return da.from_array(clf.predict(da_array))

y_predicted = predict_delayed(X)
y_predicted.compute()
#  fails with TypeError: Expected sequence or array-like, got <class 'method'>

I have spent quite some time on this and I am quite clueless on how to proceed.
Any suggestions?


问:
VBA EXCEL for each cell in range
how to move to next cell without doing anything if condition is not met

```<code>For Each Cel In Range("F22:F3000")
If IsEmpty(Cel.Value) = True Or Not IsDate(Cel.Value) Then
End If
Next Cel
If DateAdd("m", 2, Cel.Value) = Date Then
'Cel.Row(sRow).Select
ws_1.Rows(Cel.Row).EntireRow.Copy ws_2.Range("A" & Rows.Count).End(xlUp).Offset(1)
notify.Toast "My Title", "Message"
MsgBox "regarder la colonne Annotation", vbExclamation
End If
Next
</code>```

error of compilation next without for

答:
As you seem to be a beginner, let me show you how your code might look like, corrected and indented:

```<code>For Each Cel In Range("F22:F3000")
  If IsEmpty(Cel.Value) = True Or Not IsDate(Cel.Value) Then
  End If

  If DateAdd("m", 2, Cel.Value) = Date Then
    'Cel.Row(sRow).Select
    ws_1.Rows(Cel.Row).EntireRow.Copy ws_2.Range("A" & Rows.Count).End(xlUp).Offset(1) notify.Toast "My Title", "Message"
    MsgBox "regarder la colonne Annotation", vbExclamation
  End If
Next Cel
</code>```

As you see, I have removed the first Next Cel, you only can have one Next in a For-loop.

Title: VBA EXCEL for each cell in range

Body:
how to move to next cell without doing anything if condition is not met

For Each Cel In Range("F22:F3000")
If IsEmpty(Cel.Value) = True Or Not IsDate(Cel.Value) Then
End If
Next Cel
If DateAdd("m", 2, Cel.Value) = Date Then
'Cel.Row(sRow).Select
ws_1.Rows(Cel.Row).EntireRow.Copy ws_2.Range("A" & Rows.Count).End(xlUp).Offset(1)
notify.Toast "My Title", "Message"
MsgBox "regarder la colonne Annotation", vbExclamation
End If
Next

error of compilation next without for

Body:
As you seem to be a beginner, let me show you how your code might look like, corrected and indented:

For Each Cel In Range("F22:F3000")
  If IsEmpty(Cel.Value) = True Or Not IsDate(Cel.Value) Then
  End If

  If DateAdd("m", 2, Cel.Value) = Date Then
    'Cel.Row(sRow).Select
    ws_1.Rows(Cel.Row).EntireRow.Copy ws_2.Range("A" & Rows.Count).End(xlUp).Offset(1) notify.Toast "My Title", "Message"
    MsgBox "regarder la colonne Annotation", vbExclamation
  End If
Next Cel

As you see, I have removed the first Next Cel, you only can have one Next in a For-loop.


问:
apache ignite out of memory exception
I got out of memory exception and ignite got crashed. After going through the ignite logs, in last metrics I could see heap, off-heap memory usage was about 171 MB,70MB respectively and after 10 secs, ignite logs shows out of memory exception. also, other flags in metrics looks ok

Below is the log snippet

```<code>[01:04:29,690][INFO][grid-timeout-worker-#22][IgniteKernal]
Metrics for local node (to disable set 'metricsLogFrequency' to 0)
    ^-- Node [id=8a034404, uptime=39 days, 15:50:23.086]
    ^-- Cluster [hosts=1, CPUs=4, servers=1, clients=1, topVer=22, minorTopVer=0]
    ^-- Network [addrs=[0:0:0:0:0:0:0:1%lo, 127.0.0.1, 172.17.0.1, 172.28.230.222], discoPort=47500, commPort=47100]
    ^-- CPU [CPUs=4, curLoad=0.07%, avgLoad=0.15%, GC=0%]
    ^-- Heap [used=171MB, free=95.15%, comm=254MB]
    ^-- Off-heap memory [used=70MB, free=98.02%, allocated=3377MB]
    ^-- Page memory [pages=17878]
    ^--   sysMemPlc region [type=internal, persistence=true, lazyAlloc=false,
      ...  initCfg=40MB, maxCfg=100MB, usedRam=0MB, freeRam=99.98%, allocRam=100MB, allocTotal=0MB]
    ^--   default region [type=default, persistence=true, lazyAlloc=true,
      ...  initCfg=256MB, maxCfg=3177MB, usedRam=70MB, freeRam=97.78%, allocRam=3177MB, allocTotal=69MB]
    ^--   metastoreMemPlc region [type=internal, persistence=true, lazyAlloc=false,
      ...  initCfg=40MB, maxCfg=100MB, usedRam=0MB, freeRam=99.95%, allocRam=0MB, allocTotal=0MB]
    ^--   TxLog region [type=internal, persistence=true, lazyAlloc=false,
      ...  initCfg=40MB, maxCfg=100MB, usedRam=0MB, freeRam=100%, allocRam=100MB, allocTotal=0MB]
    ^--   volatileDsMemPlc region [type=user, persistence=false, lazyAlloc=true,
      ...  initCfg=40MB, maxCfg=100MB, usedRam=0MB, freeRam=100%, allocRam=0MB]
    ^-- Ignite persistence [used=69MB]
    ^-- Outbound messages queue [size=0]
    ^-- Public thread pool [active=0, idle=0, qSize=0]
    ^-- System thread pool [active=0, idle=7, qSize=0]
    ^-- Striped thread pool [active=0, idle=8, qSize=0]
[01:04:38,584][INFO][db-checkpoint-thread-#104][Checkpointer] Checkpoint started [checkpointId=41e99f38-7359-4af1-945f-61c92d2a5fb7, startPtr=WALPointer [idx=147, fileOff=11684440, len=381549], checkpointBeforeLockTime=9ms, checkpointLockWait=0ms, checkpointListenersExecuteTime=17ms, checkpointLockHoldTime=19ms, walCpRecordFsyncDuration=2ms, writeCheckpointEntryDuration=2ms, splitAndSortCpPagesDuration=0ms, pages=9, reason='timeout']
[01:04:38,619][SEVERE][db-checkpoint-thread-#104][] Critical system error detected. Will be handled accordingly to configured handler [hnd=StopNodeOrHaltFailureHandler [tryStop=false, timeout=0, super=AbstractFailureHandler [ignoredFailureTypes=UnmodifiableSet [SYSTEM_WORKER_BLOCKED, SYSTEM_CRITICAL_OPERATION_TIMEOUT]]], failureCtx=FailureContext [type=CRITICAL_ERROR, err=class o.a.i.IgniteCheckedException: Compound exception for CountDownFuture.]]
class org.apache.ignite.IgniteCheckedException: Compound exception for CountDownFuture.
    at org.apache.ignite.internal.util.future.CountDownFuture.addError(CountDownFuture.java:72)
    at org.apache.ignite.internal.util.future.CountDownFuture.onDone(CountDownFuture.java:46)
    at org.apache.ignite.internal.util.future.CountDownFuture.onDone(CountDownFuture.java:28)
    at org.apache.ignite.internal.util.future.GridFutureAdapter.onDone(GridFutureAdapter.java:478)
    at org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointPagesWriter.run(CheckpointPagesWriter.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    Suppressed: java.lang.OutOfMemoryError: unable to create new native thread
        at java.lang.Thread.start0(Native Method)
        at java.lang.Thread.start(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor.addWorker(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor.execute(Unknown Source)
        at sun.nio.ch.SimpleAsynchronousFileChannelImpl.implWrite(Unknown Source)
        at sun.nio.ch.AsynchronousFileChannelImpl.write(Unknown Source)
        at org.apache.ignite.internal.processors.cache.persistence.file.AsyncFileIO.write(AsyncFileIO.java:177)
        at org.apache.ignite.internal.processors.cache.persistence.file.AbstractFileIO$5.run(AbstractFileIO.java:117)
        at org.apache.ignite.internal.processors.cache.persistence.file.AbstractFileIO.fully(AbstractFileIO.java:53)
        at org.apache.ignite.internal.processors.cache.persistence.file.AbstractFileIO.writeFully(AbstractFileIO.java:115)
        at org.apache.ignite.internal.processors.cache.persistence.file.FilePageStore.write(FilePageStore.java:748)
        at org.apache.ignite.internal.processors.cache.persistence.pagemem.PageReadWriteManagerImpl.write(PageReadWriteManagerImpl.java:116)
        at org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager.write(FilePageStoreManager.java:636)
        at org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointManager.lambda$new$0(CheckpointManager.java:175)
        at org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointPagesWriter$1.writePage(CheckpointPagesWriter.java:266)
        at org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryImpl.copyPageForCheckpoint(PageMemoryImpl.java:1343)
        at org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryImpl.checkpointWritePage(PageMemoryImpl.java:1250)
        at org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointPagesWriter.writePages(CheckpointPagesWriter.java:207)
        at org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointPagesWriter.run(CheckpointPagesWriter.java:151)
        ... 3 more
[01:04:38,620][SEVERE][db-checkpoint-thread-#104][FailureProcessor] No deadlocked threads detected.
[01:04:38,749][SEVERE][db-checkpoint-thread-#104][FailureProcessor] Thread dump at 2022/02/06 01:04:38 CST
</code>```

答:
unable to create new native thread

This seems to be a non-Ignite exception and most likely is about your system configuration.

Check your Process File Descriptor Limit by running the ulimit -a command and increase it if required. The recommended value is 32768 or above. If it requires an adjustment that can be accomplished by either running ulimit -n 32768 -u 32768 or by modifying the /etc/security/limits.conf

Title: apache ignite out of memory exception

Body:
I got out of memory exception and ignite got crashed. After going through the ignite logs, in last metrics I could see heap, off-heap memory usage was about 171 MB,70MB respectively and after 10 secs, ignite logs shows out of memory exception. also, other flags in metrics looks ok

Below is the log snippet

[01:04:29,690][INFO][grid-timeout-worker-#22][IgniteKernal]
Metrics for local node (to disable set 'metricsLogFrequency' to 0)
    ^-- Node [id=8a034404, uptime=39 days, 15:50:23.086]
    ^-- Cluster [hosts=1, CPUs=4, servers=1, clients=1, topVer=22, minorTopVer=0]
    ^-- Network [addrs=[0:0:0:0:0:0:0:1%lo, 127.0.0.1, 172.17.0.1, 172.28.230.222], discoPort=47500, commPort=47100]
    ^-- CPU [CPUs=4, curLoad=0.07%, avgLoad=0.15%, GC=0%]
    ^-- Heap [used=171MB, free=95.15%, comm=254MB]
    ^-- Off-heap memory [used=70MB, free=98.02%, allocated=3377MB]
    ^-- Page memory [pages=17878]
    ^--   sysMemPlc region [type=internal, persistence=true, lazyAlloc=false,
      ...  initCfg=40MB, maxCfg=100MB, usedRam=0MB, freeRam=99.98%, allocRam=100MB, allocTotal=0MB]
    ^--   default region [type=default, persistence=true, lazyAlloc=true,
      ...  initCfg=256MB, maxCfg=3177MB, usedRam=70MB, freeRam=97.78%, allocRam=3177MB, allocTotal=69MB]
    ^--   metastoreMemPlc region [type=internal, persistence=true, lazyAlloc=false,
      ...  initCfg=40MB, maxCfg=100MB, usedRam=0MB, freeRam=99.95%, allocRam=0MB, allocTotal=0MB]
    ^--   TxLog region [type=internal, persistence=true, lazyAlloc=false,
      ...  initCfg=40MB, maxCfg=100MB, usedRam=0MB, freeRam=100%, allocRam=100MB, allocTotal=0MB]
    ^--   volatileDsMemPlc region [type=user, persistence=false, lazyAlloc=true,
      ...  initCfg=40MB, maxCfg=100MB, usedRam=0MB, freeRam=100%, allocRam=0MB]
    ^-- Ignite persistence [used=69MB]
    ^-- Outbound messages queue [size=0]
    ^-- Public thread pool [active=0, idle=0, qSize=0]
    ^-- System thread pool [active=0, idle=7, qSize=0]
    ^-- Striped thread pool [active=0, idle=8, qSize=0]
[01:04:38,584][INFO][db-checkpoint-thread-#104][Checkpointer] Checkpoint started [checkpointId=41e99f38-7359-4af1-945f-61c92d2a5fb7, startPtr=WALPointer [idx=147, fileOff=11684440, len=381549], checkpointBeforeLockTime=9ms, checkpointLockWait=0ms, checkpointListenersExecuteTime=17ms, checkpointLockHoldTime=19ms, walCpRecordFsyncDuration=2ms, writeCheckpointEntryDuration=2ms, splitAndSortCpPagesDuration=0ms, pages=9, reason='timeout']
[01:04:38,619][SEVERE][db-checkpoint-thread-#104][] Critical system error detected. Will be handled accordingly to configured handler [hnd=StopNodeOrHaltFailureHandler [tryStop=false, timeout=0, super=AbstractFailureHandler [ignoredFailureTypes=UnmodifiableSet [SYSTEM_WORKER_BLOCKED, SYSTEM_CRITICAL_OPERATION_TIMEOUT]]], failureCtx=FailureContext [type=CRITICAL_ERROR, err=class o.a.i.IgniteCheckedException: Compound exception for CountDownFuture.]]
class org.apache.ignite.IgniteCheckedException: Compound exception for CountDownFuture.
    at org.apache.ignite.internal.util.future.CountDownFuture.addError(CountDownFuture.java:72)
    at org.apache.ignite.internal.util.future.CountDownFuture.onDone(CountDownFuture.java:46)
    at org.apache.ignite.internal.util.future.CountDownFuture.onDone(CountDownFuture.java:28)
    at org.apache.ignite.internal.util.future.GridFutureAdapter.onDone(GridFutureAdapter.java:478)
    at org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointPagesWriter.run(CheckpointPagesWriter.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    Suppressed: java.lang.OutOfMemoryError: unable to create new native thread
        at java.lang.Thread.start0(Native Method)
        at java.lang.Thread.start(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor.addWorker(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor.execute(Unknown Source)
        at sun.nio.ch.SimpleAsynchronousFileChannelImpl.implWrite(Unknown Source)
        at sun.nio.ch.AsynchronousFileChannelImpl.write(Unknown Source)
        at org.apache.ignite.internal.processors.cache.persistence.file.AsyncFileIO.write(AsyncFileIO.java:177)
        at org.apache.ignite.internal.processors.cache.persistence.file.AbstractFileIO$5.run(AbstractFileIO.java:117)
        at org.apache.ignite.internal.processors.cache.persistence.file.AbstractFileIO.fully(AbstractFileIO.java:53)
        at org.apache.ignite.internal.processors.cache.persistence.file.AbstractFileIO.writeFully(AbstractFileIO.java:115)
        at org.apache.ignite.internal.processors.cache.persistence.file.FilePageStore.write(FilePageStore.java:748)
        at org.apache.ignite.internal.processors.cache.persistence.pagemem.PageReadWriteManagerImpl.write(PageReadWriteManagerImpl.java:116)
        at org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager.write(FilePageStoreManager.java:636)
        at org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointManager.lambda$new$0(CheckpointManager.java:175)
        at org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointPagesWriter$1.writePage(CheckpointPagesWriter.java:266)
        at org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryImpl.copyPageForCheckpoint(PageMemoryImpl.java:1343)
        at org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryImpl.checkpointWritePage(PageMemoryImpl.java:1250)
        at org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointPagesWriter.writePages(CheckpointPagesWriter.java:207)
        at org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointPagesWriter.run(CheckpointPagesWriter.java:151)
        ... 3 more
[01:04:38,620][SEVERE][db-checkpoint-thread-#104][FailureProcessor] No deadlocked threads detected.
[01:04:38,749][SEVERE][db-checkpoint-thread-#104][FailureProcessor] Thread dump at 2022/02/06 01:04:38 CST


问:
NSFetchedResultsController error: 'no object at index in section at index 0'
I have a UITableView which populate it cells with a NSFetchedResultsController based on CoreData attribute isForConverter which is Bool and should be true to be displayed. isForConverter state sets in another ViewController.
When I want to delete some cells from the UITableView and after access cells which wasn't deleted I receive the error:

```<code>*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'no object at index 5 in section at index 0'
</code>```

There is a GIF with the problem: https://cln.sh/M1aI9Z

My code for deleting cells. I don't need to delete it from database, just change it isForConverter from true to false:

```<code>override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        let currency = fetchedResultsController.object(at: indexPath)
        currency.isForConverter = false
        coreDataManager.save()
    }
}
</code>```

NSFetchedResultsController Setup and delegates:

```<code>func setupFetchedResultsController() {
    let predicate = NSPredicate(format: "isForConverter == YES")
    fetchedResultsController = coreDataManager.createCurrencyFetchedResultsController(with: predicate)
    fetchedResultsController.delegate = self
    try? fetchedResultsController.performFetch()
}

func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    tableView.beginUpdates()
}

func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    tableView.endUpdates()
}

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
    switch type {
    case .update:
        if let indexPath = indexPath {
            tableView.reloadRows(at: [indexPath], with: .none)
        }
    case .move:
        if let indexPath = indexPath, let newIndexPath = newIndexPath {
            tableView.moveRow(at: indexPath, to: newIndexPath)
        }
    case .delete:
        if let indexPath = indexPath {
            tableView.deleteRows(at: [indexPath], with: .none)
        }
    case .insert:
        if let newIndexPath = newIndexPath {
            tableView.insertRows(at: [newIndexPath], with: .none)
        }
    default:
        tableView.reloadData()
    }
}
}
</code>```

I noticed that if I just add tableView.reloadData() to:

tableView(_ tableView: UITableView, commit editingStyle:
UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath)

Then everything works good. But deletion animation is really fast and antsy. Also according to docs I should not use tableView.reloadData() with NSFetchedResultsController...

How to fix that behaviour?

UPDATE:

It seems I found out what the reason of that crash was. This is what my print() tryings gave: SCREENSHOT.
What is a pickedCurrency: this is a global variable of custom type Currency which I created to receive its attribute currentValue (Double, 87.88). I need that value only from the picked to edit cell. After I use that value for calculation at cellForRowAt() and result of the calculation fills all other cells which is not in the edit mode now.

I define pickedCurrency in textFieldDidBeginEditing() because there I receive the exact row of Currency I picked to edit:

```<code>func textFieldDidBeginEditing(_ textField: UITextField) {
    pickedCurrency = fetchedResultsController.object(at: IndexPath(row: textField.tag, section: 0))
    numberFromTextField = 0
    textField.textColor = UIColor(named: "BlueColor")
    textField.placeholder = "0"
    textField.text = ""
}
</code>```

And then use it's value in cellForRowAt to calculate all other cells values based on pickedCell value and number I put in a textField of activeCell:

```<code>    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "converterCell", for: indexPath) as! ConverterTableViewCell

    let currency = fetchedResultsController.object(at: indexPath)
    cell.flag.image = currencyManager.showCurrencyFlag(currency.shortName ?? "notFound")
    cell.shortName.text = currency.shortName
    cell.fullName.text = currency.fullName
    cell.numberTextField.tag = indexPath.row
    cell.numberTextField.delegate = self

    if let number = numberFromTextField, let pickedCurrency = pickedCurrency {
        cell.numberTextField.text = currencyManager.performCalculation(with: number, pickedCurrency, currency)
    }
    return cell
}
</code>```

It seems when I delete a lot of cells and then click on random cell to edit it's not updates its IndexPath(row: textField.tag, section: 0)...

Maybe there is a way to receive Currency object I picked for editing in cellForRowAt()?

答:
I am not certain if this will work but it seems too long for it to be a comment so give the below a try.

Initially I told you could use tag to identify a specific view which is good for quick and simple implementations but when rows get moved / deleted as we have it now, it will be very difficult to manage using tags as you have to constantly update them.

For static table views, they are fine but if your rows will change, then more sophisticated patterns like delegate / observer might be better.

Anyways, what I think can help your situation for now in textFieldDidBeginEditing is stop using the tag to get the index path and get the indexpath from what is tapped.

I still think maybe delegate pattern is better but this might work for you:

```<code>func textFieldDidBeginEditing(_ textField: UITextField) {
    // Get the coordinates of where we tapped in the table
    let tapLocation = textField.convert(textField.bounds.origin,
                                        to: tableView)

    if let indexPath = self.tableView.indexPathForRow(at: tapLocation)
    {
        // don't use tag of textfield anymore
        pickedCurrency
            = fetchedResultsController.object(at: IndexPath(row: indexPath,
                                                            section: 0))

        numberFromTextField = 0
        textField.textColor = UIColor(named: "BlueColor")
        textField.placeholder = "0"
        textField.text = ""
    }
}
</code>```

Does this help ?

Body:
I have a UITableView which populate it cells with a NSFetchedResultsController based on CoreData attribute isForConverter which is Bool and should be true to be displayed. isForConverter state sets in another ViewController.
When I want to delete some cells from the UITableView and after access cells which wasn't deleted I receive the error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'no object at index 5 in section at index 0'

There is a GIF with the problem: https://cln.sh/M1aI9Z

My code for deleting cells. I don't need to delete it from database, just change it isForConverter from true to false:

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        let currency = fetchedResultsController.object(at: indexPath)
        currency.isForConverter = false
        coreDataManager.save()
    }
}

NSFetchedResultsController Setup and delegates:

func setupFetchedResultsController() {
    let predicate = NSPredicate(format: "isForConverter == YES")
    fetchedResultsController = coreDataManager.createCurrencyFetchedResultsController(with: predicate)
    fetchedResultsController.delegate = self
    try? fetchedResultsController.performFetch()
}

func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    tableView.beginUpdates()
}

func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    tableView.endUpdates()
}

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
    switch type {
    case .update:
        if let indexPath = indexPath {
            tableView.reloadRows(at: [indexPath], with: .none)
        }
    case .move:
        if let indexPath = indexPath, let newIndexPath = newIndexPath {
            tableView.moveRow(at: indexPath, to: newIndexPath)
        }
    case .delete:
        if let indexPath = indexPath {
            tableView.deleteRows(at: [indexPath], with: .none)
        }
    case .insert:
        if let newIndexPath = newIndexPath {
            tableView.insertRows(at: [newIndexPath], with: .none)
        }
    default:
        tableView.reloadData()
    }
}
}

I noticed that if I just add tableView.reloadData() to:

tableView(_ tableView: UITableView, commit editingStyle:
UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath)

Then everything works good. But deletion animation is really fast and antsy. Also according to docs I should not use tableView.reloadData() with NSFetchedResultsController...

How to fix that behaviour?

UPDATE:

It seems I found out what the reason of that crash was. This is what my print() tryings gave: SCREENSHOT.
What is a pickedCurrency: this is a global variable of custom type Currency which I created to receive its attribute currentValue (Double, 87.88). I need that value only from the picked to edit cell. After I use that value for calculation at cellForRowAt() and result of the calculation fills all other cells which is not in the edit mode now.

I define pickedCurrency in textFieldDidBeginEditing() because there I receive the exact row of Currency I picked to edit:

func textFieldDidBeginEditing(_ textField: UITextField) {
    pickedCurrency = fetchedResultsController.object(at: IndexPath(row: textField.tag, section: 0))
    numberFromTextField = 0
    textField.textColor = UIColor(named: "BlueColor")
    textField.placeholder = "0"
    textField.text = ""
}

And then use it's value in cellForRowAt to calculate all other cells values based on pickedCell value and number I put in a textField of activeCell:

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "converterCell", for: indexPath) as! ConverterTableViewCell

    let currency = fetchedResultsController.object(at: indexPath)
    cell.flag.image = currencyManager.showCurrencyFlag(currency.shortName ?? "notFound")
    cell.shortName.text = currency.shortName
    cell.fullName.text = currency.fullName
    cell.numberTextField.tag = indexPath.row
    cell.numberTextField.delegate = self

    if let number = numberFromTextField, let pickedCurrency = pickedCurrency {
        cell.numberTextField.text = currencyManager.performCalculation(with: number, pickedCurrency, currency)
    }
    return cell
}

It seems when I delete a lot of cells and then click on random cell to edit it's not updates its IndexPath(row: textField.tag, section: 0)...

Maybe there is a way to receive Currency object I picked for editing in cellForRowAt()?

Body:
I am not certain if this will work but it seems too long for it to be a comment so give the below a try.

Initially I told you could use tag to identify a specific view which is good for quick and simple implementations but when rows get moved / deleted as we have it now, it will be very difficult to manage using tags as you have to constantly update them.

For static table views, they are fine but if your rows will change, then more sophisticated patterns like delegate / observer might be better.

Anyways, what I think can help your situation for now in textFieldDidBeginEditing is stop using the tag to get the index path and get the indexpath from what is tapped.

I still think maybe delegate pattern is better but this might work for you:

func textFieldDidBeginEditing(_ textField: UITextField) {
    // Get the coordinates of where we tapped in the table
    let tapLocation = textField.convert(textField.bounds.origin,
                                        to: tableView)

    if let indexPath = self.tableView.indexPathForRow(at: tapLocation)
    {
        // don't use tag of textfield anymore
        pickedCurrency
            = fetchedResultsController.object(at: IndexPath(row: indexPath,
                                                            section: 0))

        numberFromTextField = 0
        textField.textColor = UIColor(named: "BlueColor")
        textField.placeholder = "0"
        textField.text = ""
    }
}

Does this help ?


问:
Given the line between points 1 and 2, what is the change in angle to point 3?
I have polylines in an Oracle 18c table.

```<code>  ASSET_ID VERTEX_NUM          X          Y ANGLE_CHANGE
---------- ---------- ---------- ---------- ------------
        10          1     118.56        3.8         null
        10          2     118.62       1.03         null
        10          3     121.93       1.03            ?

        20          1     123.59       1.19         null
        20          2     124.21       1.02         null
        20          3     124.85        .96            ?
        20          4     125.49       1.01            ?
        20          5     126.11       1.16            ?
        20          6      126.7       1.41            ?
        20          7     127.24       1.75            ?
        20          8     127.26       2.16            ? --I chose to put this point in the screenshot just because the change in angle is large. So it was easy to illustrate what I'm looking for (lots of room for markup).
        20          9     127.36       2.56            ?
        20         10     127.52       2.94            ?
        20         11     127.75       3.29            ?
        20         12     128.03       3.59            ?

        30          1     129.84       1.26         null
        30          2     133.26       2.88         null
</code>```

Using SQL, I want to determine what the "change in angle" is from point to point.

Question:

How can I calculate the angles between points?

In other words, given a line between points 1 and 2, what is the change in angle to point 3?

db<>fiddle

Body:
I have polylines in an Oracle 18c table.

  ASSET_ID VERTEX_NUM          X          Y ANGLE_CHANGE
---------- ---------- ---------- ---------- ------------
        10          1     118.56        3.8         null
        10          2     118.62       1.03         null
        10          3     121.93       1.03            ?

        20          1     123.59       1.19         null
        20          2     124.21       1.02         null
        20          3     124.85        .96            ?
        20          4     125.49       1.01            ?
        20          5     126.11       1.16            ?
        20          6      126.7       1.41            ?
        20          7     127.24       1.75            ?
        20          8     127.26       2.16            ? --I chose to put this point in the screenshot just because the change in angle is large. So it was easy to illustrate what I'm looking for (lots of room for markup).
        20          9     127.36       2.56            ?
        20         10     127.52       2.94            ?
        20         11     127.75       3.29            ?
        20         12     128.03       3.59            ?

        30          1     129.84       1.26         null
        30          2     133.26       2.88         null

Using SQL, I want to determine what the "change in angle" is from point to point.

Question:

How can I calculate the angles between points?

In other words, given a line between points 1 and 2, what is the change in angle to point 3?

db<>fiddle

Body:
With the notation X01 = X1 - X0,

Θ = atan2(Y12, X12) - atan2(Y01, X01)

so that

tan(Θ) = (Y12.X01 - Y01.X12) / (X12.X01 + Y12.Y01)


问:
Module not found: Error: Package path ./index is not exported from package node_modules/rxjs (see exports field in /node_modules/rxjs/package.json)
I am trying RxJs7 in my angular 12.2.0 project and it seems like the path of rxjs operator and method changed.

I am getting the below error

```<code>./dist/candypal/website/fesm2015/candypal-website.js:8:0-50 - Error: Module not found: Error: Package path ./index is not exported from package /Users/aniruddh/aniruddh/develop/experiment/candypal/node_modules/rxjs (see exports field in /Users/aniruddh/aniruddh/develop/experiment/candypal/node_modules/rxjs/package.json)

</code>```

Note that the above error is coming from a library that uses rxjs7

答:
In your code, replace

```<code>import { Whatever } from 'rxjs/index'
</code>```

by

```<code>import { Whatever } from 'rxjs'
</code>```

The rxjs/index folder was removed from rxjs.

Body:
I am trying RxJs7 in my angular 12.2.0 project and it seems like the path of rxjs operator and method changed.

I am getting the below error

./dist/candypal/website/fesm2015/candypal-website.js:8:0-50 - Error: Module not found: Error: Package path ./index is not exported from package /Users/aniruddh/aniruddh/develop/experiment/candypal/node_modules/rxjs (see exports field in /Users/aniruddh/aniruddh/develop/experiment/candypal/node_modules/rxjs/package.json)

Note that the above error is coming from a library that uses rxjs7

Body:
In your code, replace

import { Whatever } from 'rxjs/index'

by

import { Whatever } from 'rxjs'

The rxjs/index folder was removed from rxjs.


问:
Unable to install scikit-learn-intelex in Colab
I failed to install scikit-learn-intelex (ver. 2021.2.2) in Colab. Here was what I did in Colab:

! python -m pip install --upgrade pip
! python -m pip install scikit-learn-intelex
```
<p>As a result, I got the following output, which looks normal to me.</p>
<pre class="lang-sh prettyprint-override"><code>Collecting pip
  Downloading https://files.pythonhosted.org/packages/ac/cf/0cc542fc93de2f3b9b53cb979c7d1118cffb93204afb46299a9f858e113f/pip-21.1-py3-none-any.whl (1.5MB)
     |████████████████████████████████| 1.6MB 11.3MB/s
Installing collected packages: pip
  Found existing installation: pip 19.3.1
    Uninstalling pip-19.3.1:
      Successfully uninstalled pip-19.3.1
Successfully installed pip-21.1
</code>```

and

Collecting scikit-learn-intelex
  Downloading scikit_learn_intelex-2021.2.2-py37-none-manylinux1_x86_64.whl (24 kB)
Collecting daal4py==2021.2.2
  Downloading daal4py-2021.2.2-py37-none-manylinux1_x86_64.whl (13.6 MB)
     |████████████████████████████████| 13.6 MB 108 kB/s
Collecting dpcpp-cpp-rt==2021.*
  Downloading dpcpp_cpp_rt-2021.2.0-py2.py3-none-manylinux1_x86_64.whl (171.6 MB)
     |████████████████████████████████| 171.6 MB 80 kB/s
Requirement already satisfied: numpy>=1.15 in /usr/local/lib/python3.7/dist-packages (from daal4py==2021.2.2->scikit-learn-intelex) (1.19.5)
Collecting daal==2021.2.2
  Downloading daal-2021.2.2-py2.py3-none-manylinux1_x86_64.whl (295.7 MB)
     |████████████████████████████████| 295.7 MB 13 kB/s
Collecting tbb==2021.*
  Downloading tbb-2021.2.0-py2.py3-none-manylinux1_x86_64.whl (3.9 MB)
     |████████████████████████████████| 3.9 MB 64.4 MB/s
Collecting opencl-rt==2021.*
  Downloading opencl_rt-2021.2.0-py2.py3-none-manylinux1_x86_64.whl (169.0 MB)
     |████████████████████████████████| 169.0 MB 34 kB/s
Requirement already satisfied: intel-openmp==2021.* in /usr/local/lib/python3.7/dist-packages (from dpcpp-cpp-rt==2021.*->daal4py==2021.2.2->scikit-learn-intelex) (2021.2.0)
Collecting common-cmplr-lib-rt==2021.*
  Downloading common_cmplr_lib_rt-2021.2.0-py2.py3-none-manylinux1_x86_64.whl (31.6 MB)
     |████████████████████████████████| 31.6 MB 162 kB/s
Collecting common-cmplr-lic-rt==2021.*
  Downloading common_cmplr_lic_rt-2021.2.0-py2.py3-none-manylinux1_x86_64.whl (24 kB)
Installing collected packages: tbb, common-cmplr-lic-rt, opencl-rt, common-cmplr-lib-rt, dpcpp-cpp-rt, daal, daal4py, scikit-learn-intelex
```
<p>Then I restarted the kernel by clicking on <code>Restart runtime</code> in <code>Runtime</code> of the Colab window banner before running the following code:</p>
<pre class="lang-py prettyprint-override"><code>from sklearnex import patch_sklearn
</code>```

An error message was raised after running the code. It said:

---------------------------------------------------------------------------

ModuleNotFoundError                       Traceback (most recent call last)

<ipython-input-1-45b0f2aba6d7> in <module>()
----> 1 from sklearnex import patch_sklearn

ModuleNotFoundError: No module named 'sklearnex'

---------------------------------------------------------------------------
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.

To view examples of installing some common dependencies, click the
"Open Examples" button below.
---------------------------------------------------------------------------
```

Can anyone tell me how to install the package in Colab?

答: This problem have been fixed with 2021.4 release. Thanks for reporting</p>

Body:
I failed to install scikit-learn-intelex (ver. 2021.2.2) in Colab. Here was what I did in Colab:

! python -m pip install --upgrade pip
! python -m pip install scikit-learn-intelex

As a result, I got the following output, which looks normal to me.

Collecting pip
  Downloading https://files.pythonhosted.org/packages/ac/cf/0cc542fc93de2f3b9b53cb979c7d1118cffb93204afb46299a9f858e113f/pip-21.1-py3-none-any.whl (1.5MB)
     |████████████████████████████████| 1.6MB 11.3MB/s
Installing collected packages: pip
  Found existing installation: pip 19.3.1
    Uninstalling pip-19.3.1:
      Successfully uninstalled pip-19.3.1
Successfully installed pip-21.1

and

Collecting scikit-learn-intelex
  Downloading scikit_learn_intelex-2021.2.2-py37-none-manylinux1_x86_64.whl (24 kB)
Collecting daal4py==2021.2.2
  Downloading daal4py-2021.2.2-py37-none-manylinux1_x86_64.whl (13.6 MB)
     |████████████████████████████████| 13.6 MB 108 kB/s
Collecting dpcpp-cpp-rt==2021.*
  Downloading dpcpp_cpp_rt-2021.2.0-py2.py3-none-manylinux1_x86_64.whl (171.6 MB)
     |████████████████████████████████| 171.6 MB 80 kB/s
Requirement already satisfied: numpy>=1.15 in /usr/local/lib/python3.7/dist-packages (from daal4py==2021.2.2->scikit-learn-intelex) (1.19.5)
Collecting daal==2021.2.2
  Downloading daal-2021.2.2-py2.py3-none-manylinux1_x86_64.whl (295.7 MB)
     |████████████████████████████████| 295.7 MB 13 kB/s
Collecting tbb==2021.*
  Downloading tbb-2021.2.0-py2.py3-none-manylinux1_x86_64.whl (3.9 MB)
     |████████████████████████████████| 3.9 MB 64.4 MB/s
Collecting opencl-rt==2021.*
  Downloading opencl_rt-2021.2.0-py2.py3-none-manylinux1_x86_64.whl (169.0 MB)
     |████████████████████████████████| 169.0 MB 34 kB/s
Requirement already satisfied: intel-openmp==2021.* in /usr/local/lib/python3.7/dist-packages (from dpcpp-cpp-rt==2021.*->daal4py==2021.2.2->scikit-learn-intelex) (2021.2.0)
Collecting common-cmplr-lib-rt==2021.*
  Downloading common_cmplr_lib_rt-2021.2.0-py2.py3-none-manylinux1_x86_64.whl (31.6 MB)
     |████████████████████████████████| 31.6 MB 162 kB/s
Collecting common-cmplr-lic-rt==2021.*
  Downloading common_cmplr_lic_rt-2021.2.0-py2.py3-none-manylinux1_x86_64.whl (24 kB)
Installing collected packages: tbb, common-cmplr-lic-rt, opencl-rt, common-cmplr-lib-rt, dpcpp-cpp-rt, daal, daal4py, scikit-learn-intelex

Then I restarted the kernel by clicking on Restart runtime in Runtime of the Colab window banner before running the following code:

from sklearnex import patch_sklearn

An error message was raised after running the code. It said:

---------------------------------------------------------------------------

ModuleNotFoundError                       Traceback (most recent call last)

<ipython-input-1-45b0f2aba6d7> in <module>()
----> 1 from sklearnex import patch_sklearn

ModuleNotFoundError: No module named 'sklearnex'

---------------------------------------------------------------------------
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.

To view examples of installing some common dependencies, click the
"Open Examples" button below.
---------------------------------------------------------------------------

Can anyone tell me how to install the package in Colab?


问:
how to focus input element when page renders in React
```<code>export const InputComponent = () => {
  const inputRef = useRef<HTMLInputElement | undefined>();

  useEffect(() => {
    inputRef.current.focus();
  }, [inputRef]);

  return(<input type="text" ref={inputRef})
}
</code>```

whats wrong in my code. Please help me.

答:
You missed the closing bracket for the input tag.

```<code>return <input type="text" ref={inputRef} />
</code>```

Body:
export const InputComponent = () => {
  const inputRef = useRef<HTMLInputElement | undefined>();

  useEffect(() => {
    inputRef.current.focus();
  }, [inputRef]);

  return(<input type="text" ref={inputRef})
}

whats wrong in my code. Please help me.

Body:
You missed the closing bracket for the input tag.

return <input type="text" ref={inputRef} />


问:
How to not change the length of preexisting character variables when creating a new dataset in proc-iml?
I have a dataset which I manipulate in proc-iml and then create a new dataset reading some of the manipulated values in. When I read character values in, their length is changed from 7 to 9.

This doesn't really create a problem, except for the minor annoyance that when I later merge this new dataset, I receive the warning that the variables' length is different in two datasets.

Is there a way to keep the length of the original variable?

Sample code

```<code>data data1;
infile datalines delimiter=',';

input classif :$9. time :$7.;
datalines;
05, 2021_11
051, 2021_11
;
run;

proc iml;
    use work.data1;
    read all var {classif time } into _temp_1;
    classif = _temp_1[,1];
    time   = _temp_1[,2];
close;
create work.data2 var{classif time};
append;
quit;

</code>```

Observe how the length of time is 7 in data1, but 9 in data2.

答:
As @Richard explained, this happens when you read two character variables that have different lengths into columns of a common matrix. I can think of at least three workarounds. Depending on your application, one of these methods might be more convenient than others.</p>
```<code>proc iml;
/* Option 1: Read variables into vectors, not a matrix */
use work.data1;
read all var {classif time };
close;
print (nleng(time))[L="nleng(time)"];

/* Option 2: Allocate time to have LENGTH=7 and copy the data in */
use work.data1;
read all var {classif time } into _temp_1;
close;
time = j(nrow(_temp_1), 1, BlankStr(7));  /* allocate char vector */
time[,]   = _temp_1[,2];                  /* copy the data */
print (nleng(time))[L="nleng(time)"];

/* Option 3: Read into a table instead of a matrix. */
tbl = TableCreateFromDataset("work", "data1") ;
classif = TableGetVarData(tbl, {"Classif"});
time = TableGetVarData(tbl, {"time"});
print (nleng(time))[L="nleng(time)"];
</code>```

Body:
I have a dataset which I manipulate in proc-iml and then create a new dataset reading some of the manipulated values in. When I read character values in, their length is changed from 7 to 9.

This doesn't really create a problem, except for the minor annoyance that when I later merge this new dataset, I receive the warning that the variables' length is different in two datasets.

Is there a way to keep the length of the original variable?

Sample code

data data1;
infile datalines delimiter=',';

input classif :$9. time :$7.;
datalines;
05, 2021_11
051, 2021_11
;
run;

proc iml;
    use work.data1;
    read all var {classif time } into _temp_1;
    classif = _temp_1[,1];
    time   = _temp_1[,2];
close;
create work.data2 var{classif time};
append;
quit;

Observe how the length of time is 7 in data1, but 9 in data2.

Body:
As @Richard explained, this happens when you read two character variables that have different lengths into columns of a common matrix. I can think of at least three workarounds. Depending on your application, one of these methods might be more convenient than others.

proc iml;
/* Option 1: Read variables into vectors, not a matrix */
use work.data1;
read all var {classif time };
close;
print (nleng(time))[L="nleng(time)"];

/* Option 2: Allocate time to have LENGTH=7 and copy the data in */
use work.data1;
read all var {classif time } into _temp_1;
close;
time = j(nrow(_temp_1), 1, BlankStr(7));  /* allocate char vector */
time[,]   = _temp_1[,2];                  /* copy the data */
print (nleng(time))[L="nleng(time)"];

/* Option 3: Read into a table instead of a matrix. */
tbl = TableCreateFromDataset("work", "data1") ;
classif = TableGetVarData(tbl, {"Classif"});
time = TableGetVarData(tbl, {"time"});
print (nleng(time))[L="nleng(time)"];


问:
How to define a default vector/matrix for a function's input
I would like to create a function in which one of the inputs is a matrix. But I also want the function to have a default input. For example, please see the following simple "test" function with an input "x":

```<code>def test(x=None):
    if x==None:
        y = np.array([[123], [123]])
    else:
        y = x
    return y
</code>```

In this way, let's say I want to see the function without providing input:

```<code> print(test())
</code>```

Would give:

```<code>[[123]
 [123]]
</code>```

However, if I want "x" to be a matrix or vector (like the following script):

```<code>  z = np.array([[12], [12]])
  print(test(z)
</code>```

I got an error saying:

```<code>**"The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()".**
</code>```

Fine, I want to comply with the error warning. Then I changed the function to:

```<code> def test(x=None):
     if x.all()==None:
         y = np.array([[123], [123]])
     else:
         y = x
     return y
</code>```

Would return (as expected):

```<code> print(test())
 [[123]
  [123]]
</code>```

However, with the revised script, if I want x to be none again:

```<code> print(test())
</code>```

Gives a new warning:

```<code> **'NoneType' object has no attribute 'all'**
</code>```

How can I solve this? I want the function to work either with x being a pre-defined matrix or not (a default).

答:
You can use default parameter, then if no argument is provided it will be used</p>
```<code>def test(x=np.array([[123], [123]])):
    return  x
</code>```

Body:
I would like to create a function in which one of the inputs is a matrix. But I also want the function to have a default input. For example, please see the following simple "test" function with an input "x":

def test(x=None):
    if x==None:
        y = np.array([[123], [123]])
    else:
        y = x
    return y

In this way, let's say I want to see the function without providing input:

 print(test())

Would give:

[[123]
 [123]]

However, if I want "x" to be a matrix or vector (like the following script):

  z = np.array([[12], [12]])
  print(test(z)

I got an error saying:

**"The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()".**

Fine, I want to comply with the error warning. Then I changed the function to:

 def test(x=None):
     if x.all()==None:
         y = np.array([[123], [123]])
     else:
         y = x
     return y

Would return (as expected):

 print(test())
 [[123]
  [123]]

However, with the revised script, if I want x to be none again:

 print(test())

Gives a new warning:

 **'NoneType' object has no attribute 'all'**

How can I solve this? I want the function to work either with x being a pre-defined matrix or not (a default).

Body:
You can use default parameter, then if no argument is provided it will be used

def test(x=np.array([[123], [123]])):
    return  x