问:
Issues that are not actually created, after creating aws_vpc with the terraform 'apply' command
I'm a developer studying terraform.

I was practicing creating aws-vpc using terraform.

Executing the terraform apply command to see a message that the aws_vpc resource was successful

However, when checking the aws dashboard, I found an issue that was not generated (aws_vpc)

Is there anything I missed?

Env & Result

This is the tf file used to create vpc

```<code>
resource "aws_vpc" "main" {
  cidr_block       = "10.0.0.0/16"

  tags = {
    Name = "terraform-101"
  }
}
</code>```

This is the terraform.tfstate (After terraform apply command)

```<code>{
  "version": 4,
  "terraform_version": "1.3.6",
  "serial": 9,
  "lineage": "77523688-c1e9-2a45-7c9a-eaf2f866c290",
  "outputs": {},
  "resources": [
    {
      "mode": "managed",
      "type": "aws_vpc",
      "name": "main",
      "provider": "provider[\"registry.terraform.io/hashicorp/aws\"]",
      "instances": [
        {
          "schema_version": 1,
          "attributes": {
            "arn": "arn:aws:ec2:ap-northeast-2:845502535698:vpc/vpc-016e5391ed5e5fb21",
            "assign_generated_ipv6_cidr_block": false,
            "cidr_block": "10.0.0.0/16",
            "default_network_acl_id": "acl-0d138ce7c406b664f",

            ...

            "tags": {
              "Name": "terraform-101"
            },
            "tags_all": {
              "Name": "terraform-101"
            }
          },
          "sensitive_attributes": [],
          "private": "~~~"
        }
      ]
    }
  ],
  "check_results": null
}
</code>```

I searched, but I couldn't find the right reason for the cause..

Body:
I'm a developer studying terraform.

I was practicing creating aws-vpc using terraform.

Executing the terraform apply command to see a message that the aws_vpc resource was successful

However, when checking the aws dashboard, I found an issue that was not generated (aws_vpc)

Is there anything I missed?

Env & Result

This is the tf file used to create vpc

resource "aws_vpc" "main" {
  cidr_block       = "10.0.0.0/16"

  tags = {
    Name = "terraform-101"
  }
}

This is the terraform.tfstate (After terraform apply command)

{
  "version": 4,
  "terraform_version": "1.3.6",
  "serial": 9,
  "lineage": "77523688-c1e9-2a45-7c9a-eaf2f866c290",
  "outputs": {},
  "resources": [
    {
      "mode": "managed",
      "type": "aws_vpc",
      "name": "main",
      "provider": "provider[\"registry.terraform.io/hashicorp/aws\"]",
      "instances": [
        {
          "schema_version": 1,
          "attributes": {
            "arn": "arn:aws:ec2:ap-northeast-2:845502535698:vpc/vpc-016e5391ed5e5fb21",
            "assign_generated_ipv6_cidr_block": false,
            "cidr_block": "10.0.0.0/16",
            "default_network_acl_id": "acl-0d138ce7c406b664f",

            ...

            "tags": {
              "Name": "terraform-101"
            },
            "tags_all": {
              "Name": "terraform-101"
            }
          },
          "sensitive_attributes": [],
          "private": "~~~"
        }
      ]
    }
  ],
  "check_results": null
}

I searched, but I couldn't find the right reason for the cause..


来源: stackexchange

问:
Clustered Index Scan instead of Seek
I have a database for a couple of iot-devices. The inputDatas-datatable have more than 6 Mio. rows. All selects are fast. The second table with iotDeviceParameters have only 55 rows - I would say nothing.

I want to make a select over inputdatas with a join to the parameters table but the select creates all the time an Clustered Index Scan over the parameter table. So I created an NONCLUSTERED INDEX on that table:

```<code>CREATE NONCLUSTERED INDEX [IX_IoTDeviceParameter_TenantId_DeviceId] ON [dbo].[IoTDeviceParameter]
    (
        [TenantId] ASC,
        [DeviceId] ASC
    )
INCLUDE([Input],[MinimumValue],[MinimumDuration],[AggregationType],[EnergyType],[ParameterType],[Total],[Factor])
</code>```

But without effect.

My expectation is, that the select should go to less than 0.010 seconds. Now it is 0.050 seconds but all the time goes to the scan on parameters table.

https://www.brentozar.com/pastetheplan/?id=HyPjsl79o

Some ideas?

ContentLicense: CC BY-SA 4.0

Title: Clustered Index Scan instead of Seek

Body:
I have a database for a couple of iot-devices. The inputDatas-datatable have more than 6 Mio. rows. All selects are fast. The second table with iotDeviceParameters have only 55 rows - I would say nothing.

I want to make a select over inputdatas with a join to the parameters table but the select creates all the time an Clustered Index Scan over the parameter table. So I created an NONCLUSTERED INDEX on that table:

CREATE NONCLUSTERED INDEX [IX_IoTDeviceParameter_TenantId_DeviceId] ON [dbo].[IoTDeviceParameter]
    (
        [TenantId] ASC,
        [DeviceId] ASC
    )
INCLUDE([Input],[MinimumValue],[MinimumDuration],[AggregationType],[EnergyType],[ParameterType],[Total],[Factor])

But without effect.

My expectation is, that the select should go to less than 0.010 seconds. Now it is 0.050 seconds but all the time goes to the scan on parameters table.

https://www.brentozar.com/pastetheplan/?id=HyPjsl79o

Some ideas?


问:
Echarts: boxplot. Use custom formula for results dimensions
I am using echarts for making a boxplot. I need to use a custom function to show my boxplot's whiskers. Example Here in I try to use custom function instead of the supplied ones it thows an error.

```<code>   resultDimensions: [
            { name: 'min', from: 'Income', method: 'min' },
            { name: 'Q1', from: 'Income', method: 'Q1' },
            { name: 'median', from: 'Income', method: 'median' },
            { name: 'Q3', from: 'Income', method: 'Q3' },
            { name: 'max', from: 'Income', method: 'max' },
            { name: 'Country', from: 'Country' }
          ],
</code>```

Currently, by default, the charts use 'min' and 'max' instead I want to use for the upper whisker: Q3 + 1.5 * IQR and for lower whisker Q1 - 1.5 * IQR which are standard boxplot metrics.

Like If I try to always return 3 it will throw an error and it's expecting inbuilt function names.

```<code>            { name: 'max', from: 'Income', method: () => 3 }

</code>```

Body:
I am using echarts for making a boxplot. I need to use a custom function to show my boxplot's whiskers. Example Here in I try to use custom function instead of the supplied ones it thows an error.

   resultDimensions: [
            { name: 'min', from: 'Income', method: 'min' },
            { name: 'Q1', from: 'Income', method: 'Q1' },
            { name: 'median', from: 'Income', method: 'median' },
            { name: 'Q3', from: 'Income', method: 'Q3' },
            { name: 'max', from: 'Income', method: 'max' },
            { name: 'Country', from: 'Country' }
          ],

Currently, by default, the charts use 'min' and 'max' instead I want to use for the upper whisker: Q3 + 1.5 * IQR and for lower whisker Q1 - 1.5 * IQR which are standard boxplot metrics.

Like If I try to always return 3 it will throw an error and it's expecting inbuilt function names.

            { name: 'max', from: 'Income', method: () => 3 }


问:
Quicktime player "frame by frame" mode cannot mapping OpenCV cap.read() "frame by frame"
I play my video by Quicktime player frame by frame , and using  OpenCV cap.read() frame by frame,
but it seems not mapping

i had tried the openCV cap.set() CV_CAP_PROP_POS_FRAMES
seens have similary issue ,is it the same issue on Quicktime player ?


问:
Median with svy: command
In Stata I want to know the median, p25, p75 and sd of my variables. The problem is that I need to use the svy command before the actual command so I can´t use lots of commands.

The normal command doesn´t work so I found on the internet the solution with the command epctile. The problem is that I need to install the command epctile and I can´t install it with Stata (via search ecpticle) because it says that

http://web.missouri.edu/~kolenikovs/stata/ either

is not a valid URL, or

could not be contacted, or

is not a Stata download site (has no stata.toc file).

I am confused about this homepage https://staskolenikov.net/stata/epctile.ado
because I don´t know which I need to copy in my DoFile.

When I copy everything Stata just closes and nothing is installed.

Is there another page on the internet where I can install the command? Or is there another command with that I can find the median, p25, p75 and sd with the svy command?

Title: Median with svy: command


问:
Unity Dependency issue detected when building android app (aab)
When building a android app bundle in unity 2022.2.1f1 I receive the following message

When I click Resolve Unity stops responding, if I click ignore it stops responding during the build.
Any help is appreciated!

I tried checking/unchecking checkboxes in publishing settings in the player settings menu, but that didn't help.


问:
Image transformation in tflite with variable input and outputsize
I trained a fully convolutional network to transform an image into another image of the same resolution. i was able to convert it into a .tflite model and load it in my android
app.
I create an interpreter and can set the inputsize by calling

```<code>interpreter.resizeInput(0, new int[] {1, image_size, image_size, 3});
</code>```

but when i use interpreter.run(input,output); it breaks with the message

```<code>Cannot copy from a TensorFlowLite tensor (StatefulPartitionedCall:0) with shape [1, 1, 1, 3] to a Java object with shape [1, 1024, 1024, 3].
</code>```

the output shape should be [1, 1024, 1024, 3] but it isn't.

```<code>interpreter.getOutputTensor(0).shapeSignature() and
interpreter.getInputTensor(0).shapeSignature()
</code>```

return [-1, -1, -1, 3]
but i can't change the actual shape you get from

```<code>interpreter.getOutputTensor(0).shape()
</code>```

the way i did with the input by using interpreter.resizeInput(0, new int[] {1, image_size, image_size, 3});

is there a way to implement a tflitemodel that transformes images of variable resolution
into other images of the same resolution somehow?
I am pretty sure it works before i convert it to tflite

Body:
I trained a fully convolutional network to transform an image into another image of the same resolution. i was able to convert it into a .tflite model and load it in my android
app.
I create an interpreter and can set the inputsize by calling

interpreter.resizeInput(0, new int[] {1, image_size, image_size, 3});

but when i use interpreter.run(input,output); it breaks with the message

Cannot copy from a TensorFlowLite tensor (StatefulPartitionedCall:0) with shape [1, 1, 1, 3] to a Java object with shape [1, 1024, 1024, 3].

the output shape should be [1, 1024, 1024, 3] but it isn't.

interpreter.getOutputTensor(0).shapeSignature() and
interpreter.getInputTensor(0).shapeSignature()

return [-1, -1, -1, 3]
but i can't change the actual shape you get from

interpreter.getOutputTensor(0).shape()

the way i did with the input by using interpreter.resizeInput(0, new int[] {1, image_size, image_size, 3});

is there a way to implement a tflitemodel that transformes images of variable resolution
into other images of the same resolution somehow?
I am pretty sure it works before i convert it to tflite


问:
Laravel dump() function and memory leaks
I had a memory leak problem inside a custom artisan command I made for a project.
This method made some operations and, for debugging purpose, I printed to terminal many times the variables used in the script using dump() (the laravel helper function that replaces var_dump and print_r).
The problem was that the memory used increased on every iteration of the loop causing a fatal error.
I lost many hours finding out what was the problem, and finally I found the solution: I stopped using dump() function inside the script.
Is it possible that multiple dump() calls increase memory usage? And why?</p>


问:
Scala, ZIO, Json - how to deserialize circe json response?
I have a strange problem with deserialization from external service. I have some lib where I call method and pass params. This method always returns zio.IO[Error, Value].
Inside this lib some magic happens, it connects with other service, get response and return it to me. I create a simple for comprehension example, where I call this method:

```<code>for {
  response <- library.someMethod(firstParam, secondParam).map(value => value.code).mapError(error => showError(error))
} yield response
</code>```

Error and Value here zio.IO[Error, Value] are some custom objects. When I ran this for comprehension code, I got an error, connected with serialization:

```<code>The Either on which value was invoked was not defined as a Right; it was Left(sttp.client3.DeserializationException: expected json value got 'Intern...' (line 1, column 1)).
org.scalatest.exceptions.TestFailedException: The Either on which value was invoked was not defined as a Right; it was Left(sttp.client3.DeserializationException: expected json value got 'Intern...' (line 1, column 1)).
    at org.scalatest.EitherValues$Valuable.value(EitherValues.scala:211)
</code>```

I'm not sure if I need additional decoders or I should change something in for comprehension code to deserialize this value and error? Is it possible to deserialize response and take value correctly?

Body:
I have a strange problem with deserialization from external service. I have some lib where I call method and pass params. This method always returns zio.IO[Error, Value].
Inside this lib some magic happens, it connects with other service, get response and return it to me. I create a simple for comprehension example, where I call this method:

for {
  response <- library.someMethod(firstParam, secondParam).map(value => value.code).mapError(error => showError(error))
} yield response

Error and Value here zio.IO[Error, Value] are some custom objects. When I ran this for comprehension code, I got an error, connected with serialization:

The Either on which value was invoked was not defined as a Right; it was Left(sttp.client3.DeserializationException: expected json value got 'Intern...' (line 1, column 1)).
org.scalatest.exceptions.TestFailedException: The Either on which value was invoked was not defined as a Right; it was Left(sttp.client3.DeserializationException: expected json value got 'Intern...' (line 1, column 1)).
    at org.scalatest.EitherValues$Valuable.value(EitherValues.scala:211)

I'm not sure if I need additional decoders or I should change something in for comprehension code to deserialize this value and error? Is it possible to deserialize response and take value correctly?


问:
Google One Tap Sign In With React and Firebase
I have a web-app completely based in react, we use firebase for authentication and maintain the copy in aws dynamo db as well. Authentication in our app is done via firebase completely.

We're trying to implement google one tap sign in.

I tried doing this via react-google-one-tap-login (https://www.npmjs.com/package/react-google-one-tap-login)

I used firebase's google web client id as the param.
Image

My code looks something like this:

```<code>useGoogleOneTapLogin({
onError: error => console.log("ERROR", error),
onSuccess: response => {
  console.log("SUCCESS", response)
},
googleAccountConfigs: {
  client_id: "xxxxxxxxxxxxx"
})}
</code>```

Although the prompt is visible yet when I tap on the profile to sign in, I get the following message.

Image

The current origin isn't registered with Google OAuth Client

I tried checking the authorised domains, but I already have them configured properly. (I'm testing in my local)

I tried searching around in stack overflow and looking at some tutorials, I did all of them trying to add the port numbers, deleting the cache, restarting the app.

For some reason tutorials are using Google Cloud Credentials (https://console.cloud.google.com/apis/credentials), which I'm not sure, would work in my case, since I'd want firebase + dynamo to be the source of truth in my case.

I'm stuck and probably doing something silly.

Body:
I have a web-app completely based in react, we use firebase for authentication and maintain the copy in aws dynamo db as well. Authentication in our app is done via firebase completely.

We're trying to implement google one tap sign in.

I tried doing this via react-google-one-tap-login (https://www.npmjs.com/package/react-google-one-tap-login)

I used firebase's google web client id as the param.
Image

My code looks something like this:

useGoogleOneTapLogin({
onError: error => console.log("ERROR", error),
onSuccess: response => {
  console.log("SUCCESS", response)
},
googleAccountConfigs: {
  client_id: "xxxxxxxxxxxxx"
})}

Although the prompt is visible yet when I tap on the profile to sign in, I get the following message.

Image

The current origin isn't registered with Google OAuth Client

I tried checking the authorised domains, but I already have them configured properly. (I'm testing in my local)

I tried searching around in stack overflow and looking at some tutorials, I did all of them trying to add the port numbers, deleting the cache, restarting the app.

For some reason tutorials are using Google Cloud Credentials (https://console.cloud.google.com/apis/credentials), which I'm not sure, would work in my case, since I'd want firebase + dynamo to be the source of truth in my case.

I'm stuck and probably doing something silly.


问:
Bootstrap collapse plugin and complexity in rendering pdf after expanding all collapsible elements
I have 3+ collapsed elements in my html. They have ids for e.g.collapse1, collapse2 and collapse3.
I have to generate a PDF with all the collapsed elements shown (expanded).
Some of the elements might be expanded by user. So if an element is not expanded
I need to use javascript to expand and show the item and finally render the PDF.

There are few problems I faced.

If I use javascript collapse plugin, and show collapsed item, its asynchronous.
I have to subscribe to "shown.bs.collapse" event and inside the event handler I have to render PDF.

"shown.bs.collapse" event is not fired when an element is already opened. Because of this
I need to create flags to determine whether element is already shown and need to write if / else
logic to resolve this.

Below is the complex logic I wrote (its only pseudo code). Can this be simplified?

downloadPDF() {

```<code>flag1 = collapse1.hasClass('show')
flag2 = collapse2.hasClass('show')
flag3 = collapse3.hasClass('show')

$("#collapse1").on('shown.bs.collapse', function() {
    if (!flag2)
        collapse2.show()
    else
        if (!flag3) {
            collapse3.show();
        } else {
            generatePDF()
        }
}

$("#collapse2").on('shown.bs.collapse', function(){
    if (!flag3)
        collapse3.show()
    else
        generatePDF()
}

$("#collapse3").on('shown.bs.collapse', function(){
    generatePDF()
}

if (!flag1) {
    collapse1.show()
}

if (flag1 && !flag2) {
    collapse2.show();
}

if (flag1 && flag2 && !flag3) {
    collapse3.show();
}

if (flag1 && flag2 && flag3) {
    generatePDF();
}
</code>```

}

Body:
I have 3+ collapsed elements in my html. They have ids for e.g.collapse1, collapse2 and collapse3.
I have to generate a PDF with all the collapsed elements shown (expanded).
Some of the elements might be expanded by user. So if an element is not expanded
I need to use javascript to expand and show the item and finally render the PDF.

There are few problems I faced.

If I use javascript collapse plugin, and show collapsed item, its asynchronous.
I have to subscribe to "shown.bs.collapse" event and inside the event handler I have to render PDF.

"shown.bs.collapse" event is not fired when an element is already opened. Because of this
I need to create flags to determine whether element is already shown and need to write if / else
logic to resolve this.

Below is the complex logic I wrote (its only pseudo code). Can this be simplified?

downloadPDF() {

flag1 = collapse1.hasClass('show')
flag2 = collapse2.hasClass('show')
flag3 = collapse3.hasClass('show')

$("#collapse1").on('shown.bs.collapse', function() {
    if (!flag2)
        collapse2.show()
    else
        if (!flag3) {
            collapse3.show();
        } else {
            generatePDF()
        }
}

$("#collapse2").on('shown.bs.collapse', function(){
    if (!flag3)
        collapse3.show()
    else
        generatePDF()
}

$("#collapse3").on('shown.bs.collapse', function(){
    generatePDF()
}

if (!flag1) {
    collapse1.show()
}

if (flag1 && !flag2) {
    collapse2.show();
}

if (flag1 && flag2 && !flag3) {
    collapse3.show();
}

if (flag1 && flag2 && flag3) {
    generatePDF();
}

}


问:
How to maintain simple database in git?
I have a JSON (multiline) file with lots of project settings and a list of included modules for a few projects. It's version-controlled by git with the same repository as my projects. It is constantly growing and works just fine to set up and tune my projects. The only problem is, when working with team and branches I constantly have merge conflicts that need to be solved manually, and 99% of cases is "use both" because it's just new entries. So what are the alternatives? I need to have the same version and branching in this database since it has project settings and dependencies, but I want to reduce conflicts to a minimum. And I do not want a separate database, that I need to maintain in parallel with git, they need to perfectly sync automatically when switching between different branches or commits. Thanks!</p>

Title: How to maintain simple database in git?


问:
There is a very unusual output I got to see in Javascript loops while working with array
When I iterate using for loop the output shows 7 undefined indexes but for the same in forEach loop it does not show that. And If I assign "undefined" to any of the indexes, It shows in foreach loop.
Why is that?
This is the code snippet:

let x = [1, 2, 3];
x[10] = 55; // explicitly passing value to 10th index of array

for (let i = 0; i < x.length; i++) {
  console.log(x[i]);
}

x.forEach((item) => {
  console.log(item);
});```
</div>
</div>
</p>
<p>Output:</p>
<p>for loop output:</p>
```1
2
3
7 <undefined>
55
```
<p>forEach loop output:</p>
```1
2
3
55
```

Body:
When I iterate using for loop the output shows 7 undefined indexes but for the same in forEach loop it does not show that. And If I assign "undefined" to any of the indexes, It shows in foreach loop.
Why is that?
This is the code snippet:

let x = [1, 2, 3];
x[10] = 55; // explicitly passing value to 10th index of array

for (let i = 0; i < x.length; i++) {
  console.log(x[i]);
}

x.forEach((item) => {
  console.log(item);
});

Output:

for loop output:

1
2
3
7 <undefined>
55

forEach loop output:

1
2
3
55


问:
Django sitemap category page location not working
I made sitemap to my site but i have some problems.

First problem is end of the sitemap.xml page, lots of codes in it, but how can i remove these lines.
Here is my sitemap https://www.endustri.io/sitemap.xml

And here is the codes which i wanna remove...

And Second problem is
I have category page forexample: https://www.endustri.io/kategori/makine/

When i make sitemap class like this

```<code>class CategorySitemap(Sitemap):
    changefreq = 'weekly'
    priority = 0.8

    def items(self):
        return Category.objects.all()

    def lastmod(self, obj):
        return obj.date_added
</code>```

In sitemap my category links be like this https://www.endustri.io/makine/ but it must be like this https://www.endustri.io/kategori/makine/

How can i fix this?

```<code>Here is my model.py
from django.db import models
from django.contrib.auth.models import User
from tinymce import models as tinymce_models
from django.urls import reverse

class Category(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'Categories'

    def __str__(self):
        return str(self.title)

    def get_absolute_url(self):
        return reverse('detail', args=[str(self.slug)])

class Post(models.Model):
    category = models.ForeignKey(Category, related_name="posts", on_delete=models.CASCADE)
    title = models.CharField(max_length=300)
    slug = models.SlugField(max_length=300)
    intro = models.TextField()
    body = tinymce_models.HTMLField()
    description = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    featured_photo = models.ImageField(null=True, blank=True, upload_to="blog/")
    date_added = models.DateTimeField(auto_now_add=True)
    num_reads = models.PositiveIntegerField(default=0)

    def __str__(self):
        return str(self.title)

    def get_absolute_url(self):
        return reverse('detail', args=[str(self.slug)])
</code>```

And sitemaps.py

```<code>from django.contrib.sitemaps import Sitemap
from .models import Post, Category
from django.urls import reverse

class PostSitemap(Sitemap):
    changefreq = 'weekly'
    priority = 0.9

    def items(self):
        return Post.objects.all().order_by('-id')

    def lastmod(self, obj):
        return obj.date_added

class CategorySitemap(Sitemap):
    changefreq = 'weekly'
    priority = 0.8

    def items(self):
        return Category.objects.all()

    def lastmod(self, obj):
        return obj.date_added
</code>```

Body:
I made sitemap to my site but i have some problems.

First problem is end of the sitemap.xml page, lots of codes in it, but how can i remove these lines.
Here is my sitemap https://www.endustri.io/sitemap.xml

And here is the codes which i wanna remove...

And Second problem is
I have category page forexample: https://www.endustri.io/kategori/makine/

When i make sitemap class like this

class CategorySitemap(Sitemap):
    changefreq = 'weekly'
    priority = 0.8

    def items(self):
        return Category.objects.all()

    def lastmod(self, obj):
        return obj.date_added

In sitemap my category links be like this https://www.endustri.io/makine/ but it must be like this https://www.endustri.io/kategori/makine/

How can i fix this?

Here is my model.py
from django.db import models
from django.contrib.auth.models import User
from tinymce import models as tinymce_models
from django.urls import reverse

class Category(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'Categories'

    def __str__(self):
        return str(self.title)

    def get_absolute_url(self):
        return reverse('detail', args=[str(self.slug)])

class Post(models.Model):
    category = models.ForeignKey(Category, related_name="posts", on_delete=models.CASCADE)
    title = models.CharField(max_length=300)
    slug = models.SlugField(max_length=300)
    intro = models.TextField()
    body = tinymce_models.HTMLField()
    description = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    featured_photo = models.ImageField(null=True, blank=True, upload_to="blog/")
    date_added = models.DateTimeField(auto_now_add=True)
    num_reads = models.PositiveIntegerField(default=0)

    def __str__(self):
        return str(self.title)

    def get_absolute_url(self):
        return reverse('detail', args=[str(self.slug)])

And sitemaps.py

from django.contrib.sitemaps import Sitemap
from .models import Post, Category
from django.urls import reverse

class PostSitemap(Sitemap):
    changefreq = 'weekly'
    priority = 0.9

    def items(self):
        return Post.objects.all().order_by('-id')

    def lastmod(self, obj):
        return obj.date_added

class CategorySitemap(Sitemap):
    changefreq = 'weekly'
    priority = 0.8

    def items(self):
        return Category.objects.all()

    def lastmod(self, obj):
        return obj.date_added


问:
Is there a way I can change a cell that holds data into a table using functions?
When converting data from PDF's into excel I have run into an issue where instead of giving me the table in a table format, it comes out in a single cell separated by spaces. I have been dealing with this issue for a while.

Here is an example of what the PDF converter will give me

The data in the left and right column are Identical in this case, but this is not the norm.

I have tried a few things. My first formula returns a single column of data, but each cell in the column has two data points.

```<code>=TRANSPOSE(TEXTSPLIT(D2,CHAR(10),,TRUE))
</code>```

My second returns a single column of data, but only the first desired column.

```<code>=TEXTSPLIT(TRANSPOSE(TEXTSPLIT(D2,CHAR(10),"##0.00")),CHAR(32))
</code>```

How do I turn this into a 2 column table with a formula?

Body:
When converting data from PDF's into excel I have run into an issue where instead of giving me the table in a table format, it comes out in a single cell separated by spaces. I have been dealing with this issue for a while.

Here is an example of what the PDF converter will give me

The data in the left and right column are Identical in this case, but this is not the norm.

I have tried a few things. My first formula returns a single column of data, but each cell in the column has two data points.

=TRANSPOSE(TEXTSPLIT(D2,CHAR(10),,TRUE))

My second returns a single column of data, but only the first desired column.

=TEXTSPLIT(TRANSPOSE(TEXTSPLIT(D2,CHAR(10),"##0.00")),CHAR(32))

How do I turn this into a 2 column table with a formula?


问:
attempt to get length of a nil value (field 'animation')
I have a Problem and I don't know how to fix it. When trying to access the animations menu, the menu wont open. Then closes completely it wont answer anymore until I restart it.

The console spits out this:

SCRIPT ERROR: @krz_personalmenu_master/client/main.lua:845: attempt to get length of a nil value (field 'animation')

Here is the part of the script it states in the error:

function RenderAnimationMenu()
    RageUI.DrawContent({header = true, instructionalButton = true}, function()
        for i = 1, #RMenu['animation'], 1 do
            RageUI.Button(RMenu['animation'][i].Menu.Title, nil, {RightLabel = "→→→"}, true, function() end, RMenu['animation'][i].Menu)
        end
    end)
end
```

I tried to access the Animation Menu in the Personal Menu.

Body:
I have a Problem and I don't know how to fix it. When trying to access the animations menu, the menu wont open. Then closes completely it wont answer anymore until I restart it.

The console spits out this:

SCRIPT ERROR: @krz_personalmenu_master/client/main.lua:845: attempt to get length of a nil value (field 'animation')

Here is the part of the script it states in the error:

function RenderAnimationMenu()
    RageUI.DrawContent({header = true, instructionalButton = true}, function()
        for i = 1, #RMenu['animation'], 1 do
            RageUI.Button(RMenu['animation'][i].Menu.Title, nil, {RightLabel = "→→→"}, true, function() end, RMenu['animation'][i].Menu)
        end
    end)
end

I tried to access the Animation Menu in the Personal Menu.


问:
After upgrading Spring Boot version to 2.7 Flowable engine not able create table
I have updated spring-boot-starter-parent dependency version to 2.7.1 and flowable-engine to 6.8.0
then after when I am running JUnit test cases then I am getting below error

```<code>> nested exception is org.flowable.common.engine.api.FlowableException: couldn’t create db schema: create table ACT_HI_TSK_LOG (column names .....)
..
..
..
Caused by: org.h2.jdbc.JdbcSqlNonTransmissionException: Unknown data type: "IDENTITY"; SQL Statement: create table ACT_HI_TSK_LOG (ID_ identity, TYPE_ varchar(64), TASK_ID_ varchar(64) not null, .....)
</code>```

Getting same error for creating ACT_EVT_LOG table

I don't have defined or written this tables and I think this is coming from the flowable-engine dependency.

Dependencies which I have used :

<dependency>
    <groupId>org.flowable</groupId>
    <artifactId>flowable-engine</artifactId>
    <version>6.8.0</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.1</version>
    <type>pom</type>
</dependency>
```
<p>Can someone help me on this please.</p>
<p>If I am using Spring <code>2.6.x</code> version then it's working fine and all JUnit test cases are getting passed</p>
<p><strong>GETTING BELOW ERROR AFTER UPGRADING THE SPRING-BOOT-STARTER-PARENT v2.7.7</strong></p>
<blockquote>
<p>H2 is on v1.4.200 And flowable-engine v6.8.0</p>
</blockquote>
```Error creating bean with name 'processEngine': FactoryBean threw the exception on object creation; nested exception is java.lang.RuntimeException: Exception while initializing Database connection at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:660) .........
................
ommitted caused by: java.lang.RuntimeException: Exception while initializing Database connection at
...................
......................
org.flowable.spring/SpringProcessEngineConfiguration.buildProcessEngine(SpringProcessEngineConfiguration.java:76) at org.flowable.spring.ProcessEngineFactoryBean.getObject(ProcessEngineFactoryBean.java:59) at
org.flowable.spring.ProcessEngineFactoryBean.getObject(ProcessEngineFactoryBean.java:32) at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:169) ... 65 common frames omitted Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The drive could not establish a secure connection to SQL Server by using Secure Socket Layer (SSL) exception. Error: "PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target". ClientConnectionId:a31221-r15-erer-gdf45451 at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:3680) at
com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:2047) at
com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:3204) at
com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2833) at
com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:2671) at
```

Body:
I have updated spring-boot-starter-parent dependency version to 2.7.1 and flowable-engine to 6.8.0
then after when I am running JUnit test cases then I am getting below error

> nested exception is org.flowable.common.engine.api.FlowableException: couldn’t create db schema: create table ACT_HI_TSK_LOG (column names .....)
..
..
..
Caused by: org.h2.jdbc.JdbcSqlNonTransmissionException: Unknown data type: "IDENTITY"; SQL Statement: create table ACT_HI_TSK_LOG (ID_ identity, TYPE_ varchar(64), TASK_ID_ varchar(64) not null, .....)

Getting same error for creating ACT_EVT_LOG table

I don't have defined or written this tables and I think this is coming from the flowable-engine dependency.

Dependencies which I have used :

<dependency>
    <groupId>org.flowable</groupId>
    <artifactId>flowable-engine</artifactId>
    <version>6.8.0</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.1</version>
    <type>pom</type>
</dependency>

Can someone help me on this please.

If I am using Spring 2.6.x version then it's working fine and all JUnit test cases are getting passed

GETTING BELOW ERROR AFTER UPGRADING THE SPRING-BOOT-STARTER-PARENT v2.7.7

H2 is on v1.4.200 And flowable-engine v6.8.0

Error creating bean with name 'processEngine': FactoryBean threw the exception on object creation; nested exception is java.lang.RuntimeException: Exception while initializing Database connection at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:660) .........
................
ommitted caused by: java.lang.RuntimeException: Exception while initializing Database connection at
...................
......................
org.flowable.spring/SpringProcessEngineConfiguration.buildProcessEngine(SpringProcessEngineConfiguration.java:76) at org.flowable.spring.ProcessEngineFactoryBean.getObject(ProcessEngineFactoryBean.java:59) at
org.flowable.spring.ProcessEngineFactoryBean.getObject(ProcessEngineFactoryBean.java:32) at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:169) ... 65 common frames omitted Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The drive could not establish a secure connection to SQL Server by using Secure Socket Layer (SSL) exception. Error: "PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target". ClientConnectionId:a31221-r15-erer-gdf45451 at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:3680) at
com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:2047) at
com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:3204) at
com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2833) at
com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:2671) at


问:
VisualVM is stopped by Cylance protect antivirus
By enterprise policy, we have to run Cylance protect antivirus on our workstations. It cannot be suspended or uninstalled.
I can start VisualVM, but when I try to connect to a process, a message is displayed by Cylance protect that the process of VisualVM was stopped because it was "recognized as a threat".
Edit: I see VisualVM's start page where the Java processes, including VisualVM and Eclipse, are displayed. As soon as I select a process and try any action (monitor, profile, etc.) Cylance pops up and hard terminates VisualVM. The Java processes keep running.
The tech team thinks this comes from VisualVM trying to access another process' memory.

My system: Java 11, Eclipse 2022-12, Windows 11.

We tested for a short time with Cylance disabled and then the profiling worked.
(I needed some time to talk my tech team into that so this does not seem to be a practicable solution.)
I don't expect this to change with the Java or Eclipse version. Was already the same with Java 8 and / or elder Eclipse versions.
Has anybody the same constellation and knows how to configure a rule in Cylance that profiling with VisualVM is possible?


问:
R script error : attempt to apply non-function
I am trying to code the Gravitational Search Algorithm in R language to tune Xgboost, but I am facing an error: Error in xgb_model$set_params(as.list(particle_positions[i, ])) :  attempt to apply non-function
The error appears when I try to evaluate the initial position:

```<code># Evaluate the initial particle positions
for (i in 1:n_particles) {

  xgb_model$set_params(as.list(particle_positions[i, ]))
  resampling <- trainControl(method = "repeatedcv", number = 5, repeats = 5, verboseIter = FALSE)
  model_fit <- train(
    x = as.matrix(train[, -15]), y = train[, 15],
    method = "xgbTree", trControl = resampling,
    metric = "Accuracy", tuneLength = 0,
    maximize = TRUE
  )
  best_positions[i, ] <- particle_positions[i, ]
  best_values[i] <- model_fit$results[1, "Accuracy"]
}
</code>```

Any idea what I am doing wrong?

Body:
I am trying to code the Gravitational Search Algorithm in R language to tune Xgboost, but I am facing an error: Error in xgb_model$set_params(as.list(particle_positions[i, ])) :  attempt to apply non-function
The error appears when I try to evaluate the initial position:

# Evaluate the initial particle positions
for (i in 1:n_particles) {

  xgb_model$set_params(as.list(particle_positions[i, ]))
  resampling <- trainControl(method = "repeatedcv", number = 5, repeats = 5, verboseIter = FALSE)
  model_fit <- train(
    x = as.matrix(train[, -15]), y = train[, 15],
    method = "xgbTree", trControl = resampling,
    metric = "Accuracy", tuneLength = 0,
    maximize = TRUE
  )
  best_positions[i, ] <- particle_positions[i, ]
  best_values[i] <- model_fit$results[1, "Accuracy"]
}

Any idea what I am doing wrong?


问:
I can't set up a proxy in Vite
I need to set up a proxy in Vite for CORS. I have tried different settings. I keep getting the CORS problem in the browser.

Access to load at 'http://localhost:3000/api/login' from origin 'http://localhost:5173' has been blocked by CORS policy: no 'Access-Control-Allow-Origin' header is present for the requested resource. If an opaque response serves you, set the request mode to 'no-cors' to retrieve the CORS-disabled resource.

I have this setting

```<code> proxy: {
  '/api': {
       target: 'https://localhost:3000',
       changeOrigin: true,
       secure: false,
   }
}
</code>```

Title: I can't set up a proxy in Vite

Body:
I need to set up a proxy in Vite for CORS. I have tried different settings. I keep getting the CORS problem in the browser.

Access to load at 'http://localhost:3000/api/login' from origin 'http://localhost:5173' has been blocked by CORS policy: no 'Access-Control-Allow-Origin' header is present for the requested resource. If an opaque response serves you, set the request mode to 'no-cors' to retrieve the CORS-disabled resource.

I have this setting

 proxy: {
  '/api': {
       target: 'https://localhost:3000',
       changeOrigin: true,
       secure: false,
   }
}


问:
WS-Security policy and security token, Error in obtaining token from WSO2
I'm developing a WSO2 API to invoke a specific service protected by SAML token. For the security, this is a two-step authentication process. First the service consumer (me) has to authenticate to the
SecurityTokenService using X.509 direct authentication. The STS issues a signed SAML token claiming the consumers identity. In a second request the service consumer
calls the business service and includes the received SAML token and a timestamp within the wsse:Security header.
So, I need to access SAML-secured service via WSO2 ESB.

For the first part, I successfully got the token.  For the 2nd request I included this process of generating a token (as a Issuer) to a policy:

https://pastebin.com/jgUDzDT6

But my code for the second part doesn't work in ESB, it returns ErrorInObtainingToken.
And I don't understand how to send already received token in a proper way. Could you please help me?

I used the policy file provided by the service, compared it to the one generated automatically in WSO2 Integration Studio, added and deleted lines, the result is always the same:

```<code>[PassThroughMessageProcessor-126] ERROR {org.apache.rahas.client.STSClient} - errorInObtainingToken
Caused by: org.apache.rahas.TrustException: Error in obtaining token from : "http://localhost:8280/.../token"
[-1234] [] [PassThroughMessageProcessor-130] ERROR {org.apache.axis2.engine.AxisEngine} - Message Receiver not found for AxisOperation: requestSecurityToken
org.apache.axis2.AxisFault: Message Receiver not found for AxisOperation: requestSecurityToken
</code>```

Body:
I'm developing a WSO2 API to invoke a specific service protected by SAML token. For the security, this is a two-step authentication process. First the service consumer (me) has to authenticate to the
SecurityTokenService using X.509 direct authentication. The STS issues a signed SAML token claiming the consumers identity. In a second request the service consumer
calls the business service and includes the received SAML token and a timestamp within the wsse:Security header.
So, I need to access SAML-secured service via WSO2 ESB.

For the first part, I successfully got the token.  For the 2nd request I included this process of generating a token (as a Issuer) to a policy:

https://pastebin.com/jgUDzDT6

But my code for the second part doesn't work in ESB, it returns ErrorInObtainingToken.
And I don't understand how to send already received token in a proper way. Could you please help me?

I used the policy file provided by the service, compared it to the one generated automatically in WSO2 Integration Studio, added and deleted lines, the result is always the same:

[PassThroughMessageProcessor-126] ERROR {org.apache.rahas.client.STSClient} - errorInObtainingToken
Caused by: org.apache.rahas.TrustException: Error in obtaining token from : "http://localhost:8280/.../token"
[-1234] [] [PassThroughMessageProcessor-130] ERROR {org.apache.axis2.engine.AxisEngine} - Message Receiver not found for AxisOperation: requestSecurityToken
org.apache.axis2.AxisFault: Message Receiver not found for AxisOperation: requestSecurityToken


问:
There is not this file and I get ERROR in ./node_modules/@mui/x-date-pickers/node_modules/@mui/utils/esm/index.js
I am trying to use @mui/x-data-grid-premium trial version.

Before the npm install @mui/x-data-grid-premium everything works fine. After the installation, I changed DataGrid to DataGridPremium and I saved the file then my site shows the following error
`ERROR in ./node_modules/@mui/x-date-pickers/node_modules/@mui/utils/esm/index.js

Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: ENOENT: no such file or directory, open 'C:\Users..\frontend\node_modules@mui\x-date-pickers\node_modules@mui\utils\esm\index.js'`


问:
Issue with the library ScrollReveal with bootsrap tabs
I have a problem with the ScrollReveal library when loading an animation inside bootstrap tabs (I use bootstrap 5). In the first tab it works fine but in the others it doesn't. It seems as if it doesn't recognize the scroll because the elements are hidden by the library but it never shows them.

The funny thing is that when I open the explorer inspector it starts working on that tab and stops working on the others.

I already tried trying to reload the javascript when I change the tab, but nothing changes.

I replicated this in codepen so you can see it:

```<code> ScrollReveal({
      reset: true
    });
    ScrollReveal().reveal('.reveal_left', {
      delay: 800,
      origin: 'left',
      distance: '-500px'
    })
.square{
  width:100px;
  height: 100px;
  background-color:red;
  color:#fff;
}
h4{
  color:blue;
  margin-bottom: 1rem;
  text-align:center
}
<script src="https://unpkg.com/scrollreveal"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.2/css/bootstrap.min.css" rel="stylesheet"/>

<h4>Al final de cada tab se encuentra el objeto square con la animacion de ScrollReveal: </h4>
<div class="d-flex align-items-start">
  <div class="nav flex-column nav-pills me-3" id="v-pills-tab" role="tablist" aria-orientation="vertical">
    <button class="nav-link active" id="v-pills-home-tab" data-bs-toggle="pill" data-bs-target="#v-pills-home" type="button" role="tab" aria-controls="v-pills-home" aria-selected="true">Home</button>
    <button class="nav-link" id="v-pills-profile-tab" data-bs-toggle="pill" data-bs-target="#v-pills-profile" type="button" role="tab" aria-controls="v-pills-profile" aria-selected="false">Profile</button>
    <button class="nav-link" id="v-pills-messages-tab" data-bs-toggle="pill" data-bs-target="#v-pills-messages" type="button" role="tab" aria-controls="v-pills-messages" aria-selected="false">Messages</button>
    <button class="nav-link" id="v-pills-settings-tab" data-bs-toggle="pill" data-bs-target="#v-pills-settings" type="button" role="tab" aria-controls="v-pills-settings" aria-selected="false">Settings</button>
  </div>

  <div class="tab-content" id="v-pills-tabContent">
    <div class="tab-pane fade show active" id="v-pills-home" role="tabpanel" aria-labelledby="v-pills-home-tab">
      <h1>Home Section </h1>
      <p>Lorem ipsum dolor sit amet consectetur adipiscing, elit blandit ac augue venenatis semper, quisque urna lobortis nisl hac. Senectus dapibus faucibus aliquam sodales dignissim dui vestibulum curae in proin, lectus nam magna eget inceptos malesuada lacinia tempus tristique, eu iaculis neque at quisque platea fringilla duis erat. Et turpis arcu duis conubia leo auctor purus, himenaeos class mus sollicitudin ante praesent, scelerisque mollis egestas feugiat massa aptent. Cursus curae aliquet penatibus magna et lobortis metus augue, faucibus posuere nisi donec malesuada nam neque.

Orci risus scelerisque pulvinar mauris turpis a, suspendisse dui hendrerit phasellus conubia est velit, dictumst praesent nisl vivamus ultricies. Primis ornare fringilla natoque montes erat netus litora viverra mi, turpis nostra purus malesuada odio porttitor cum hendrerit suspendisse praesent, risus pharetra tellus ridiculus in nec cubilia fames. Habitant non mauris etiam libero iaculis aptent ultricies nullam, vulputate nisi bibendum egestas tincidunt scelerisque integer.</p>
      <div class="reveal_left square">
        square with revela class
      </div>
    </div>
    <div class="tab-pane fade" id="v-pills-profile" role="tabpanel" aria-labelledby="v-pills-profile-tab">
            <h1>Profile </h1>
        <p>Lorem ipsum dolor sit amet consectetur adipiscing, elit blandit ac augue venenatis semper, quisque urna lobortis nisl hac. Senectus dapibus faucibus aliquam sodales dignissim dui vestibulum curae in proin, lectus nam magna eget inceptos malesuada lacinia tempus tristique, eu iaculis neque at quisque platea fringilla duis erat. Et turpis arcu duis conubia leo auctor purus, himenaeos class mus sollicitudin ante praesent, scelerisque mollis egestas feugiat massa aptent. Cursus curae aliquet penatibus magna et lobortis metus augue, faucibus posuere nisi donec malesuada nam neque.

Orci risus scelerisque pulvinar mauris turpis a, suspendisse dui hendrerit phasellus conubia est velit, dictumst praesent nisl vivamus ultricies. Primis ornare fringilla natoque montes erat netus litora viverra mi, turpis nostra purus malesuada odio porttitor cum hendrerit suspendisse praesent, risus pharetra tellus ridiculus in nec cubilia fames. Habitant non mauris etiam libero iaculis aptent ultricies nullam, vulputate nisi bibendum egestas tincidunt scelerisque integer.</p>
          <div class="reveal_left square">
        square with revela class
      </div>
    </div>
    <div class="tab-pane fade" id="v-pills-messages" role="tabpanel" aria-labelledby="v-pills-messages-tab">
            <h1>Messages</h1>
        <p>Lorem ipsum dolor sit amet consectetur adipiscing, elit blandit ac augue venenatis semper, quisque urna lobortis nisl hac. Senectus dapibus faucibus aliquam sodales dignissim dui vestibulum curae in proin, lectus nam magna eget inceptos malesuada lacinia tempus tristique, eu iaculis neque at quisque platea fringilla duis erat. Et turpis arcu duis conubia leo auctor purus, himenaeos class mus sollicitudin ante praesent, scelerisque mollis egestas feugiat massa aptent. Cursus curae aliquet penatibus magna et lobortis metus augue, faucibus posuere nisi donec malesuada nam neque.

Orci risus scelerisque pulvinar mauris turpis a, suspendisse dui hendrerit phasellus conubia est velit, dictumst praesent nisl vivamus ultricies. Primis ornare fringilla natoque montes erat netus litora viverra mi, turpis nostra purus malesuada odio porttitor cum hendrerit suspendisse praesent, risus pharetra tellus ridiculus in nec cubilia fames. Habitant non mauris etiam libero iaculis aptent ultricies nullam, vulputate nisi bibendum egestas tincidunt scelerisque integer.</p>
              <div class="reveal_left square">
        square with revela class
      </div>
    </div>
    <div class="tab-pane fade" id="v-pills-settings" role="tabpanel" aria-labelledby="v-pills-settings-tab">
            <h1>Settings</h1>
              <div class="reveal_left square">
        square with revela class
      </div>
    </div>
  </div>
</div>
</code>```

My complete code

I appreciate your help.

Body:
I have a problem with the ScrollReveal library when loading an animation inside bootstrap tabs (I use bootstrap 5). In the first tab it works fine but in the others it doesn't. It seems as if it doesn't recognize the scroll because the elements are hidden by the library but it never shows them.

The funny thing is that when I open the explorer inspector it starts working on that tab and stops working on the others.

I already tried trying to reload the javascript when I change the tab, but nothing changes.

I replicated this in codepen so you can see it:

 ScrollReveal({
      reset: true
    });
    ScrollReveal().reveal('.reveal_left', {
      delay: 800,
      origin: 'left',
      distance: '-500px'
    })
.square{
  width:100px;
  height: 100px;
  background-color:red;
  color:#fff;
}
h4{
  color:blue;
  margin-bottom: 1rem;
  text-align:center
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.2/css/bootstrap.min.css" rel="stylesheet"/>

Al final de cada tab se encuentra el objeto square con la animacion de ScrollReveal:

    <button class="nav-link active" id="v-pills-home-tab" data-bs-toggle="pill" data-bs-target="#v-pills-home" type="button" role="tab" aria-controls="v-pills-home" aria-selected="true">Home</button>
    <button class="nav-link" id="v-pills-profile-tab" data-bs-toggle="pill" data-bs-target="#v-pills-profile" type="button" role="tab" aria-controls="v-pills-profile" aria-selected="false">Profile</button>
    <button class="nav-link" id="v-pills-messages-tab" data-bs-toggle="pill" data-bs-target="#v-pills-messages" type="button" role="tab" aria-controls="v-pills-messages" aria-selected="false">Messages</button>
    <button class="nav-link" id="v-pills-settings-tab" data-bs-toggle="pill" data-bs-target="#v-pills-settings" type="button" role="tab" aria-controls="v-pills-settings" aria-selected="false">Settings</button>

Home Section

Lorem ipsum dolor sit amet consectetur adipiscing, elit blandit ac augue venenatis semper, quisque urna lobortis nisl hac. Senectus dapibus faucibus aliquam sodales dignissim dui vestibulum curae in proin, lectus nam magna eget inceptos malesuada lacinia tempus tristique, eu iaculis neque at quisque platea fringilla duis erat. Et turpis arcu duis conubia leo auctor purus, himenaeos class mus sollicitudin ante praesent, scelerisque mollis egestas feugiat massa aptent. Cursus curae aliquet penatibus magna et lobortis metus augue, faucibus posuere nisi donec malesuada nam neque.

Orci risus scelerisque pulvinar mauris turpis a, suspendisse dui hendrerit phasellus conubia est velit, dictumst praesent nisl vivamus ultricies. Primis ornare fringilla natoque montes erat netus litora viverra mi, turpis nostra purus malesuada odio porttitor cum hendrerit suspendisse praesent, risus pharetra tellus ridiculus in nec cubilia fames. Habitant non mauris etiam libero iaculis aptent ultricies nullam, vulputate nisi bibendum egestas tincidunt scelerisque integer.

        square with revela class

Profile

Lorem ipsum dolor sit amet consectetur adipiscing, elit blandit ac augue venenatis semper, quisque urna lobortis nisl hac. Senectus dapibus faucibus aliquam sodales dignissim dui vestibulum curae in proin, lectus nam magna eget inceptos malesuada lacinia tempus tristique, eu iaculis neque at quisque platea fringilla duis erat. Et turpis arcu duis conubia leo auctor purus, himenaeos class mus sollicitudin ante praesent, scelerisque mollis egestas feugiat massa aptent. Cursus curae aliquet penatibus magna et lobortis metus augue, faucibus posuere nisi donec malesuada nam neque.

Orci risus scelerisque pulvinar mauris turpis a, suspendisse dui hendrerit phasellus conubia est velit, dictumst praesent nisl vivamus ultricies. Primis ornare fringilla natoque montes erat netus litora viverra mi, turpis nostra purus malesuada odio porttitor cum hendrerit suspendisse praesent, risus pharetra tellus ridiculus in nec cubilia fames. Habitant non mauris etiam libero iaculis aptent ultricies nullam, vulputate nisi bibendum egestas tincidunt scelerisque integer.

        square with revela class

Messages

Lorem ipsum dolor sit amet consectetur adipiscing, elit blandit ac augue venenatis semper, quisque urna lobortis nisl hac. Senectus dapibus faucibus aliquam sodales dignissim dui vestibulum curae in proin, lectus nam magna eget inceptos malesuada lacinia tempus tristique, eu iaculis neque at quisque platea fringilla duis erat. Et turpis arcu duis conubia leo auctor purus, himenaeos class mus sollicitudin ante praesent, scelerisque mollis egestas feugiat massa aptent. Cursus curae aliquet penatibus magna et lobortis metus augue, faucibus posuere nisi donec malesuada nam neque.

Orci risus scelerisque pulvinar mauris turpis a, suspendisse dui hendrerit phasellus conubia est velit, dictumst praesent nisl vivamus ultricies. Primis ornare fringilla natoque montes erat netus litora viverra mi, turpis nostra purus malesuada odio porttitor cum hendrerit suspendisse praesent, risus pharetra tellus ridiculus in nec cubilia fames. Habitant non mauris etiam libero iaculis aptent ultricies nullam, vulputate nisi bibendum egestas tincidunt scelerisque integer.

        square with revela class

Settings

        square with revela class

My complete code

I appreciate your help.


问:
nestjs testing - how to start a server with jest mocked modules
I already have e2e backend tests running using jest and some mocked modules using fastify and now that when I use app.listen it will be able to receive calls.

My problem:

I would like to start the nestjs server with the mocked jest modules to be able to call it from outside without the jest scope e.g. for vulnerability scanning of the api endpoints. I have some external dependencies that I want to exclude - this is why I would like to use my jest mocked nestjs modules.

if I try to used ts-node an error will be thrown in those mocked modules

command:

```<code>npx ts-node run.ts
</code>```

file: run.ts

import { initializeApplication } from './app';

(async () => {
  const app = await initializeApplication();
  app.listen(3005, '0.0.0.0');
})();
```
<p><strong>error:</strong></p>
```jest.fn(
^
ReferenceError: jest is not defined
```

I would like to be able to start the nestjs backend with jest mocked nestjs modules to make external api calls against the backend using fake dependencies.

Body:
I already have e2e backend tests running using jest and some mocked modules using fastify and now that when I use app.listen it will be able to receive calls.

My problem:

I would like to start the nestjs server with the mocked jest modules to be able to call it from outside without the jest scope e.g. for vulnerability scanning of the api endpoints. I have some external dependencies that I want to exclude - this is why I would like to use my jest mocked nestjs modules.

if I try to used ts-node an error will be thrown in those mocked modules

command:

npx ts-node run.ts

file: run.ts

import { initializeApplication } from './app';

(async () => {
  const app = await initializeApplication();
  app.listen(3005, '0.0.0.0');
})();

error:

jest.fn(
^
ReferenceError: jest is not defined

I would like to be able to start the nestjs backend with jest mocked nestjs modules to make external api calls against the backend using fake dependencies.


问:
How to use LongPressDraggable in ListView on Flutter
I have a list of elements (listview widget) that can be moved to a target, (in the example I don't include the target to simplify, my question is in the listview). Each item in the list is a LongPressDraggable.

My problem is that when touching an element of the list, if the finger moves minimally, almost imperceptibly, then the longpress event does not fire, you have to lift your finger again and touch the element again.

In the LongPressDraggable I am setting the property delay: const Duration(milliseconds: 50), by default it has 500 ms and with this I have improved the user experience somewhat.

My question is the following: Is there any way to specify a clearance to the listview, that is, a minimum movement so that after that clearance it launches the scroll event and while not?

This is my code:

```<code>import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

Future<void> main() async {
  runApp(const MyApp2());
}

class MyApp2 extends StatelessWidget {
  const MyApp2({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      scrollBehavior: const MaterialScrollBehavior().copyWith(
          dragDevices: {PointerDeviceKind.mouse, PointerDeviceKind.touch}),
      title: 'ListView',
      home: Scaffold(
        body: getBody(context),
      ),
    );
  }

  Widget getBody(BuildContext context) {
    var list = <Widget>[];
    list.add(Container(height: 50, width: 100, color: Colors.black));
    list.add(Container(height: 50, width: 100, color: Colors.amber));
    list.add(Container(
        height: 50, width: 100, color: Color.fromARGB(255, 241, 150, 143)));
    list.add(Container(height: 50, width: 100, color: Colors.blue));
    list.add(Container(height: 50, width: 100, color: Colors.pink));
    list.add(Container(height: 50, width: 100, color: Colors.blueAccent));

    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(
          width: 10,
        ),

        SizedBox(
          width: 100,
          height: 200,
          child: ListView.builder(
              itemCount: list.length,
              itemBuilder: (context, index) {
                return Padding(
                  padding: const EdgeInsets.symmetric(vertical: 5),
                  child: LongPressDraggable<Widget>(
                      delay: const Duration(milliseconds: 50)
                      data: list[index],
                      feedback: AnimatedScale(
                          duration: const Duration(seconds: 1),
                          scale: 1.25,
                          child: list[index]),
                      childWhenDragging:
                          Opacity(opacity: 0.5, child: list[index]),
                      child: list[index]),
                );
              }),
        )
      ],
    );
  }
}
</code>```

Body:
I have a list of elements (listview widget) that can be moved to a target, (in the example I don't include the target to simplify, my question is in the listview). Each item in the list is a LongPressDraggable.

My problem is that when touching an element of the list, if the finger moves minimally, almost imperceptibly, then the longpress event does not fire, you have to lift your finger again and touch the element again.

In the LongPressDraggable I am setting the property delay: const Duration(milliseconds: 50), by default it has 500 ms and with this I have improved the user experience somewhat.

My question is the following: Is there any way to specify a clearance to the listview, that is, a minimum movement so that after that clearance it launches the scroll event and while not?

This is my code:

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

Future<void> main() async {
  runApp(const MyApp2());
}

class MyApp2 extends StatelessWidget {
  const MyApp2({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      scrollBehavior: const MaterialScrollBehavior().copyWith(
          dragDevices: {PointerDeviceKind.mouse, PointerDeviceKind.touch}),
      title: 'ListView',
      home: Scaffold(
        body: getBody(context),
      ),
    );
  }

  Widget getBody(BuildContext context) {
    var list = <Widget>[];
    list.add(Container(height: 50, width: 100, color: Colors.black));
    list.add(Container(height: 50, width: 100, color: Colors.amber));
    list.add(Container(
        height: 50, width: 100, color: Color.fromARGB(255, 241, 150, 143)));
    list.add(Container(height: 50, width: 100, color: Colors.blue));
    list.add(Container(height: 50, width: 100, color: Colors.pink));
    list.add(Container(height: 50, width: 100, color: Colors.blueAccent));

    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(
          width: 10,
        ),

        SizedBox(
          width: 100,
          height: 200,
          child: ListView.builder(
              itemCount: list.length,
              itemBuilder: (context, index) {
                return Padding(
                  padding: const EdgeInsets.symmetric(vertical: 5),
                  child: LongPressDraggable<Widget>(
                      delay: const Duration(milliseconds: 50)
                      data: list[index],
                      feedback: AnimatedScale(
                          duration: const Duration(seconds: 1),
                          scale: 1.25,
                          child: list[index]),
                      childWhenDragging:
                          Opacity(opacity: 0.5, child: list[index]),
                      child: list[index]),
                );
              }),
        )
      ],
    );
  }
}


问:
Convert Pymsql into pymongo command
Please anybody convert this command in to pymongo command how can I use this Pymsql command in to pymongo command please help anybody

```<code>
cur.execute("Select*from student where"
+Str(self.search__by.get())+"LIKE '%"+str(self.search__text.get())"%' ")
rows=cur.fetchall()
</code>```

This Pymsql command for search a student data by many options like name, roll number, contact in students management system please anybody help

Title: Convert Pymsql into pymongo command

Body:
Please anybody convert this command in to pymongo command how can I use this Pymsql command in to pymongo command please help anybody

cur.execute("Select*from student where"
+Str(self.search__by.get())+"LIKE '%"+str(self.search__text.get())"%' ")
rows=cur.fetchall()

This Pymsql command for search a student data by many options like name, roll number, contact in students management system please anybody help


问:
Data Replication failed between OpenDJ 2.6.4 and 4.4.11
We plan to upgrade our OpenDJ server(currently on 2.6.4) to 4.4.11. We decided to do the data migration by enabling replication between old and new servers. We were able to enable the replication between servers and the replication process got susccessfully completed. But the we checked the replication status, it is showing as 0 entries in the new OpenDJ server.

We found below error in the error log file,

Also when we check the data from Apache Directory studio we can see the data. But some records does not have values.

We followed this https://backstage.forgerock.com/knowledge/kb/article/a19631732 but it didnt fix the issue.


问:
How to recognize in powershell that the called gradle build has failed
I am using the following Start-Process call inside a for loop of my script. The aim is to abort the script if the called build has failed. Actually it does not do that. I think I know the reason but have no other way to solve this.

```<code>    $proc = Start-Process -FilePath 'C:\Windows\System32\cmd.exe' -ArgumentList '/c',
   "$currentProject\dev.bat clean build" -Wait -PassThru

if ($proc.ExitCode -eq 0){
    Write-Host "SUCCESS -->[$currentProject]"
}
else{
    Write-Error "BUILD-ERROR --> $currentProject please fix it first"
    Write-Host "call this manually: $currentProject\dev.bat clean build"
    break
}
</code>```

If somehow the build task failed it returns something like this

```<code>some error reports and finally this:
BUILD FAILED in 34s
6 actionable tasks: 3 executed, 3 up-to-date
</code>```

In this case my script into the success branch of the if / else because the Start-Process call returned success.

Any idea how I can recognize the "Build Failed" case?
Thanks

Body:
I am using the following Start-Process call inside a for loop of my script. The aim is to abort the script if the called build has failed. Actually it does not do that. I think I know the reason but have no other way to solve this.

    $proc = Start-Process -FilePath 'C:\Windows\System32\cmd.exe' -ArgumentList '/c',
   "$currentProject\dev.bat clean build" -Wait -PassThru

if ($proc.ExitCode -eq 0){
    Write-Host "SUCCESS -->[$currentProject]"
}
else{
    Write-Error "BUILD-ERROR --> $currentProject please fix it first"
    Write-Host "call this manually: $currentProject\dev.bat clean build"
    break
}

If somehow the build task failed it returns something like this

some error reports and finally this:
BUILD FAILED in 34s
6 actionable tasks: 3 executed, 3 up-to-date

In this case my script into the success branch of the if / else because the Start-Process call returned success.

Any idea how I can recognize the "Build Failed" case?
Thanks


问:
How to add drawer items to right drawer in multiple drawers in Reactnavigation
I want to add some drawer items to right drawer, like in left.
In official documentation https://reactnavigation.org/docs/multiple-drawers I found this:

```<code>function RightDrawerContent() {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>This is the right drawer</Text>
    </View>
  );
}
</code>```

And how to add drawer items to here?

Body:
I want to add some drawer items to right drawer, like in left.
In official documentation https://reactnavigation.org/docs/multiple-drawers I found this:

function RightDrawerContent() {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>This is the right drawer</Text>
    </View>
  );
}

And how to add drawer items to here?


问:
How to modify error message after executing a command via a Gradle task
I'm implementing a Gradle Java plugin which registers below task.

```<code>TaskProvider<Exec> taskProvider = project.getTasks().register("spectralTask", Exec.class);
taskProvider.configure(exec -> {
    exec.executable("spectral");
    exec.args("lint");
});
</code>```

When the output of the executed command is an error, this is what I get.

```<code>FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:spectralTask'.
> Process 'command 'spectral'' finished with non-zero exit value 1
</code>```

This error message is not very helpful. I want to fix it.
Is there a way to do below?

Print a custom error message.

Print the exact error message given by the executed command.

Body:
I'm implementing a Gradle Java plugin which registers below task.

TaskProvider<Exec> taskProvider = project.getTasks().register("spectralTask", Exec.class);
taskProvider.configure(exec -> {
    exec.executable("spectral");
    exec.args("lint");
});

When the output of the executed command is an error, this is what I get.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:spectralTask'.
> Process 'command 'spectral'' finished with non-zero exit value 1

This error message is not very helpful. I want to fix it.
Is there a way to do below?

Print a custom error message.

Print the exact error message given by the executed command.


问:
Change detection not happening after rxjs subject emits value
I'm not sure why change detection is not running in the case described below. My app is written in Ionic (v6.20.1) with Angular(14+)

I've read this: https://angular.io/guide/zone
, but I still don't see why it's not occuring.

Can someone clarify this please?

app.component.ts:

```<code>setupAppStateChange() {
  App.addListener('appStateChange', async ({ isActive }) => {
   if (!isActive) return

   if (this.location.isCurrentPathEqualTo('/wallet')) {
     this.walletService.refreshAmount()
   }
}
</code>```

Note: change detection works if i do this, but i want to understand why it's needed:

```<code>   this.zone.run(async () => {
      this.walletService.refreshAmount()
   })
</code>```

wallet.service.ts:

```<code>private _amount: number
private _amountChanged: Subject<number> = new Subject<number>()

async refreshAmount() {
    const wallet: Wallet = await Parse.Cloud.run('getWallet')
    this._amount = wallet.balance
    this._amountChanged.next(this._amount)
}
</code>```

wallet.page.ts:

```<code>private subscribeAmountChanged() {
    this.availableAmountChanged = this.walletService.amountChanged.subscribe({
      next: async (value) => {
        //hide topup screen
        this.isTopUp = false

        if (this.availableAmount != value) {
          //set new amount
          this.availableAmount = value

          //reset history list
          await this.loadFirstHistoryPage()
        }
      },
    })
 }
</code>```

Body:
I'm not sure why change detection is not running in the case described below. My app is written in Ionic (v6.20.1) with Angular(14+)

I've read this: https://angular.io/guide/zone
, but I still don't see why it's not occuring.

Can someone clarify this please?

app.component.ts:

setupAppStateChange() {
  App.addListener('appStateChange', async ({ isActive }) => {
   if (!isActive) return

   if (this.location.isCurrentPathEqualTo('/wallet')) {
     this.walletService.refreshAmount()
   }
}

Note: change detection works if i do this, but i want to understand why it's needed:

   this.zone.run(async () => {
      this.walletService.refreshAmount()
   })

wallet.service.ts:

private _amount: number
private _amountChanged: Subject<number> = new Subject<number>()

async refreshAmount() {
    const wallet: Wallet = await Parse.Cloud.run('getWallet')
    this._amount = wallet.balance
    this._amountChanged.next(this._amount)
}

wallet.page.ts:

private subscribeAmountChanged() {
    this.availableAmountChanged = this.walletService.amountChanged.subscribe({
      next: async (value) => {
        //hide topup screen
        this.isTopUp = false

        if (this.availableAmount != value) {
          //set new amount
          this.availableAmount = value

          //reset history list
          await this.loadFirstHistoryPage()
        }
      },
    })
 }


问:
Flutter Riverpod 2.0 - how to emit (add) a value to a stream provider manually (through user input)?
i'm learning riverpod but i'm facing alot of problems because the lack of examples.

i have the following:

a class called CounterState1 which contains a stream that emits an integer.

a provider for CounterState1.

a stream provider for CounterState1().Stream.

i want to emit a value to the stream through user intercation e.g. (a button click to emit an integer to the stream).
in plain old streams we used stream controllers with sinks and listeners for user interactions.

i want to achieve the same goal Riverpod streams provider.
i know i can do this task with stateNotifier. but i want it to be done with streams.

i wrote a simple code to demonstrate what supposed to happen:

```<code>class CounterState1{
  int counter;

  CounterState1(this.counter);

  Stream<int> counterStream () async* {
    yield counter;
  }

  // this method here increments a the value that is supposed to emit to stream.
  // this could have been done with `CounterStreamController.sink(++counter);`
  void incStreamVal() => counter++;
}
</code>```
```<code>final counterState1Provider = Provider((ref) => CounterState1(1));

final streamCounterProvider = StreamProvider((ref) {
  var str = ref.read(counterState1Provider).counterStream();
  return str;
});

class IncrementerView2 extends ConsumerWidget {
  const IncrementerView2({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    AsyncValue<int> asyncVal = ref.watch(streamCounterProvider);

    return Scaffold(
      appBar: AppBar(title: const Text("Incrementer")),
      body: Center(
          child: asyncVal.when(
              data: (data) => Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Text(asyncVal.value.toString(),
                          style: const TextStyle(fontSize: 30)),
                      Column(
                        children: [
                          ElevatedButton(
                              onPressed: () {
                                // when clicking here it is supposed to add a value to
                                // the sink of the stream.
                                ref.read(counterState1Provider).incStreamVal();
                              },
                              child: const Text("inc First")),
                        ],
                      ),
                    ],
                  ),
              error: (error, stackTrace) => Text(error.toString()),
              loading: () => const CircularProgressIndicator())),
    );
  }
}

</code>```

Body:
i'm learning riverpod but i'm facing alot of problems because the lack of examples.

i have the following:

a class called CounterState1 which contains a stream that emits an integer.

a provider for CounterState1.

a stream provider for CounterState1().Stream.

i want to emit a value to the stream through user intercation e.g. (a button click to emit an integer to the stream).
in plain old streams we used stream controllers with sinks and listeners for user interactions.

i want to achieve the same goal Riverpod streams provider.
i know i can do this task with stateNotifier. but i want it to be done with streams.

i wrote a simple code to demonstrate what supposed to happen:

class CounterState1{
  int counter;

  CounterState1(this.counter);

  Stream<int> counterStream () async* {
    yield counter;
  }

  // this method here increments a the value that is supposed to emit to stream.
  // this could have been done with `CounterStreamController.sink(++counter);`
  void incStreamVal() => counter++;
}

final counterState1Provider = Provider((ref) => CounterState1(1));

final streamCounterProvider = StreamProvider((ref) {
  var str = ref.read(counterState1Provider).counterStream();
  return str;
});

class IncrementerView2 extends ConsumerWidget {
  const IncrementerView2({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    AsyncValue<int> asyncVal = ref.watch(streamCounterProvider);

    return Scaffold(
      appBar: AppBar(title: const Text("Incrementer")),
      body: Center(
          child: asyncVal.when(
              data: (data) => Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Text(asyncVal.value.toString(),
                          style: const TextStyle(fontSize: 30)),
                      Column(
                        children: [
                          ElevatedButton(
                              onPressed: () {
                                // when clicking here it is supposed to add a value to
                                // the sink of the stream.
                                ref.read(counterState1Provider).incStreamVal();
                              },
                              child: const Text("inc First")),
                        ],
                      ),
                    ],
                  ),
              error: (error, stackTrace) => Text(error.toString()),
              loading: () => const CircularProgressIndicator())),
    );
  }
}


问:
JS scoping error when async loading Chrome local storage
I have a Chrome extension that saves some settings in the local storage.
My script worked fine before I switched the loading function to async as described in Chrome reference.
After switching, my global settings variable became undefined in a button clickHandler.

```<code>var settings = {
  sliderValue: 0,
  modeSelectValue: 0,
  enabled: false
};

async function restoreOptions() {
  settings = await chrome.storage.local.get("settings").then(() => {
    console.log("Loaded: " + JSON.stringify(settings));
  });
}

document.addEventListener("DOMContentLoaded", () => {
  //...

  restoreOptions();

  console.log("Setting Form");
  enabled.checked = Boolean(settings.enabled);
  modeSelect.selectedIndex = settings.modeSelectValue;
  slider.value = settings.sliderValue;

  button.addEventListener("click", (e) => {
    console.log(settings);    // Undefined
  });
});

</code>```

How can I access "settings" in the ClickHandler?

Body:
I have a Chrome extension that saves some settings in the local storage.
My script worked fine before I switched the loading function to async as described in Chrome reference.
After switching, my global settings variable became undefined in a button clickHandler.

var settings = {
  sliderValue: 0,
  modeSelectValue: 0,
  enabled: false
};

async function restoreOptions() {
  settings = await chrome.storage.local.get("settings").then(() => {
    console.log("Loaded: " + JSON.stringify(settings));
  });
}

document.addEventListener("DOMContentLoaded", () => {
  //...

  restoreOptions();

  console.log("Setting Form");
  enabled.checked = Boolean(settings.enabled);
  modeSelect.selectedIndex = settings.modeSelectValue;
  slider.value = settings.sliderValue;

  button.addEventListener("click", (e) => {
    console.log(settings);    // Undefined
  });
});

How can I access "settings" in the ClickHandler?


问:
Npm scripts vs gulp or similar test runners?
What are the advantages and disadvantages of both? I currently have npm scripts for test execution like this in package.json:

```<code>  "scripts": {
    "test": "npx playwright test",
    "lint": "eslint . --ext js,ts",
    etc
    }
</code>```

Having never used gulp or grunt, I would like to know if they do have any massive advantages over just using npm scripts? Thank you

Body:
What are the advantages and disadvantages of both? I currently have npm scripts for test execution like this in package.json:

  "scripts": {
    "test": "npx playwright test",
    "lint": "eslint . --ext js,ts",
    etc
    }

Having never used gulp or grunt, I would like to know if they do have any massive advantages over just using npm scripts? Thank you


问:
Adding and Removing an Object from a List of Objects using HTTP PATCH
I am implementing a PATCH endpoint using ASP.NET Core and EF7 for two models related by a many-to-many relationship and encountered two errors when trying to add or remove an object from a list of objects

I have these Note and Tag model classes:

```<code>public class Note
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    public string? Title { get; set; }
    [Required]
    public string Description { get; set; }
    public List<Tag>? Tags { get; set; }
    public bool Deleted { get; set; }
    public DateTime CreatedDate { get; set; }
    public DateTime ChangedDate { get; set; }
}

public class Tag
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int TagID { get; set; }
    [Required]
    public string TagName { get; set; }
    public List<Note>? Notes { get; set; }
    public DateTime CreatedDate { get; set; }
}
</code>```

They are related by a many-to-many relation using a join table configured with Fluent API. The DbContext is provided below

```<code>public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}

public DbSet<Note> Notes { get; set; }
public DbSet<Tag> Tags { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Note>()
                .HasMany(n => n.Tags)
                .WithMany(t => t.Notes)
                .UsingEntity(j => j
                .ToTable("NoteTag")
                .HasData
                (
                    new {NotesID = 1, TagsTagID = 1},
                    new {NotesID = 2, TagsTagID = 2}
                ));

    modelBuilder.Entity<Tag>().HasData
            (
            new Tag
            {
                TagID= 1,
                TagName="testTag1",
                CreatedDate= DateTime.Now
            },
            new Tag
            {
                TagID= 2,
                TagName = "testTag2",
                CreatedDate= DateTime.Now
            }
            );
    modelBuilder.Entity<Note>().HasData
            (
            new Note
            {
                ID= 1,
                Title="testTitle1",
                Description="testDescription1",
                Deleted=false,
                CreatedDate= DateTime.Now,
                ChangedDate= DateTime.Now,
            },
            new Note
            {
                ID = 2,
                Title = "testTitle2",
                Description = "testDescription2",
                Deleted = false,
                CreatedDate = DateTime.Now,
                ChangedDate = DateTime.Now,
            }
            );
}
</code>```

I have a PATCH endpoint to update Note as below

```<code>[HttpPatch("{id:int}", Name = "UpdateNote")]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult UpdateNote(int id, JsonPatchDocument<Note> patchNoteDTO)
    {
        if (id == 0 || patchNoteDTO == null)
            return BadRequest();
        var note = _db.Notes.Include(x=>x.Tags).AsNoTracking().FirstOrDefault(u => u.ID == id);
        if (note == null)
            return NotFound();
        patchNoteDTO.ApplyTo(note, ModelState);
        if (!ModelState.IsValid)
            return BadRequest(ModelState);
        note.ChangedDate = DateTime.Now;
        _db.Update(note);
        _db.SaveChanges();
        return NoContent();
    }
</code>```

Error 1: When I am trying to add a new Tag to the List of Tags using PATCH (Add Patch Doc), it throws an error (Error Message) as it is trying to enter a duplicate record in NoteTag (Join) table even though I'm adding a Tag of ID 2

Error 2: Not exactly an error. When I try to remove an existing Tag from the List using PATCH (Remove Patch Doc), it runs but the corresponding entry in NoteTag(Join) table is not removed (NoteTag). I'm assuming EF should handle this automatically as I cannot access NoteTag table to do any modifications

Any solutions to fix these two errors to get the desired behavior?

Body:
I am implementing a PATCH endpoint using ASP.NET Core and EF7 for two models related by a many-to-many relationship and encountered two errors when trying to add or remove an object from a list of objects

I have these Note and Tag model classes:

public class Note
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    public string? Title { get; set; }
    [Required]
    public string Description { get; set; }
    public List<Tag>? Tags { get; set; }
    public bool Deleted { get; set; }
    public DateTime CreatedDate { get; set; }
    public DateTime ChangedDate { get; set; }
}

public class Tag
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int TagID { get; set; }
    [Required]
    public string TagName { get; set; }
    public List<Note>? Notes { get; set; }
    public DateTime CreatedDate { get; set; }
}

They are related by a many-to-many relation using a join table configured with Fluent API. The DbContext is provided below

public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}

public DbSet<Note> Notes { get; set; }
public DbSet<Tag> Tags { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Note>()
                .HasMany(n => n.Tags)
                .WithMany(t => t.Notes)
                .UsingEntity(j => j
                .ToTable("NoteTag")
                .HasData
                (
                    new {NotesID = 1, TagsTagID = 1},
                    new {NotesID = 2, TagsTagID = 2}
                ));

    modelBuilder.Entity<Tag>().HasData
            (
            new Tag
            {
                TagID= 1,
                TagName="testTag1",
                CreatedDate= DateTime.Now
            },
            new Tag
            {
                TagID= 2,
                TagName = "testTag2",
                CreatedDate= DateTime.Now
            }
            );
    modelBuilder.Entity<Note>().HasData
            (
            new Note
            {
                ID= 1,
                Title="testTitle1",
                Description="testDescription1",
                Deleted=false,
                CreatedDate= DateTime.Now,
                ChangedDate= DateTime.Now,
            },
            new Note
            {
                ID = 2,
                Title = "testTitle2",
                Description = "testDescription2",
                Deleted = false,
                CreatedDate = DateTime.Now,
                ChangedDate = DateTime.Now,
            }
            );
}

I have a PATCH endpoint to update Note as below

[HttpPatch("{id:int}", Name = "UpdateNote")]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult UpdateNote(int id, JsonPatchDocument<Note> patchNoteDTO)
    {
        if (id == 0 || patchNoteDTO == null)
            return BadRequest();
        var note = _db.Notes.Include(x=>x.Tags).AsNoTracking().FirstOrDefault(u => u.ID == id);
        if (note == null)
            return NotFound();
        patchNoteDTO.ApplyTo(note, ModelState);
        if (!ModelState.IsValid)
            return BadRequest(ModelState);
        note.ChangedDate = DateTime.Now;
        _db.Update(note);
        _db.SaveChanges();
        return NoContent();
    }

Error 1: When I am trying to add a new Tag to the List of Tags using PATCH (Add Patch Doc), it throws an error (Error Message) as it is trying to enter a duplicate record in NoteTag (Join) table even though I'm adding a Tag of ID 2

Error 2: Not exactly an error. When I try to remove an existing Tag from the List using PATCH (Remove Patch Doc), it runs but the corresponding entry in NoteTag(Join) table is not removed (NoteTag). I'm assuming EF should handle this automatically as I cannot access NoteTag table to do any modifications

Any solutions to fix these two errors to get the desired behavior?


问:
Verifying ssl certificate for an https server created with device ip address in java
I created an https server running with device ip addresses and port 8080 in android app with Java.
(Like: 192.168.1.20:8080/something)

Currently I have created sslContext with a self-signed BKS file, of course browsers do not trust this certificate because it is self-signed. I used ZeroSSL to generate an IP address specific ssl certificate but in the "Verify Domain" stage two options are available DNS (CNAME) and Html File Upload. I haven't been able to find and know anything about how I can use these options in my own code.

Are there any other methods besides ZeroSSL? Can you give an idea how I can create a structure?

Also if I successfully verify an SSL certificate for the IP address. What action should I take when the IP address of this android device changes? Because we created the certificate for the state before the IP address changed.

My Create Https Server Code:

```<code>        try {
            InetSocketAddress address = new InetSocketAddress(8080);
            Log.i(HttpServerManager.getHttpServerManager().TAG, "HttpServer starting up: ");

            HttpServerManager.getHttpServerManager().httpServer = HttpsServer.create(address, 0);

            SSLContext sslContext = SSLContext.getInstance("TLS");
            char[] password = "123456".toCharArray();

            // Initialise the keystore
            KeyStore ks = KeyStore.getInstance("BKS");
            ks.load(HoneywellApplication.instance().getApplicationContext()
                    .getResources().openRawResource(R.raw.mynewkey), password);

            // Set up the key manager factory
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(ks, password);

            // Set up the trust manager factory
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            tmf.init(ks);

            // Set up the HTTPS context and parameters
            sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
            HttpServerManager.getHttpServerManager().httpServer.setHttpsConfigurator(new HttpsConfigurator(sslContext) {
                public void configure(HttpsParameters params) {
                    try {

                        // Initialise the SSL context
                        SSLContext c = SSLContext.getDefault();
                        SSLEngine engine = c.createSSLEngine();
                        params.setNeedClientAuth(false);
                        params.setCipherSuites(engine.getEnabledCipherSuites());
                        params.setProtocols(engine.getEnabledProtocols());

                        // Get the default parameters
                        SSLParameters defaultSSLParameters = c.getDefaultSSLParameters();
                        params.setSSLParameters(defaultSSLParameters);
                    } catch (Exception ex) {
                        Log.e(HttpServerManager.getHttpServerManager().TAG, "HttpsServer configure ex: " + ex.getLocalizedMessage());

                    }
                }
            });

            HttpServerManager.getHttpServerManager().httpServer.createContext("/", new RootHandler());

            HttpServerManager.getHttpServerManager().httpServer.setExecutor(null);
            HttpServerManager.getHttpServerManager().httpServer.start();

            Log.i(HttpServerManager.getHttpServerManager().TAG, "HttpServer started");

        } catch (Exception e) {
            e.printStackTrace();
        }
</code>```

Body:
I created an https server running with device ip addresses and port 8080 in android app with Java.
(Like: 192.168.1.20:8080/something)

Currently I have created sslContext with a self-signed BKS file, of course browsers do not trust this certificate because it is self-signed. I used ZeroSSL to generate an IP address specific ssl certificate but in the "Verify Domain" stage two options are available DNS (CNAME) and Html File Upload. I haven't been able to find and know anything about how I can use these options in my own code.

Are there any other methods besides ZeroSSL? Can you give an idea how I can create a structure?

Also if I successfully verify an SSL certificate for the IP address. What action should I take when the IP address of this android device changes? Because we created the certificate for the state before the IP address changed.

My Create Https Server Code:

        try {
            InetSocketAddress address = new InetSocketAddress(8080);
            Log.i(HttpServerManager.getHttpServerManager().TAG, "HttpServer starting up: ");

            HttpServerManager.getHttpServerManager().httpServer = HttpsServer.create(address, 0);

            SSLContext sslContext = SSLContext.getInstance("TLS");
            char[] password = "123456".toCharArray();

            // Initialise the keystore
            KeyStore ks = KeyStore.getInstance("BKS");
            ks.load(HoneywellApplication.instance().getApplicationContext()
                    .getResources().openRawResource(R.raw.mynewkey), password);

            // Set up the key manager factory
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(ks, password);

            // Set up the trust manager factory
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            tmf.init(ks);

            // Set up the HTTPS context and parameters
            sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
            HttpServerManager.getHttpServerManager().httpServer.setHttpsConfigurator(new HttpsConfigurator(sslContext) {
                public void configure(HttpsParameters params) {
                    try {

                        // Initialise the SSL context
                        SSLContext c = SSLContext.getDefault();
                        SSLEngine engine = c.createSSLEngine();
                        params.setNeedClientAuth(false);
                        params.setCipherSuites(engine.getEnabledCipherSuites());
                        params.setProtocols(engine.getEnabledProtocols());

                        // Get the default parameters
                        SSLParameters defaultSSLParameters = c.getDefaultSSLParameters();
                        params.setSSLParameters(defaultSSLParameters);
                    } catch (Exception ex) {
                        Log.e(HttpServerManager.getHttpServerManager().TAG, "HttpsServer configure ex: " + ex.getLocalizedMessage());

                    }
                }
            });

            HttpServerManager.getHttpServerManager().httpServer.createContext("/", new RootHandler());

            HttpServerManager.getHttpServerManager().httpServer.setExecutor(null);
            HttpServerManager.getHttpServerManager().httpServer.start();

            Log.i(HttpServerManager.getHttpServerManager().TAG, "HttpServer started");

        } catch (Exception e) {
            e.printStackTrace();
        }