问:
Heap Sort ,index of array starting 1 instead of 0
```<code>#include<stdio.h>

int swap(int *a,int *b){

int tmp;

 tmp=*a;
*a=*b;
*b=tmp;

}

void heapify(int a[],int n,int i){

int largest =i;
int left=2*i+1;
int right=2*i+2;

while(left<=n&&a[left]>a[largest]){
    largest=left;
 }

while(right<=n&&a[right]>a[largest]){
    largest=right;
 }

if(largest!=i){
swap(&a[largest],&a[i]);
heapify(a,n,largest);
 }

}

int heapSort(int a[],int n){

int i;

for(i=n/2-1;i>=0;i--){
  heapify(a,n,i);
 }

for(i=n;i>=0;i--){
    swap(&a[0],&a[i]);
    heapify(a,n,0);

 }

}

 void printlist(int A[],int len){

int i;

for(i=0;i<len;i++){
    printf(" %d",A[i]);
 }
 printf("\n");
}

int main(){

int a[]={1,5,4,6,3,9,7};
int len=sizeof(a)/sizeof(a[0]);

printf("before :");
printlist(a,len);
heapSort(a,len-1);
printf("after:");
printlist(a,len);

}
</code>```

Since index of array in heapsort starting 1,i have manually changed it to 0 by changing value of i,left,right....

But the problems still occurs

Here is the output:
before : 1 5 4 6 3 9 7
after: 9 7 6 4 5 3 1

There must be some mistakes i didn't noticed,thanks for helping!!

ps:Could anyone suggest a cool link,that cant spot the bug or mistake of code,it will be nice.

答:
The problem is here:

```<code>for(i=n;i>=0;i--){
    swap(&a[0],&a[i]);
    heapify(a,n,0);

}
</code>```

The call to heapify is still using the entire heap. You need to change that to heapify(a, i-1, 0).

Also, in your heapify function, you have:

```<code>while(left<=n&&a[left]>a[largest]){
    largest=left;
 }

while(right<=n&&a[right]>a[largest]){
    largest=right;
 }
</code>```

There's no need for these to be while statements, because the loop body will never execute more than once. For example if in the first one the body is executed, then largest == left, and there's no way that a[left] > a[largest] will evaluate to true the next time around. Those can both be if statements.

Body:
#include<stdio.h>

int swap(int *a,int *b){

int tmp;

 tmp=*a;
*a=*b;
*b=tmp;

}

void heapify(int a[],int n,int i){

int largest =i;
int left=2*i+1;
int right=2*i+2;

while(left<=n&&a[left]>a[largest]){
    largest=left;
 }

while(right<=n&&a[right]>a[largest]){
    largest=right;
 }

if(largest!=i){
swap(&a[largest],&a[i]);
heapify(a,n,largest);
 }

}

int heapSort(int a[],int n){

int i;

for(i=n/2-1;i>=0;i--){
  heapify(a,n,i);
 }

for(i=n;i>=0;i--){
    swap(&a[0],&a[i]);
    heapify(a,n,0);

 }

}

 void printlist(int A[],int len){

int i;

for(i=0;i<len;i++){
    printf(" %d",A[i]);
 }
 printf("\n");
}

int main(){

int a[]={1,5,4,6,3,9,7};
int len=sizeof(a)/sizeof(a[0]);

printf("before :");
printlist(a,len);
heapSort(a,len-1);
printf("after:");
printlist(a,len);

}

Since index of array in heapsort starting 1,i have manually changed it to 0 by changing value of i,left,right....

But the problems still occurs

Here is the output:
before : 1 5 4 6 3 9 7
after: 9 7 6 4 5 3 1

There must be some mistakes i didn't noticed,thanks for helping!!

ps:Could anyone suggest a cool link,that cant spot the bug or mistake of code,it will be nice.

Body:
The problem is here:

for(i=n;i>=0;i--){
    swap(&a[0],&a[i]);
    heapify(a,n,0);

}

The call to heapify is still using the entire heap. You need to change that to heapify(a, i-1, 0).

Also, in your heapify function, you have:

while(left<=n&&a[left]>a[largest]){
    largest=left;
 }

while(right<=n&&a[right]>a[largest]){
    largest=right;
 }

There's no need for these to be while statements, because the loop body will never execute more than once. For example if in the first one the body is executed, then largest == left, and there's no way that a[left] > a[largest] will evaluate to true the next time around. Those can both be if statements.


来源: stackexchange

问:
Supervised classification: plotting K-NN accuracy for different sample sizes and k values
Hope you guys understand that it is hard to replicate something like this on a generic dataset.

Basically what I'm trying to do is perform K-NN with test and train sets of two different sizes for seven different values of k.

My main problem is that res should be a vector storing all the accuracy values for the same train-set size but it shows one value per iteration and this doesn't allow me to plot accuracy graphs as they appear empty.

Do you know how to fix this problem?

Data is available directly on R for free.

```<code>data("Sonar")

#Randomization of the sample
set.seed(123)

random <- sample(rep(1:dim(Sonar)[1]))

Sonar <- Sonar[random,]
head(Sonar)

for (i in c(50,100)){   #train/test set size
  sonar.train <- Sonar[1:i,-61]
  sonar.train.label <- Sonar[1:i,61]
  sonar.test <- Sonar[(1+i) :208,-61]
  sonar.test.label <- Sonar[(1+i) :208 ,61]
  res <- rep(NA,7)
  for (j in c(3,5,7,9,11,13,15)){     #values of k
    mod = knn(train= sonar.train, test = sonar.test, cl = sonar.train.label, k = j) #classification for test set
    err = sum(sonar.test.label==mod) #accuracy
    res[match(j,c(3,5,7,9,11,13,15))] = err/length(mod)  #put accuracy value in vector
    print(res)
    plot(x = c(3,5,7,9,11,13,15) ,y = res, type = "l" ,col = "blue", xlab = "Neighbours", ylab = "Accuracy") #plot the accuracy graphs for each of the two different train/test sets
    res <- rep(NA,7)
  }
  }
#output
>
 0.6835443        NA        NA        NA        NA        NA        NA
        NA 0.6582278        NA        NA        NA        NA        NA
        NA        NA 0.6075949        NA        NA        NA        NA
        NA        NA        NA 0.6265823        NA        NA        NA
        NA        NA        NA        NA 0.5949367        NA        NA
        NA        NA        NA        NA        NA 0.5949367        NA
        NA        NA        NA        NA        NA        NA 0.5506329
 0.6759259        NA        NA        NA        NA        NA        NA
        NA 0.6111111        NA        NA        NA        NA        NA
        NA        NA 0.5648148        NA        NA        NA        NA
        NA        NA        NA 0.5833333        NA        NA        NA
        NA        NA        NA        NA 0.5925926        NA        NA
        NA        NA        NA        NA        NA 0.5740741        NA
        NA        NA        NA        NA        NA        NA 0.5740741
</code>```

The accuracy plot appear empty and with different labels for k on the x axis.

Thank you for reading and helping me!

答:
Your inner loop is supposed to fill the values in res, one per iteration. However, you seem to reset res at the end of each iteration of the loop. That's why it is not keeping any of the previous values.

These two lines need to be outside the inner loop (and inside the outer loop)

```<code>  plot(x = c(3,5,7,9,11,13,15) ,y = res, type = "l" ,col = "blue", xlab = "Neighbours", ylab = "Accuracy") #plot the accuracy graphs for each of the two different train/test sets
  res <- rep(NA,7)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hope you guys understand that it is hard to replicate something like this on a generic dataset.

Basically what I'm trying to do is perform K-NN with test and train sets of two different sizes for seven different values of k.

My main problem is that res should be a vector storing all the accuracy values for the same train-set size but it shows one value per iteration and this doesn't allow me to plot accuracy graphs as they appear empty.

Do you know how to fix this problem?

Data is available directly on R for free.

data("Sonar")

#Randomization of the sample
set.seed(123)

random <- sample(rep(1:dim(Sonar)[1]))

Sonar <- Sonar[random,]
head(Sonar)

for (i in c(50,100)){   #train/test set size
  sonar.train <- Sonar[1:i,-61]
  sonar.train.label <- Sonar[1:i,61]
  sonar.test <- Sonar[(1+i) :208,-61]
  sonar.test.label <- Sonar[(1+i) :208 ,61]
  res <- rep(NA,7)
  for (j in c(3,5,7,9,11,13,15)){     #values of k
    mod = knn(train= sonar.train, test = sonar.test, cl = sonar.train.label, k = j) #classification for test set
    err = sum(sonar.test.label==mod) #accuracy
    res[match(j,c(3,5,7,9,11,13,15))] = err/length(mod)  #put accuracy value in vector
    print(res)
    plot(x = c(3,5,7,9,11,13,15) ,y = res, type = "l" ,col = "blue", xlab = "Neighbours", ylab = "Accuracy") #plot the accuracy graphs for each of the two different train/test sets
    res <- rep(NA,7)
  }
  }
#output
>
 0.6835443        NA        NA        NA        NA        NA        NA
        NA 0.6582278        NA        NA        NA        NA        NA
        NA        NA 0.6075949        NA        NA        NA        NA
        NA        NA        NA 0.6265823        NA        NA        NA
        NA        NA        NA        NA 0.5949367        NA        NA
        NA        NA        NA        NA        NA 0.5949367        NA
        NA        NA        NA        NA        NA        NA 0.5506329
 0.6759259        NA        NA        NA        NA        NA        NA
        NA 0.6111111        NA        NA        NA        NA        NA
        NA        NA 0.5648148        NA        NA        NA        NA
        NA        NA        NA 0.5833333        NA        NA        NA
        NA        NA        NA        NA 0.5925926        NA        NA
        NA        NA        NA        NA        NA 0.5740741        NA
        NA        NA        NA        NA        NA        NA 0.5740741

The accuracy plot appear empty and with different labels for k on the x axis.

Thank you for reading and helping me!

Body:
Your inner loop is supposed to fill the values in res, one per iteration. However, you seem to reset res at the end of each iteration of the loop. That's why it is not keeping any of the previous values.

These two lines need to be outside the inner loop (and inside the outer loop)

  plot(x = c(3,5,7,9,11,13,15) ,y = res, type = "l" ,col = "blue", xlab = "Neighbours", ylab = "Accuracy") #plot the accuracy graphs for each of the two different train/test sets
  res <- rep(NA,7)


问:
AWS Mythical Mysfits - Nomodule named flask - ImportError
I am very new to aws and especially docker
so I have been following this link to understand stuff about developing a web application -
https://aws.amazon.com/getting-started/hands-on/build-modern-app-fargate-lambda-dynamodb-python/module-two/

I am stuck at the point where it asks us to test the service locally using a 'docker run' command(in module - 2)
when I run the command I am getting an 'ImportError'.

Here are my code-snippets ....please help me out !
mythicalMysfitsService.py -

from flask import Flask, jsonify, json, Response, request
from flask_cors import CORS

# A very basic API created using Flask that has two possible routes for requests.

app = application = Flask(__name__)
CORS(application)

# The service basepath has a short response just to ensure that healthchecks
# sent to the service root will receive a healthy response.
@app.route("/")
def healthCheckResponse():
    return jsonify({"message" : "Nothing here, used for health check. Try /mysfits instead."})

# The main API resource that the next version of the Mythical Mysfits website
# will utilize. It returns the data for all of the Mysfits to be displayed on
# the website.  Because we do not yet have any persistent storage available for
# our application, the mysfits are simply stored in a static JSON file. Which is
# read from the the filesystem, and directly used as the service response.
@app.route("/mysfits")
def getMysfits():

    # read the mysfits JSON from the listed file.
    response = Response(open("mysfits-response.json").read())

    # set the Content-Type header so that the browser is aware that the response
    # is formatted as JSON and our frontend JavaScript code is able to
    # appropriately parse the response.
    response.headers["Content-Type"]= "application/json"

    return response

# Run the service on the local server it has been deployed to,
# listening on port 8080.
if __name__ == "__main__":
    application.run(host="0.0.0.0", port=8080)
```

<p>Dockerfile - </p>

```FROM ubuntu:latest
RUN echo Updating existing packages, installing and upgrading python and pip.
RUN apt-get update -y
RUN apt-get install -y python3-pip python-dev build-essential
RUN pip3 install --upgrade pip
RUN echo Copying the Mythical Mysfits Flask service into a service directory.
COPY ./service /MythicalMysfitsService
WORKDIR /MythicalMysfitsService
RUN echo Installing Python packages listed in requirements.txt
RUN pip3 install -r ./requirements.txt
RUN echo Starting python and starting the Flask service...
ENTRYPOINT ["python"]
CMD ["mythicalMysfitsService.py"]
```

<p>docker build - </p>

```ec2-user:~/environment/aws-modern-application-workshop/module-2/app (python) $ docker build . -t 054166015944.dkr.ecr.us-east-2.amazonaws.com/mythicalmysfits/service:latest
```

<p>OUTPUT - </p>

```Sending build context to Docker daemon  14.85kB
Step 1/14 : FROM ubuntu:latest
 ---> 1d622ef86b13
Step 2/14 : RUN echo Updating existing packages, installing and upgrading python and pip.
 ---> Using cache
 ---> 7cdaa818c9c2
Step 3/14 : RUN apt-get update -y
 ---> Using cache
 ---> a1fd46891d1e
Step 4/14 : RUN apt-get install -y python3-pip python-dev build-essential
 ---> Using cache
 ---> f81dc75dfc3f
Step 5/14 : RUN pip3 install --upgrade pip
 ---> Using cache
 ---> 0cee88c88f43
Step 6/14 : RUN echo Copying the Mythical Mysfits Flask service into a service directory.
 ---> Using cache
 ---> 709b50aac794
Step 7/14 : COPY ./service /MythicalMysfitsService
 ---> Using cache
 ---> f70454638e83
Step 8/14 : WORKDIR /MythicalMysfitsService
 ---> Using cache
 ---> 418a08d8ac32
Step 9/14 : RUN echo Installing Python packages listed in requirements.txt
 ---> Using cache
 ---> 03659d0cb00e
Step 10/14 : RUN pip3 install -r ./requirements.txt
 ---> Using cache
 ---> cb65480b6104
Step 11/14 : RUN echo Starting python and starting the Flask service...
 ---> Using cache
 ---> 89738a63f437
Step 12/14 : ENTRYPOINT ["python"]
 ---> Using cache
 ---> 97b4f200a571
Step 13/14 : CMD ["mythicalMysfitsService.py"]
 ---> Using cache
 ---> a22fe5fb5bdb
Step 14/14 : RUN unset -v PYTHONPATH
 ---> Using cache
 ---> f43930d6410a
Successfully built f43930d6410a
Successfully tagged 054166015944.dkr.ecr.us-east-2.amazonaws.com/mythicalmysfits/service:latest
```

<p>docker run to test service locally - </p>

```$ docker run -p 8080:8080 054166015944.dkr.ecr.us-east-2.amazonaws.com/mythicalmysfits/service:latest
```

<p>error - </p>

```Traceback (most recent call last):
  File "mythicalMysfitsService.py", line 1, in <module>
    from flask import Flask, jsonify, json, Response, request
ImportError: No module named flask
```

<p>checked for flask using <code>flask --version</code>
OUTPUT - </p>

```Flask 1.0.4
Werkzeug 1.0.0
```

So I have 'flask' installed but it still says No module named flask.

答:
You may want to try this (It solved the same problem I have):

Update python at 4 places in the Dockerfile

```<code>FROM ubuntu:latest
RUN echo Updating existing packages, installing and upgrading python and pip.
RUN apt-get update -y
RUN apt-get install -y python3-pip python-dev build-essential
RUN pip3 install --upgrade pip
RUN echo Copying the Mythical Mysfits Flask service into a service directory.
COPY ./service /MythicalMysfitsService
WORKDIR /MythicalMysfitsService
RUN echo Installing Python packages listed in requirements.txt
RUN pip3 install -r ./requirements.txt
RUN echo Starting python and starting the Flask service...
ENTRYPOINT ["python3"]
CMD ["mythicalMysfitsService.py"]
</code>```

Body:
I am very new to aws and especially docker
so I have been following this link to understand stuff about developing a web application -
https://aws.amazon.com/getting-started/hands-on/build-modern-app-fargate-lambda-dynamodb-python/module-two/

I am stuck at the point where it asks us to test the service locally using a 'docker run' command(in module - 2)
when I run the command I am getting an 'ImportError'.

Here are my code-snippets ....please help me out !
mythicalMysfitsService.py -

from flask import Flask, jsonify, json, Response, request
from flask_cors import CORS

# A very basic API created using Flask that has two possible routes for requests.

app = application = Flask(__name__)
CORS(application)

# The service basepath has a short response just to ensure that healthchecks
# sent to the service root will receive a healthy response.
@app.route("/")
def healthCheckResponse():
    return jsonify({"message" : "Nothing here, used for health check. Try /mysfits instead."})

# The main API resource that the next version of the Mythical Mysfits website
# will utilize. It returns the data for all of the Mysfits to be displayed on
# the website.  Because we do not yet have any persistent storage available for
# our application, the mysfits are simply stored in a static JSON file. Which is
# read from the the filesystem, and directly used as the service response.
@app.route("/mysfits")
def getMysfits():

    # read the mysfits JSON from the listed file.
    response = Response(open("mysfits-response.json").read())

    # set the Content-Type header so that the browser is aware that the response
    # is formatted as JSON and our frontend JavaScript code is able to
    # appropriately parse the response.
    response.headers["Content-Type"]= "application/json"

    return response

# Run the service on the local server it has been deployed to,
# listening on port 8080.
if __name__ == "__main__":
    application.run(host="0.0.0.0", port=8080)

Dockerfile -

FROM ubuntu:latest
RUN echo Updating existing packages, installing and upgrading python and pip.
RUN apt-get update -y
RUN apt-get install -y python3-pip python-dev build-essential
RUN pip3 install --upgrade pip
RUN echo Copying the Mythical Mysfits Flask service into a service directory.
COPY ./service /MythicalMysfitsService
WORKDIR /MythicalMysfitsService
RUN echo Installing Python packages listed in requirements.txt
RUN pip3 install -r ./requirements.txt
RUN echo Starting python and starting the Flask service...
ENTRYPOINT ["python"]
CMD ["mythicalMysfitsService.py"]

docker build -

ec2-user:~/environment/aws-modern-application-workshop/module-2/app (python) $ docker build . -t 054166015944.dkr.ecr.us-east-2.amazonaws.com/mythicalmysfits/service:latest

OUTPUT -

Sending build context to Docker daemon  14.85kB
Step 1/14 : FROM ubuntu:latest
 ---> 1d622ef86b13
Step 2/14 : RUN echo Updating existing packages, installing and upgrading python and pip.
 ---> Using cache
 ---> 7cdaa818c9c2
Step 3/14 : RUN apt-get update -y
 ---> Using cache
 ---> a1fd46891d1e
Step 4/14 : RUN apt-get install -y python3-pip python-dev build-essential
 ---> Using cache
 ---> f81dc75dfc3f
Step 5/14 : RUN pip3 install --upgrade pip
 ---> Using cache
 ---> 0cee88c88f43
Step 6/14 : RUN echo Copying the Mythical Mysfits Flask service into a service directory.
 ---> Using cache
 ---> 709b50aac794
Step 7/14 : COPY ./service /MythicalMysfitsService
 ---> Using cache
 ---> f70454638e83
Step 8/14 : WORKDIR /MythicalMysfitsService
 ---> Using cache
 ---> 418a08d8ac32
Step 9/14 : RUN echo Installing Python packages listed in requirements.txt
 ---> Using cache
 ---> 03659d0cb00e
Step 10/14 : RUN pip3 install -r ./requirements.txt
 ---> Using cache
 ---> cb65480b6104
Step 11/14 : RUN echo Starting python and starting the Flask service...
 ---> Using cache
 ---> 89738a63f437
Step 12/14 : ENTRYPOINT ["python"]
 ---> Using cache
 ---> 97b4f200a571
Step 13/14 : CMD ["mythicalMysfitsService.py"]
 ---> Using cache
 ---> a22fe5fb5bdb
Step 14/14 : RUN unset -v PYTHONPATH
 ---> Using cache
 ---> f43930d6410a
Successfully built f43930d6410a
Successfully tagged 054166015944.dkr.ecr.us-east-2.amazonaws.com/mythicalmysfits/service:latest

docker run to test service locally -

$ docker run -p 8080:8080 054166015944.dkr.ecr.us-east-2.amazonaws.com/mythicalmysfits/service:latest

error -

Traceback (most recent call last):
  File "mythicalMysfitsService.py", line 1, in <module>
    from flask import Flask, jsonify, json, Response, request
ImportError: No module named flask

checked for flask using flask --version
OUTPUT -

Flask 1.0.4
Werkzeug 1.0.0

So I have 'flask' installed but it still says No module named flask.

Body:
You may want to try this (It solved the same problem I have):

Update python at 4 places in the Dockerfile

FROM ubuntu:latest
RUN echo Updating existing packages, installing and upgrading python and pip.
RUN apt-get update -y
RUN apt-get install -y python3-pip python-dev build-essential
RUN pip3 install --upgrade pip
RUN echo Copying the Mythical Mysfits Flask service into a service directory.
COPY ./service /MythicalMysfitsService
WORKDIR /MythicalMysfitsService
RUN echo Installing Python packages listed in requirements.txt
RUN pip3 install -r ./requirements.txt
RUN echo Starting python and starting the Flask service...
ENTRYPOINT ["python3"]
CMD ["mythicalMysfitsService.py"]


问:
Blazor Cannot read the property parentnode of undefined
In the below code, when I click the button, instead of appearing a hello text, it throws an exception: Cannot read the property parentnode of undefined. I know that I can solve it in many ways but what's the reason of this? why is this occurring?</p>

```<code>@page "/"

@{
    void click()
    {
        <h1>Hello</h1>
    }
}

<button @onclick="click">Click me!</button>
</code>```

答:
Your syntax and the way is incorrect. Try this one.</p>

```<code>@page "/"
<h1>@text</h1>

<button @onclick="@click">Click me</button>

@code
{
     private string text;

     private void click()
     {
          text = "Hello";
     }
}
</code>```

Body:
In the below code, when I click the button, instead of appearing a hello text, it throws an exception: Cannot read the property parentnode of undefined. I know that I can solve it in many ways but what's the reason of this? why is this occurring?

@page "/"

@{
    void click()
    {

Hello

    }
}

<button @onclick="click">Click me!</button>

Body:
Your syntax and the way is incorrect. Try this one.

@page "/"
<h1>@text</h1>

<button @onclick="@click">Click me</button>

@code
{
     private string text;

     private void click()
     {
          text = "Hello";
     }
}


问:
How to order html elements in the same order as array using jQuery?
I'd like to order html elements in the same order as arrayData.

JavaScript

```<code>    var arrayData = [59, 56, 57];
</code>```

HTML

```<code>    <div class="selectize-input">
        <div class="item" data-value="56">Dog</div>
        <div class="item" data-value="57">Rabbit</div>
        <div class="item" data-value="59">Cat</div>
    </div>
</code>```

I want the result like this.

```<code>    <div class="selectize-input">
        <div class="item" data-value="59">Cat</div>
        <div class="item" data-value="56">Dog</div>
        <div class="item" data-value="57">Rabbit</div>
    </div>
</code>```

Is there any good way to achive this?
Thank you in advance.

[Additional]
I want to get result something like this, but don't now how to apply it to html elements and render on browser.

```<code>const orderRule = ['Cat', 'Rabbit', 'Dog', 'Pig', 'Mouse'],
      array = ['Mouse','Rabbit', 'Pig', 'Dog', 'Cat'];

const sortArray = [...array].sort((a, b) => orderRule.indexOf(a) - orderRule.indexOf(b));
console.log(sortArray);
</code>```

答:
If you only have the parent element in html and want to add the child div in sorted order then :

const divList = [
    {value:59, title:"Cat"},
    {value:56, title:"Dog"}
]

```<code>  divList.forEach((obj) => {

    $("<div />")
        .html(obj.title)
        .attr('data-value', obj.value)
        .addClass('item')
        .appendTo( $('.selectize-input'))
</code>```

})

Codepen : https://codepen.io/AdityaDwivedi/pen/pojMYRr

If you already have the div element added in your html & you want to sort them up :

Dog

Rabbit

Cat

`

```<code>const divOrder = ["59", "56", "57"]
    const orderedDiv = $('.selectize-input > div').sort((a, b) =>
    divOrder.indexOf(a.id) - divOrder.indexOf(b.id)
    );

  $('.selectize-input').empty()

orderedDiv.map((obj) =>{
  $("<div />")
            .html(orderedDiv[obj].innerHTML)
            .attr('data-value', orderedDiv[obj].value)
            .appendTo( $('.selectize-input'))})
</code>```

`

Codepen : https://codepen.io/AdityaDwivedi/pen/QWjeopv?editors=1111

Body:
I'd like to order html elements in the same order as arrayData.

JavaScript

    var arrayData = [59, 56, 57];

HTML

Dog

Rabbit

Cat

I want the result like this.

Cat

Dog

Rabbit

Is there any good way to achive this?
Thank you in advance.

[Additional]
I want to get result something like this, but don't now how to apply it to html elements and render on browser.

const orderRule = ['Cat', 'Rabbit', 'Dog', 'Pig', 'Mouse'],
      array = ['Mouse','Rabbit', 'Pig', 'Dog', 'Cat'];

const sortArray = [...array].sort((a, b) => orderRule.indexOf(a) - orderRule.indexOf(b));
console.log(sortArray);

Body:
If you only have the parent element in html and want to add the child div in sorted order then :

const divList = [
    {value:59, title:"Cat"},
    {value:56, title:"Dog"}
]

  divList.forEach((obj) => {

    $("<div />")
        .html(obj.title)
        .attr('data-value', obj.value)
        .addClass('item')
        .appendTo( $('.selectize-input'))

})

Codepen : https://codepen.io/AdityaDwivedi/pen/pojMYRr

If you already have the div element added in your html & you want to sort them up :

<div class="selectize-input">
  <div class="item" data-value="56" id="56">Dog</div>
        <div class="item" data-value="57" id="57">Rabbit</div>
        <div class="item" data-value="59" id="59">Cat</div>
</div>

`

const divOrder = ["59", "56", "57"]
    const orderedDiv = $('.selectize-input > div').sort((a, b) =>
    divOrder.indexOf(a.id) - divOrder.indexOf(b.id)
    );

  $('.selectize-input').empty()

orderedDiv.map((obj) =>{
  $("<div />")
            .html(orderedDiv[obj].innerHTML)
            .attr('data-value', orderedDiv[obj].value)
            .appendTo( $('.selectize-input'))})

`

Codepen : https://codepen.io/AdityaDwivedi/pen/QWjeopv?editors=1111


问:
How to pass 2 javascript events in one click?
I want to pass 2 javascript events in one click, I put 2 of them into href and onclick. But when I click, it always executes the onclick action. Click again or a third time, the href action gets executed. I do not know how it was like this.

How do I to solve it?

If I combine 2 javascript events in one part(href or onclick). is it could run well? how to?

thanks.

```<code><a href="javascript:function1('value1')" onclick="javascript:function2('value2')">
</code>```

答:
you'd better not use dom level0 event.
in jquery you can do:

```<code> $('element').bind('click',function(){
  function1();
  function2(); })
</code>```

not in jquery, you can use
http://dean.edwards.name/my/events.js

ContentLicense: CC BY-SA 3.0

Body:
you'd better not use dom level0 event.
in jquery you can do:

 $('element').bind('click',function(){
  function1();
  function2(); })

not in jquery, you can use
http://dean.edwards.name/my/events.js


问:
Assembly division more decimal numbers remainders than just one
How am I supposed to get more division numbers in Assembly?

I can only print the first decimal number :c

```<code>org 100h ;start

xor edx,edx
mov eax,1
mov ebx,7
div ebx ; 1 / 7
; EAX / EBX = EAX; remainder IN EDX
; EDX VALUE IS ONLY 1 INSTEAD OF 1428571428571429....
; SO instead of printing 0,1428571428571429...x
;(x is how many decimal numbers I want) I can only print out 0,1 :(

mov ax,4c00h;end
int 21h
</code>```

答:
The integer division div looses the fraction from calculating 1/7 because it can only store the integer part of the result in the EAX register.

It is possible to print the result from calculating 1/7 with 9 decimal places and still only use integer operations. Just scale it up a bit and rather calculate 1000000000/7.

```<code>    ORG     256

    mov     eax, 1000000000
    mov     ebx, 7
    xor     edx, edx
    div     ebx          ; -> EAX = 142857142 EDX=6
; Rounding to nearest
    shr     ebx
    cmp     ebx, edx
    adc     eax, 0
; Converting to decimal characters
    mov     ebx, 10
    push    bx           ; Sentinel
  NextDiv:
    xor     edx, edx
    div     ebx
    add     dl, '0'
    push    dx
    test    eax, eax
    jnz     NextDiv
; Printing the result
    mov     ah, 02h      ; DOS.PrintChar
    mov     dl, '0'
    int     21h
    mov     dl, '.'
    int     21h
    pop     dx
  NextChar:
    int     21h
    pop     dx
    cmp     dx, bx
    jne     NextChar
; Giving yourself an opportunity to see the result
    mov     ah, 00h      ; BIOS.GetKey
    int     16h
; Quiting the program
    mov     ax, 4C00h    ; DOS.Terminate
    int     21h
</code>```

The above program will print:

0.142857143

Body:
How am I supposed to get more division numbers in Assembly?

I can only print the first decimal number :c

org 100h ;start

xor edx,edx
mov eax,1
mov ebx,7
div ebx ; 1 / 7
; EAX / EBX = EAX; remainder IN EDX
; EDX VALUE IS ONLY 1 INSTEAD OF 1428571428571429....
; SO instead of printing 0,1428571428571429...x
;(x is how many decimal numbers I want) I can only print out 0,1 :(

mov ax,4c00h;end
int 21h

Body:
The integer division div looses the fraction from calculating 1/7 because it can only store the integer part of the result in the EAX register.

It is possible to print the result from calculating 1/7 with 9 decimal places and still only use integer operations. Just scale it up a bit and rather calculate 1000000000/7.

    ORG     256

    mov     eax, 1000000000
    mov     ebx, 7
    xor     edx, edx
    div     ebx          ; -> EAX = 142857142 EDX=6
; Rounding to nearest
    shr     ebx
    cmp     ebx, edx
    adc     eax, 0
; Converting to decimal characters
    mov     ebx, 10
    push    bx           ; Sentinel
  NextDiv:
    xor     edx, edx
    div     ebx
    add     dl, '0'
    push    dx
    test    eax, eax
    jnz     NextDiv
; Printing the result
    mov     ah, 02h      ; DOS.PrintChar
    mov     dl, '0'
    int     21h
    mov     dl, '.'
    int     21h
    pop     dx
  NextChar:
    int     21h
    pop     dx
    cmp     dx, bx
    jne     NextChar
; Giving yourself an opportunity to see the result
    mov     ah, 00h      ; BIOS.GetKey
    int     16h
; Quiting the program
    mov     ax, 4C00h    ; DOS.Terminate
    int     21h

The above program will print:

0.142857143


问:
Unique index by another column for postgresql
For example, I have this table (postgresql):

CREATE TABLE t(
 a TEXT,
 b TEXT
);
CREATE UNIQUE INDEX t_a_uniq_idx ON t(a);
```

<p>I want to create unique constraint/index for <code>b</code> and <code>a</code> columns. But not simple <code>ADD CONSTRAINT t_ab UNIQUE (a, b)</code>. I want unique <code>b</code> by <code>a</code>:</p>

<pre class="lang-sql prettyprint-override"><code>INSERT INTO t(a,b) VALUES('123', null); -- this is ok
INSERT INTO t(a,b) VALUES('456', '123'); -- this is not ok, because duplicate '123'
</code>```

How can I do this?

Edit:

Why do I need this? For example, If I have users table and I want to create email changing feature, I need structure like this:

CREATE TABLE users(
 email TEXT,
 unconfirmed_email TEXT
 -- some other data
);
CREATE UNIQUE INDEX unq_users_email_idx ON users(email);
```

User can set value into unconfirmed_email column, but only if this value don't used in email column.

答:
While this leads to an interesting problem, I agree that the data could be modelled better - specifically, the column unconfirmed_email can be seen as combining two attributes: an association between an address and a user, which it shares with the email column; and a status of whether that address is confirmed, which is dependant on the combination of user and address, not on one or the other.

This implies that a new table should be extracted of user_email_addresses:

user_id - foreign key to users

email - non-nullable

is_confirmed boolean

Interestingly, as often turns out to be the case, this extracted table has natural data that could be added:

When was the address added?

When was it confirmed?

What is the verification code sent to the user?

If the user is allowed multiple addresses, which is the primary, or which is to be used for a particular purpose?

We can now model various constraints on this table (using unique indexes in some cases because you can't specify Where on a unique constraint):

Each user can only have one association (whether confirmed or not) with a particular e-mail address: Constraint Unique ( user_id, email )

An e-mail address can only be confirmed for one user: Unique Index On user_emails ( email ) Where is_confirmed Is True;

Each user can have only one confirmed address: Unique Index On user_emails ( user_id ) Where is_confirmed Is True;. You might want to adjust this to allow users to confirm multiple addresses, but have a single "primary" address.

Each user can have only one unconfirmed address: Unique Index On user_emails ( user_id ) Where is_confirmed Is False;. This is implied in your current design, but may not actually be necessary.

This leaves us with a re-worded version of your original problem: how do we forbid unconfirmed rows with the same email as a confirmed row, but allow multiple identical unconfirmed rows.

One approach would be to use an Exclude constraint for rows where email matches, but is_confirmed doesn't match. The cast to int is necessary because creating the gist index on boolean fails.

```<code>Alter Table user_emails
Add Constraint unconfirmed_must_not_match_confirmed
Exclude Using gist (
    email With =,
    Cast(is_confirmed as Int) With <>
);
</code>```

On its own, this would allow multiple copies of email, as long as they all had the same value of is_confirmed. But since we've already constrained against multiple rows where is_confirmed Is True, the only duplicates remaining will be where is_confirmed Is False on all matching rows.

Here is a db<>fiddle demonstrating the above design: https://dbfiddle.uk/?rdbms=postgres_12&fiddle=fd8e4e6a4cce79d9bc6bf07111e68df9

Body:
For example, I have this table (postgresql):

CREATE TABLE t(
 a TEXT,
 b TEXT
);
CREATE UNIQUE INDEX t_a_uniq_idx ON t(a);

I want to create unique constraint/index for b and a columns. But not simple ADD CONSTRAINT t_ab UNIQUE (a, b). I want unique b by a:

INSERT INTO t(a,b) VALUES('123', null); -- this is ok
INSERT INTO t(a,b) VALUES('456', '123'); -- this is not ok, because duplicate '123'

How can I do this?

Edit:

Why do I need this? For example, If I have users table and I want to create email changing feature, I need structure like this:

CREATE TABLE users(
 email TEXT,
 unconfirmed_email TEXT
 -- some other data
);
CREATE UNIQUE INDEX unq_users_email_idx ON users(email);

User can set value into unconfirmed_email column, but only if this value don't used in email column.

Body:
While this leads to an interesting problem, I agree that the data could be modelled better - specifically, the column unconfirmed_email can be seen as combining two attributes: an association between an address and a user, which it shares with the email column; and a status of whether that address is confirmed, which is dependant on the combination of user and address, not on one or the other.

This implies that a new table should be extracted of user_email_addresses:

user_id - foreign key to users

email - non-nullable

is_confirmed boolean

Interestingly, as often turns out to be the case, this extracted table has natural data that could be added:

When was the address added?

When was it confirmed?

What is the verification code sent to the user?

If the user is allowed multiple addresses, which is the primary, or which is to be used for a particular purpose?

We can now model various constraints on this table (using unique indexes in some cases because you can't specify Where on a unique constraint):

Each user can only have one association (whether confirmed or not) with a particular e-mail address: Constraint Unique ( user_id, email )

An e-mail address can only be confirmed for one user: Unique Index On user_emails ( email ) Where is_confirmed Is True;

Each user can have only one confirmed address: Unique Index On user_emails ( user_id ) Where is_confirmed Is True;. You might want to adjust this to allow users to confirm multiple addresses, but have a single "primary" address.

Each user can have only one unconfirmed address: Unique Index On user_emails ( user_id ) Where is_confirmed Is False;. This is implied in your current design, but may not actually be necessary.

This leaves us with a re-worded version of your original problem: how do we forbid unconfirmed rows with the same email as a confirmed row, but allow multiple identical unconfirmed rows.

One approach would be to use an Exclude constraint for rows where email matches, but is_confirmed doesn't match. The cast to int is necessary because creating the gist index on boolean fails.

Alter Table user_emails
Add Constraint unconfirmed_must_not_match_confirmed
Exclude Using gist (
    email With =,
    Cast(is_confirmed as Int) With <>
);

On its own, this would allow multiple copies of email, as long as they all had the same value of is_confirmed. But since we've already constrained against multiple rows where is_confirmed Is True, the only duplicates remaining will be where is_confirmed Is False on all matching rows.

Here is a db<>fiddle demonstrating the above design: https://dbfiddle.uk/?rdbms=postgres_12&fiddle=fd8e4e6a4cce79d9bc6bf07111e68df9


问:
Encoding and Decoding in Node js
I have a string, On which I need to encode it into "iso-8859-1" and then I need to convert back it into a readable string.

Is there any way to do this in node js natively? If I am encoding it into "iso-8859-1" then do I need to use the same to decode it back?

I am able to do it in .Net

```<code>string encodedData = "VABpAG0AZQAgAHMAZQByAGUAaQBzAA==";
Encoding encoding = Encoding.GetEncoding("iso-8859-1"); // encoding in "iso-8859-1"
byte[] = decodedbuff = convert.FromBase64String(encodedData);   // getting buffer
result = encoding.GetString(decodedbuff);    //decoding
</code>```

How to achieve it in node js?

答:
You can simply create a buffer from your encoded base64 string and then use toString() with latin1 (iso-8859-1 is latin1 in nodejs)  on the buffer to get the decoded string:

```<code>const encoded = "VABpAG0AZQAgAHMAZQByAGUAaQBzAA==";
const buffer = Buffer.from(encoded, 'base64');
console.log(buffer.toString('latin1')); // prints T i m e   s e r e i s
</code>```

Title: Encoding and Decoding in Node js

Body:
I have a string, On which I need to encode it into "iso-8859-1" and then I need to convert back it into a readable string.

Is there any way to do this in node js natively? If I am encoding it into "iso-8859-1" then do I need to use the same to decode it back?

I am able to do it in .Net

string encodedData = "VABpAG0AZQAgAHMAZQByAGUAaQBzAA==";
Encoding encoding = Encoding.GetEncoding("iso-8859-1"); // encoding in "iso-8859-1"
byte[] = decodedbuff = convert.FromBase64String(encodedData);   // getting buffer
result = encoding.GetString(decodedbuff);    //decoding

How to achieve it in node js?

Body:
You can simply create a buffer from your encoded base64 string and then use toString() with latin1 (iso-8859-1 is latin1 in nodejs)  on the buffer to get the decoded string:

const encoded = "VABpAG0AZQAgAHMAZQByAGUAaQBzAA==";
const buffer = Buffer.from(encoded, 'base64');
console.log(buffer.toString('latin1')); // prints T i m e   s e r e i s


问:
C# Properties.Settings.Default
How to ensure that retrieving value from Properties.Settings.Default exists?
For example, when I use this code:

```<code>folderBrowserDialog1.SelectedPath = (string)Properties.Settings.Default["SelectedPath"];
</code>```

and value SelectedPath does not exist, I get the followng exception:

System.Configuration.SettingsPropertyNotFoundException' occurred in
  System.dll

How can I avoid this exception?

答:
you can set default null value for the variable .
add this code to Settings.Designer.cs file :

```<code>[UserScopedSetting]
[DebuggerNonUserCode]
[DefaultSettingValue(null)] // <-- set default value
public string test1
{
    get
    {
        return (string)this[nameof(test1)];
    }
    set
    {
        this[nameof(test1)] = (object)value;
    }
}
</code>```

then check :

```<code>if (Properties.Settings.Default.test1 != null)
</code>```

Title: C# Properties.Settings.Default

Body:
How to ensure that retrieving value from Properties.Settings.Default exists?
For example, when I use this code:

folderBrowserDialog1.SelectedPath = (string)Properties.Settings.Default["SelectedPath"];

and value SelectedPath does not exist, I get the followng exception:

System.Configuration.SettingsPropertyNotFoundException' occurred in
  System.dll

How can I avoid this exception?

Body:
you can set default null value for the variable .
add this code to Settings.Designer.cs file :

[UserScopedSetting]
[DebuggerNonUserCode]
[DefaultSettingValue(null)] // <-- set default value
public string test1
{
    get
    {
        return (string)this[nameof(test1)];
    }
    set
    {
        this[nameof(test1)] = (object)value;
    }
}

then check :

if (Properties.Settings.Default.test1 != null)


问:
C stack with arrays
I am trying to store arrays in a stack;

```<code>int *orderStack[2];
int orderSize=2;
int orderTop=0;

void pushOrder(int newOrder[2]) {

    if(orderTop>=orderSize) {
        int i;
        int *stack2 = (int*) malloc(sizeof(int)*orderSize*2);
        for(i=0; i<orderSize; i++) {
            stack2[i] = orderStack[i];
        }

        orderStack = stack2;
        orderSize *= 2;
    }

    orderStack[numberTop][0] = newOrder[0];
    orderStack[numberTop++][0] = newOrder[1];

    int temp, i, j, k;

    for (j = 0; j < numberTop; ++j) {
        for (k = j + 1; k < numberTop; ++k) {
            if (orderStack[j][1] > orderStack[k][1]) {
                temp = orderStack[j][1];
                orderStack[j][1] = orderStack[k][1];
                orderStack[k][1] = temp;
            }
       }
   }
}
</code>```

But this it gives this error: [Error] assignment to expression with array type for the line

```<code>orderStack = stack2;
</code>```

I read more then 20 questions about this error, arrays and stacks but I could not find what am I doing wrong.

答:
int *orderStack[2];

In this statement you are declaring orderStack as an array. The compiler allocates 2 slots in this array, each of which can store a pointer to integer. You can assign to these slots:

```<code>orderStack[0] = stack1;
orderStack[1] = stack2;
</code>```

where stack1 and stack2 are of type int *

But you cannot assign orderStack itself - that wouldn't make any sense to the compiler.

If you want to be able to assign orderStack itself then you would declare it as:

```<code>int **orderStack;
</code>```

However, now you will have to first assign it to an array of arrays, and then populate the elements of this array (which would be arrays of int)

Title: C stack with arrays

Body:
I am trying to store arrays in a stack;

int *orderStack[2];
int orderSize=2;
int orderTop=0;

void pushOrder(int newOrder[2]) {

    if(orderTop>=orderSize) {
        int i;
        int *stack2 = (int*) malloc(sizeof(int)*orderSize*2);
        for(i=0; i<orderSize; i++) {
            stack2[i] = orderStack[i];
        }

        orderStack = stack2;
        orderSize *= 2;
    }

    orderStack[numberTop][0] = newOrder[0];
    orderStack[numberTop++][0] = newOrder[1];

    int temp, i, j, k;

    for (j = 0; j < numberTop; ++j) {
        for (k = j + 1; k < numberTop; ++k) {
            if (orderStack[j][1] > orderStack[k][1]) {
                temp = orderStack[j][1];
                orderStack[j][1] = orderStack[k][1];
                orderStack[k][1] = temp;
            }
       }
   }
}

But this it gives this error: [Error] assignment to expression with array type for the line

orderStack = stack2;

I read more then 20 questions about this error, arrays and stacks but I could not find what am I doing wrong.

Body:
int *orderStack[2];

In this statement you are declaring orderStack as an array. The compiler allocates 2 slots in this array, each of which can store a pointer to integer. You can assign to these slots:

orderStack[0] = stack1;
orderStack[1] = stack2;

where stack1 and stack2 are of type int *

But you cannot assign orderStack itself - that wouldn't make any sense to the compiler.

If you want to be able to assign orderStack itself then you would declare it as:

int **orderStack;

However, now you will have to first assign it to an array of arrays, and then populate the elements of this array (which would be arrays of int)


问:
Waiting for data to be retrieved from local storage
When the gallery is loaded in my gallery app, a functioned is called to check whether the current user has liked an image in an array of images. If the user has liked the image, a solid heart icon is displayed on top of the image. If the hasn't liked the image, a heart outline icon is displayed.

Within the function, we get the current users index in an array of users. This information is retrieved from a user object which is stored in the browsers local storage. The problem I am having is that the function is called before the user data is retrieved from the local storage and I'm not sure how to get around this problem?

Here is the relevant html from the gallery-list component:

```<code><div class="gallery-container">
    <div
      class="image-container"
      *ngFor="let image of galleryList">
      <div *ngIf="checkLike(image.imagePath)" class="heart-icon-container">
        <ion-icon name="heart" class="heart-icon" (click)="updateLike(image.imagePath)"></ion-icon>
      </div>
      <div *ngIf="!checkLike(image.imagePath)" class="heart-icon-container">
        <ion-icon name="heart-outline" class="heart-icon" (click)="updateLike(image.imagePath)"></ion-icon>
      </div>
    </div>
</div>
</code>```

Here is the relevant code from the gallery-list ts file:

```<code>  currUsersIndex: number;

ngOnInit() {

    this.currUsersIndex = this.usersService.getCurrUserArrIndex();

}

 checkLike(imageUrl: string): boolean {
    const users = this.usersService.getUsers();

    if(this.isLoggedIn) {
      const FavouritesList = users[this.currUsersIndex].likes;

      if(FavouritesList.includes(imageUrl)) {
          return true;
      } else {
          return false;
      }
  }
    }
</code>```

Finally, this is where the users index is retrieved from the users.service file:

```<code>private users: User[] = [];
 getCurrUserArrIndex() {

        const usersEmail = this.getCurrentUser().email;

        const users = this.getUsers();

        const usersIndex = users.findIndex(user => user.email === usersEmail);

        return usersIndex;

        }

 getCurrentUser() {

    const userData: {

         email: string,
         id: string,
         _token: string,
         _tokenExpirationDate: string

     } = JSON.parse(localStorage.getItem('authUserData'));

 return userData;

 }

    getUsers() {
        return this.users.slice();
    }
</code>```

Please note, the users array is initially set to empty but it is set with the users from a firebase database when the app initializes.

The error message I am receiving in the console is: "can't access property "likes", users[this.currUsersIndex] is undefined"

答:
I think, the issue here is that this.currUsersIndex is not set when you call checkLike() in the HTML.

Alternatively what i could recommend you is that, define a boolean variable in your component as,

```<code>checkLike = false;
</code>```

and then call the function checkLike() after setting currUsersIndex

```<code>ngOnInit() {
    this.currUsersIndex = this.usersService.getCurrUserArrIndex();
    this.checkLike();
}

checkLike(imageUrl: string): boolean {
    const users = this.usersService.getUsers();
    if(this.isLoggedIn) {
      const FavouritesList = users[this.currUsersIndex].likes;
      if(FavouritesList.includes(imageUrl)) {
          this.checkLike = true;
      } else {
          this.checkLike = false;
     }
  }
</code>```

You must be already having the imageUrl in the component.ts just replace with that.

Body:
When the gallery is loaded in my gallery app, a functioned is called to check whether the current user has liked an image in an array of images. If the user has liked the image, a solid heart icon is displayed on top of the image. If the hasn't liked the image, a heart outline icon is displayed.

Within the function, we get the current users index in an array of users. This information is retrieved from a user object which is stored in the browsers local storage. The problem I am having is that the function is called before the user data is retrieved from the local storage and I'm not sure how to get around this problem?

Here is the relevant html from the gallery-list component:

        <ion-icon name="heart" class="heart-icon" (click)="updateLike(image.imagePath)"></ion-icon>

        <ion-icon name="heart-outline" class="heart-icon" (click)="updateLike(image.imagePath)"></ion-icon>

Here is the relevant code from the gallery-list ts file:

  currUsersIndex: number;

ngOnInit() {

    this.currUsersIndex = this.usersService.getCurrUserArrIndex();

}

 checkLike(imageUrl: string): boolean {
    const users = this.usersService.getUsers();

    if(this.isLoggedIn) {
      const FavouritesList = users[this.currUsersIndex].likes;

      if(FavouritesList.includes(imageUrl)) {
          return true;
      } else {
          return false;
      }
  }
    }

Finally, this is where the users index is retrieved from the users.service file:

private users: User[] = [];
 getCurrUserArrIndex() {

        const usersEmail = this.getCurrentUser().email;

        const users = this.getUsers();

        const usersIndex = users.findIndex(user => user.email === usersEmail);

        return usersIndex;

        }

 getCurrentUser() {

    const userData: {

         email: string,
         id: string,
         _token: string,
         _tokenExpirationDate: string

     } = JSON.parse(localStorage.getItem('authUserData'));

 return userData;

 }

    getUsers() {
        return this.users.slice();
    }

Please note, the users array is initially set to empty but it is set with the users from a firebase database when the app initializes.

The error message I am receiving in the console is: "can't access property "likes", users[this.currUsersIndex] is undefined"

Body:
I think, the issue here is that this.currUsersIndex is not set when you call checkLike() in the HTML.

Alternatively what i could recommend you is that, define a boolean variable in your component as,

checkLike = false;

and then call the function checkLike() after setting currUsersIndex

ngOnInit() {
    this.currUsersIndex = this.usersService.getCurrUserArrIndex();
    this.checkLike();
}

checkLike(imageUrl: string): boolean {
    const users = this.usersService.getUsers();
    if(this.isLoggedIn) {
      const FavouritesList = users[this.currUsersIndex].likes;
      if(FavouritesList.includes(imageUrl)) {
          this.checkLike = true;
      } else {
          this.checkLike = false;
     }
  }

You must be already having the imageUrl in the component.ts just replace with that.


答:
The plot function and the re-initilization of res should be outside the inner loop, otherwise you are resetting res to a vector of NAs within each inner cycle.

The new for cycle should be as following

```<code>for (i in c(50,100)){   #train/test set size
  sonar.train <- Sonar[1:i,-61]
  sonar.train.label <- Sonar[1:i,61]
  sonar.test <- Sonar[(1+i) :208,-61]
  sonar.test.label <- Sonar[(1+i) :208 ,61]
  res <- rep(NA,7)
  for (j in c(3,5,7,9,11,13,15)){     #values of k
    mod = knn(train= sonar.train, test = sonar.test, cl = sonar.train.label, k = j) #classification for test set
    err = sum(sonar.test.label==mod) #accuracy
    res[match(j,c(3,5,7,9,11,13,15))] = err/length(mod)  #put accuracy value in vector
  }
  plot(x = c(3,5,7,9,11,13,15) ,y = res, type = "l" ,col = "blue", xlab = "Neighbours", ylab = "Accuracy", main = paste("i =", i)) #plot the accuracy graphs for each of the two different train/test sets
  res <- rep(NA,7)
}
</code>```

By the way, I've added a main = paste("i =", i) in the plotting function in order to recognize which iteration the cycle refers to.

EDIT

I've realized only after I was writing the answer that @Aziz preempted me by a few seconds :D

Title: Supervised classification: plotting K-NN accuracy for different sample sizes and k values

Body:
Hope you guys understand that it is hard to replicate something like this on a generic dataset.

Basically what I'm trying to do is perform K-NN with test and train sets of two different sizes for seven different values of k.

My main problem is that res should be a vector storing all the accuracy values for the same train-set size but it shows one value per iteration and this doesn't allow me to plot accuracy graphs as they appear empty.

Do you know how to fix this problem?

Data is available directly on R for free.

data("Sonar")

#Randomization of the sample
set.seed(123)

random <- sample(rep(1:dim(Sonar)[1]))

Sonar <- Sonar[random,]
head(Sonar)

for (i in c(50,100)){   #train/test set size
  sonar.train <- Sonar[1:i,-61]
  sonar.train.label <- Sonar[1:i,61]
  sonar.test <- Sonar[(1+i) :208,-61]
  sonar.test.label <- Sonar[(1+i) :208 ,61]
  res <- rep(NA,7)
  for (j in c(3,5,7,9,11,13,15)){     #values of k
    mod = knn(train= sonar.train, test = sonar.test, cl = sonar.train.label, k = j) #classification for test set
    err = sum(sonar.test.label==mod) #accuracy
    res[match(j,c(3,5,7,9,11,13,15))] = err/length(mod)  #put accuracy value in vector
    print(res)
    plot(x = c(3,5,7,9,11,13,15) ,y = res, type = "l" ,col = "blue", xlab = "Neighbours", ylab = "Accuracy") #plot the accuracy graphs for each of the two different train/test sets
    res <- rep(NA,7)
  }
  }
#output
>
 0.6835443        NA        NA        NA        NA        NA        NA
        NA 0.6582278        NA        NA        NA        NA        NA
        NA        NA 0.6075949        NA        NA        NA        NA
        NA        NA        NA 0.6265823        NA        NA        NA
        NA        NA        NA        NA 0.5949367        NA        NA
        NA        NA        NA        NA        NA 0.5949367        NA
        NA        NA        NA        NA        NA        NA 0.5506329
 0.6759259        NA        NA        NA        NA        NA        NA
        NA 0.6111111        NA        NA        NA        NA        NA
        NA        NA 0.5648148        NA        NA        NA        NA
        NA        NA        NA 0.5833333        NA        NA        NA
        NA        NA        NA        NA 0.5925926        NA        NA
        NA        NA        NA        NA        NA 0.5740741        NA
        NA        NA        NA        NA        NA        NA 0.5740741

The accuracy plot appear empty and with different labels for k on the x axis.

Thank you for reading and helping me!

Body:
The plot function and the re-initilization of res should be outside the inner loop, otherwise you are resetting res to a vector of NAs within each inner cycle.

The new for cycle should be as following

for (i in c(50,100)){   #train/test set size
  sonar.train <- Sonar[1:i,-61]
  sonar.train.label <- Sonar[1:i,61]
  sonar.test <- Sonar[(1+i) :208,-61]
  sonar.test.label <- Sonar[(1+i) :208 ,61]
  res <- rep(NA,7)
  for (j in c(3,5,7,9,11,13,15)){     #values of k
    mod = knn(train= sonar.train, test = sonar.test, cl = sonar.train.label, k = j) #classification for test set
    err = sum(sonar.test.label==mod) #accuracy
    res[match(j,c(3,5,7,9,11,13,15))] = err/length(mod)  #put accuracy value in vector
  }
  plot(x = c(3,5,7,9,11,13,15) ,y = res, type = "l" ,col = "blue", xlab = "Neighbours", ylab = "Accuracy", main = paste("i =", i)) #plot the accuracy graphs for each of the two different train/test sets
  res <- rep(NA,7)
}

By the way, I've added a main = paste("i =", i) in the plotting function in order to recognize which iteration the cycle refers to.

EDIT

I've realized only after I was writing the answer that @Aziz preempted me by a few seconds :D


问:
netscape.javascript.JSException: SyntaxError: Unexpected keyword 'this'. Expected ')' to end a argument list
I'm trying to insert a String of text into a

 element inside a HTML document inside a WebView.

.java

```<code>webEngine = webView.getEngine();

String headerText = "This is the Header";
webEngine.executeScript("testCheckMate(" + headerText + ");");
</code>```

the HTML

```<code><h3 class="panel-title"></h3>

<script>
    $(document).ready(function() {
        window.testCheckMate = function (data) {
            $( ".panel-title" ).append( data );
        };
    });
</script>
</code>```

I, however, keep getting the error:

```<code>Caused by: netscape.javascript.JSException: SyntaxError: Unexpected keyword 'this'. Expected ')' to end a argument list.
at com.sun.webkit.dom.JSObject.fwkMakeException(JSObject.java:128)
at com.sun.webkit.WebPage.twkExecuteScript(Native Method)
at com.sun.webkit.WebPage.executeScript(WebPage.java:1439)
at javafx.scene.web.WebEngine.executeScript(WebEngine.java:982)
</code>```

What am I doing wrong?

答:
You pass a string which already contains the " character. So from Java side you must quote this with \" . However in JavaScript this String is again parsed and the \" will be the end of string. This is why the end argument list error is thrown.
When passing strings, which are used to invoke functions, you should use on Java side:

```<code>ret = ret.replaceAll("\"","\\\\\"");
</code>```

This solved my problem.

Body:
I'm trying to insert a String of text into a

 element inside a HTML document inside a WebView.

.java

webEngine = webView.getEngine();

String headerText = "This is the Header";
webEngine.executeScript("testCheckMate(" + headerText + ");");

the HTML

I, however, keep getting the error:

Caused by: netscape.javascript.JSException: SyntaxError: Unexpected keyword 'this'. Expected ')' to end a argument list.
at com.sun.webkit.dom.JSObject.fwkMakeException(JSObject.java:128)
at com.sun.webkit.WebPage.twkExecuteScript(Native Method)
at com.sun.webkit.WebPage.executeScript(WebPage.java:1439)
at javafx.scene.web.WebEngine.executeScript(WebEngine.java:982)

What am I doing wrong?

Body:
You pass a string which already contains the " character. So from Java side you must quote this with \" . However in JavaScript this String is again parsed and the \" will be the end of string. This is why the end argument list error is thrown.
When passing strings, which are used to invoke functions, you should use on Java side:

ret = ret.replaceAll("\"","\\\\\"");

This solved my problem.


问:
Set title onSubmit based on current SELECT OPTION VALUE - react
I found this tutorial on how to create a react quizz app on youtube link to tutorial

I am trying to set the title based on the current Select Option Value when submitting the form.
Currently I managed to change the title only when a different option is selected.

```<code>import React, { useState, useEffect, useRef } from "react";
import "./App.css";
import axios from "axios";

import FlashcardList from "./components/FlashcardList";

function App() {
  const [flashcards, setFlashcards] = useState([]);
  const [categories, setCategories] = useState([]);
  const [title, setTitle] = useState("General Knowledge");

  const categoryEl = useRef();
  const amountEl = useRef();

  useEffect(() => {
    axios.get("https://opentdb.com/api_category.php").then((res) => {
      setCategories(res.data.trivia_categories);
    });
  }, []);

  function decodeString(str) {
    const textArea = document.createElement("textarea");
    textArea.innerHTML = str;
    return textArea.value;
  }

  function handleSubmit(e) {
    e.preventDefault();
    axios
      .get("https://opentdb.com/api.php", {
        params: {
          amount: amountEl.current.value,
          category: categoryEl.current.value,
        },
      })
      .then((res) => {
        setFlashcards(
          res.data.results.map((questionItem, index) => {
            const answer = decodeString(questionItem.correct_answer);
            const options = [...questionItem.incorrect_answers, answer];
            return {
              id: `${index} - ${Date.now()}`,
              question: decodeString(questionItem.question),
              answer: answer,
              options: options.sort(() => Math.random() - 0.5),
            };
          })
        );
      });
  }

  function getTitle(e) {
    setTitle(e.target.options[e.target.selectedIndex].text);
  }

  return (
    <>
      <form className="header" onSubmit={handleSubmit}>
        <div className="form-group">
          <label htmlFor="category">Category</label>
          <select id="category" ref={categoryEl} onChange={getTitle}>
            {categories.map((category) => {
              return (
                <option value={category.id} key={category.id}>
                  {category.name}
                </option>
              );
            })}
          </select>
        </div>
        <div className="form-group">
          <label htmlFor="amount">Number Of Questions</label>
          <input
            type="number"
            id="amount"
            min="1"
            step="1"
            defaultValue={10}
            ref={amountEl}
          />
        </div>
        <div className="form-group">
          <button className="btn">Generate</button>
        </div>
      </form>
      <div className="container">
        <h1 className="title">{title}</h1>
        <FlashcardList flashcards={flashcards} />
      </div>
    </>
  );
}

export default App;
</code>```

Code

Live demo

答:
You can set the category as soon the categories are fetched. Can just use the zeroth element to set the title.</p>

```<code>useEffect(() => {  axios.get("https://opentdb.com/api_category.php").then((res) => {
  setCategories(res.data.trivia_categories);
  setTitle(res.data.trivia_categories[0]);
});
}, []);
</code>```

Body:
I found this tutorial on how to create a react quizz app on youtube link to tutorial

I am trying to set the title based on the current Select Option Value when submitting the form.
Currently I managed to change the title only when a different option is selected.

import React, { useState, useEffect, useRef } from "react";
import "./App.css";
import axios from "axios";

import FlashcardList from "./components/FlashcardList";

function App() {
  const [flashcards, setFlashcards] = useState([]);
  const [categories, setCategories] = useState([]);
  const [title, setTitle] = useState("General Knowledge");

  const categoryEl = useRef();
  const amountEl = useRef();

  useEffect(() => {
    axios.get("https://opentdb.com/api_category.php").then((res) => {
      setCategories(res.data.trivia_categories);
    });
  }, []);

  function decodeString(str) {
    const textArea = document.createElement("textarea");
    textArea.innerHTML = str;
    return textArea.value;
  }

  function handleSubmit(e) {
    e.preventDefault();
    axios
      .get("https://opentdb.com/api.php", {
        params: {
          amount: amountEl.current.value,
          category: categoryEl.current.value,
        },
      })
      .then((res) => {
        setFlashcards(
          res.data.results.map((questionItem, index) => {
            const answer = decodeString(questionItem.correct_answer);
            const options = [...questionItem.incorrect_answers, answer];
            return {
              id: `${index} - ${Date.now()}`,
              question: decodeString(questionItem.question),
              answer: answer,
              options: options.sort(() => Math.random() - 0.5),
            };
          })
        );
      });
  }

  function getTitle(e) {
    setTitle(e.target.options[e.target.selectedIndex].text);
  }

  return (
    <>
      <form className="header" onSubmit={handleSubmit}>

          Category
          <select id="category" ref={categoryEl} onChange={getTitle}>
            {categories.map((category) => {
              return (
                <option value={category.id} key={category.id}>
                  {category.name}
                </option>
              );
            })}
          </select>

          Number Of Questions
          <input
            type="number"
            id="amount"
            min="1"
            step="1"
            defaultValue={10}
            ref={amountEl}
          />

          <button className="btn">Generate</button>

      </form>

{title}

        <FlashcardList flashcards={flashcards} />

    </>
  );
}

export default App;

Code

Live demo

Body:
You can set the category as soon the categories are fetched. Can just use the zeroth element to set the title.

useEffect(() => {  axios.get("https://opentdb.com/api_category.php").then((res) => {
  setCategories(res.data.trivia_categories);
  setTitle(res.data.trivia_categories[0]);
});
}, []);


问:
For the series 1, 1, 2, 2, 4, 2, 6, what are the next terms in the sequence? What is the nth term?
i want to know the pattern for the above series in order to write the code for above series.
I am thinking that the above series is mix of two different series 1,2,4,6,...and 1,2,2,..
Please help me with this sequence and also tell whether i am  thinking in correct way or not.</p>

答:
It is series whose greatest common divisior (gcd) is 1 also known as Euler's Totient Function.

series format = {1 1 2 2 4 2 6 32 ..... 168 80 216 120 164 100}

Code:

```<code> public static void main(String[] args) {

//n is the input for the size of the series
        for(int j=1;j<=n;j++){
            System.out.print(calSeriesVal(j)+" ");
        }
}

private static int calDivisor(int a, int b)
{
    if (a == 0)
        return b;
    return calDivisor(b % a, a);
}

private static int calSeriesVal(int n)
{
    int val = 1;
    for (int i = 2; i < n; i++)
        if (calDivisor(i, n) == 1)
            val++;
    return val;
}
</code>```

Body:
It is series whose greatest common divisior (gcd) is 1 also known as Euler's Totient Function.

series format = {1 1 2 2 4 2 6 32 ..... 168 80 216 120 164 100}

Code:

 public static void main(String[] args) {

//n is the input for the size of the series
        for(int j=1;j<=n;j++){
            System.out.print(calSeriesVal(j)+" ");
        }
}

private static int calDivisor(int a, int b)
{
    if (a == 0)
        return b;
    return calDivisor(b % a, a);
}

private static int calSeriesVal(int n)
{
    int val = 1;
    for (int i = 2; i < n; i++)
        if (calDivisor(i, n) == 1)
            val++;
    return val;
}


问:
Saving arrays on Flutter
I have an array that contains widgets List<ListCard> listsList= []; And inside each widget I have an array that has objects of a class called Product List<Product> products = [];. Through the app you can add products to the list but I want to save this 2 arrays (and the inner objects). How can I do it? I thought I can do a database but maybe there is something more straightforward than designing all the schema.

答: You can use this package https://pub.dev/packages/localstorage . It is pretty straighforward</p>

Title: Saving arrays on Flutter


问:
How to get Q Values in RL - DDQN
I'm not sure how to get the Q Values for a DDQN.

DQN is the normal network, TAR the target network.

```<code>    q_values = self.DQN.predict(c_states) # DQN batch predict Q on states
    dqn_next = self.DQN.predict(n_states) # DQN batch predict Q on next_states
    tar_next = self.TAR.predict(n_states) # TAR batch predict Q on next_states
</code>```

I mainly found 2 versions:

Version 1:

```<code>q_values[i][actions[i]] = (rewards[i] + (GAMMA * np.amax(tar_next[i])))
</code>```

Version 2:

```<code>act = np.argmax(dqn_next[i])
q_values[i][actions[i]] = (rewards[i] + (GAMMA * tar_next[i][act]))
</code>```

Which one is correct? And why?

Version 1 Links:

https://github.com/keon/deep-q-learning/blob/master/ddqn.py

https://pythonprogramming.net/training-deep-q-learning-dqn-reinforcement-learning-python-tutorial

Version 2 Links:

https://github.com/germain-hug/Deep-RL-Keras/blob/master/DDQN/ddqn.py

https://github.com/rlcode/reinforcement-learning/blob/master/2-cartpole/2-double-dqn/cartpole_ddqn.py

https://jaromiru.com/2016/11/07/lets-make-a-dqn-double-learning-and-prioritized-experience-replay/

EDIT:
Many thanks, to clarify this

```<code>Q-learning:
q_values[i][actions[i]] = (rewards[i] + (GAMMA * np.amax(tar_next[i])))

SARSA:
act = np.argmax(dqn_next[i])
q_values[i][actions[i]] = (rewards[i] + (GAMMA * tar_next[i][act]))
</code>```

EDIT: re-open 03/2020

I'm sorry but i have to re-open that question. Maybe I misunderstood something, but the following sources show that my Version 2 (SARSA) is Double Q Learning?

Page 158 : Double Q-learning
http://incompleteideas.net/book/RLbook2018.pdf

adventuresinML

adventuresinML source

答:
Thanks to your help and the informations here leosimmons, I found the source of my confusion:

The Bellman equation used here Bellman equation - link 3 follows the equation:

```<code>value = reward + discount_factor * target_network.predict(next_state)[argmax(online_network.predict(next_state))]
</code>```

The Bellman equation in the original (vanilla) DQN Bellman equation - link 2 is:

```<code>value = reward + discount_factor * max(target_network.predict(next_state))
</code>```

leosimmons

The difference is that, using the terminology of the field, the second
  equation uses the target network for both SELECTING and EVALUATING the
  action to take whereas the first equation uses the online network for
  SELECTING the action to take and the target network for EVALUATING the
  action. Selection here means choosing which action to take, and
  evaluation means getting the projected Q value for that action. This
  form of the Bellman equation is what makes this agent a Double DQN and
  not just a DQN and was introduced in 3.

1 https://medium.com/@leosimmons/double-dqn-implementation-to-solve-openai-gyms-cartpole-v-0-df554cd0614d

2 https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf

3 https://arxiv.org/pdf/1509.06461.pdf

Very well explained here:
https://youtu.be/ILDLT97FsNM?t=331

Title: How to get Q Values in RL - DDQN

Body:
I'm not sure how to get the Q Values for a DDQN.

DQN is the normal network, TAR the target network.

    q_values = self.DQN.predict(c_states) # DQN batch predict Q on states
    dqn_next = self.DQN.predict(n_states) # DQN batch predict Q on next_states
    tar_next = self.TAR.predict(n_states) # TAR batch predict Q on next_states

I mainly found 2 versions:

Version 1:

q_values[i][actions[i]] = (rewards[i] + (GAMMA * np.amax(tar_next[i])))

Version 2:

act = np.argmax(dqn_next[i])
q_values[i][actions[i]] = (rewards[i] + (GAMMA * tar_next[i][act]))

Which one is correct? And why?

Version 1 Links:

https://github.com/keon/deep-q-learning/blob/master/ddqn.py

https://pythonprogramming.net/training-deep-q-learning-dqn-reinforcement-learning-python-tutorial

Version 2 Links:

https://github.com/germain-hug/Deep-RL-Keras/blob/master/DDQN/ddqn.py

https://github.com/rlcode/reinforcement-learning/blob/master/2-cartpole/2-double-dqn/cartpole_ddqn.py

https://jaromiru.com/2016/11/07/lets-make-a-dqn-double-learning-and-prioritized-experience-replay/

EDIT:
Many thanks, to clarify this

Q-learning:
q_values[i][actions[i]] = (rewards[i] + (GAMMA * np.amax(tar_next[i])))

SARSA:
act = np.argmax(dqn_next[i])
q_values[i][actions[i]] = (rewards[i] + (GAMMA * tar_next[i][act]))

EDIT: re-open 03/2020

I'm sorry but i have to re-open that question. Maybe I misunderstood something, but the following sources show that my Version 2 (SARSA) is Double Q Learning?

Page 158 : Double Q-learning
http://incompleteideas.net/book/RLbook2018.pdf

adventuresinML

adventuresinML source

Body:
Thanks to your help and the informations here leosimmons, I found the source of my confusion:

The Bellman equation used here Bellman equation - link 3 follows the equation:

value = reward + discount_factor * target_network.predict(next_state)[argmax(online_network.predict(next_state))]

The Bellman equation in the original (vanilla) DQN Bellman equation - link 2 is:

value = reward + discount_factor * max(target_network.predict(next_state))

leosimmons

The difference is that, using the terminology of the field, the second
  equation uses the target network for both SELECTING and EVALUATING the
  action to take whereas the first equation uses the online network for
  SELECTING the action to take and the target network for EVALUATING the
  action. Selection here means choosing which action to take, and
  evaluation means getting the projected Q value for that action. This
  form of the Bellman equation is what makes this agent a Double DQN and
  not just a DQN and was introduced in 3.

1 https://medium.com/@leosimmons/double-dqn-implementation-to-solve-openai-gyms-cartpole-v-0-df554cd0614d

2 https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf

3 https://arxiv.org/pdf/1509.06461.pdf

Very well explained here:
https://youtu.be/ILDLT97FsNM?t=331


问:
SymPy: lambdify with 2-D inputs
I'm computing a square matrix V, each element of which is an integral that I compute with sympy. I compute only one definite integral V_nm, the result of which is a numerical expression with symbolic indices m and n. Say V_nm looks like this:

```<code>>>> V_nm
sin(3*n)*cos(m)
</code>```

Now I wish to make a 2-D numerical (not symbolic!) matrix out of V_nm using m and n as indices of the array. Say for a 2 x 2 matrix, the result for the given V_nm would be:

```<code>[[sin(3)cos(1) sin(3)cos(2)]
 [sin(6)cos(1) sin(6)cos(2)]]
</code>```

i.e., n specifies the column and m specifies the rows. (Note: I start m and n at 1 and not 0, but that's no concern).

How do I achieve this?

I know I can use V_nm.subs([(n, ...), (m, ...)]) in a list comprehension followed by evalf() but that's the long route. I wish to achieve this using lambdify. I know how to use lambdify for 1-D arrays. Can you please tell me how to implement it for 2-D arrays?

答:
There is sympy's FunctionMatrix which is intended for this kind of case. Note that it uses zero-based indexing:

```<code>In [1]: m, n, i, j = symbols('m, n, i, j')

In [2]: V_nm = FunctionMatrix(m, n, Lambda((i, j), 100*(i+1) + (j+1)))

In [3]: V_nm
Out[3]: [100⋅i + j + 101]

In [4]: V_nm.subs({m:2, n:3}).as_explicit()
Out[4]:
⎡101  102  103⎤
⎢             ⎥
⎣201  202  203⎦

In [5]: lambdify((m, n), V_nm)(2, 3)
Out[5]:
array([[101., 102., 103.],
       [201., 202., 203.]])
</code>```

Title: SymPy: lambdify with 2-D inputs

Body:
I'm computing a square matrix V, each element of which is an integral that I compute with sympy. I compute only one definite integral V_nm, the result of which is a numerical expression with symbolic indices m and n. Say V_nm looks like this:

>>> V_nm
sin(3*n)*cos(m)

Now I wish to make a 2-D numerical (not symbolic!) matrix out of V_nm using m and n as indices of the array. Say for a 2 x 2 matrix, the result for the given V_nm would be:

[[sin(3)cos(1) sin(3)cos(2)]
 [sin(6)cos(1) sin(6)cos(2)]]

i.e., n specifies the column and m specifies the rows. (Note: I start m and n at 1 and not 0, but that's no concern).

How do I achieve this?

I know I can use V_nm.subs([(n, ...), (m, ...)]) in a list comprehension followed by evalf() but that's the long route. I wish to achieve this using lambdify. I know how to use lambdify for 1-D arrays. Can you please tell me how to implement it for 2-D arrays?

Body:
There is sympy's FunctionMatrix which is intended for this kind of case. Note that it uses zero-based indexing:

In [1]: m, n, i, j = symbols('m, n, i, j')

In [2]: V_nm = FunctionMatrix(m, n, Lambda((i, j), 100*(i+1) + (j+1)))

In [3]: V_nm
Out[3]: [100⋅i + j + 101]

In [4]: V_nm.subs({m:2, n:3}).as_explicit()
Out[4]:
⎡101  102  103⎤
⎢             ⎥
⎣201  202  203⎦

In [5]: lambdify((m, n), V_nm)(2, 3)
Out[5]:
array([[101., 102., 103.],
       [201., 202., 203.]])


问:
Redistributing files in a folder
I need to do some job with my files and the steps are as follow:

Delete from the selection all folders where there is a mention of test in json.json file

Delete folders without wav files

I have written the below script and don't understand why it doesn't echo for empty directory?

#!/bin/bash

for obj in rom/*; do

        if [ -d "$obj" ]; then

              if
                 grep -w test $obj/*.json; then
                 echo $PWD/$obj
                 rm -rf $PWD/$obj
              fi

              if
                  find $obj -type f -name "*.wav"; then
                  echo "ok"
               else
                  echo "In this dir you haven't .wav files"
#                 rm -rf $PWD/$obj
              fi
        fi

done
```

答:
You can find the answer in man find:

EXIT STATUS

       find exits with status 0 if all files are processed successfully, greater than 0 if errors occur.  This is deliberately a very broad description, but if the return value is non-zero, you should  not
       rely on the correctness of the results of find.

So even if find doesn't find the files you were looking for, it will return true because it processed all files successfully.

You could use command substitution like this:

```<code>if test "$(find $obj -type f -name "*.wav")"; then
</code>```

to check if the directory contains any .wav file.

Suggestion: please consider quoting $obj like this "$obj". You could face problems with directories or files with spaces in their names.

Title: Redistributing files in a folder

Body:
You can find the answer in man find:

EXIT STATUS

       find exits with status 0 if all files are processed successfully, greater than 0 if errors occur.  This is deliberately a very broad description, but if the return value is non-zero, you should  not
       rely on the correctness of the results of find.

So even if find doesn't find the files you were looking for, it will return true because it processed all files successfully.

You could use command substitution like this:

if test "$(find $obj -type f -name "*.wav")"; then

to check if the directory contains any .wav file.

Suggestion: please consider quoting $obj like this "$obj". You could face problems with directories or files with spaces in their names.


问:
Getting images from firebase storage and rendering them with a map function
I current have a folder in my firebase storage that looks like this:
enter image description here

I am trying to map through a cloud firestore collection and rendering a screen with list items that have the corresponding info and the image. My document field include IDs that have 0 and 1 for example so I have an easier method of finding the images that I have on firebase storage folder. This is the code I'm using to render:

```<code>renderAccordion() {
    return this.state.accordionarr.map((item,index) => {
      const url = this.returnurl(this.state.displaydatestringversion, item.id);
      return(
        <View key={index}>
          <Accordion
            onChange={this.onChange}
            activeSections={this.state.activeSections}
          >
            <Accordion.Panel header= {item.name}>
              <List>
              <List.Item>
                <Image
                source = {{ uri: url }}
                style = {styles.sizer}
                ></Image>
              </List.Item>
                <List.Item>{item.protein}</List.Item>
                <List.Item>{item.carbohydrate}</List.Item>
              </List>
            </Accordion.Panel>
          </Accordion>
        </View>
      );
    });
  }
</code>```

In the (item,index) you can assume the fields of item look like this:
enter image description here

Also, if you check the second line there is a method call returnurl. That looks like this:

```<code>returnurl = async(date, id) => {
    var ref = firebase.storage().ref(date+'/'+id+".jpg");
    const url = await ref.getDownloadURL();
    return url;
  }
</code>```

I am currently getting an error message of "of type NSMutableDictionary cannot be converted to a valid URL.
What is wrong with my code? Or is there a more efficient way of mapping through a field and finding/downloading the image url to render the screen?

答:
You can't call an async function in your render methods. If you need async data in rendering, you should start loading that data when the component mounts (or when any input for loading the data is available), and then put the data into the component's state once it's loaded.

See for example:

Firebase storage: download images to and put to img src in React map

Image from Cloud Storage is not redendring in .map list

How to update Firebase data to the React application in realtime

React Native how to read Real Time Database Firebase

Firebase storage: download images to and put to img src in React map

Body:
I current have a folder in my firebase storage that looks like this:
enter image description here

I am trying to map through a cloud firestore collection and rendering a screen with list items that have the corresponding info and the image. My document field include IDs that have 0 and 1 for example so I have an easier method of finding the images that I have on firebase storage folder. This is the code I'm using to render:

renderAccordion() {
    return this.state.accordionarr.map((item,index) => {
      const url = this.returnurl(this.state.displaydatestringversion, item.id);
      return(
        <View key={index}>
          <Accordion
            onChange={this.onChange}
            activeSections={this.state.activeSections}
          >
            <Accordion.Panel header= {item.name}>
              <List>
              <List.Item>
                <Image
                source = {{ uri: url }}
                style = {styles.sizer}
                ></Image>
              </List.Item>
                <List.Item>{item.protein}</List.Item>
                <List.Item>{item.carbohydrate}</List.Item>
              </List>
            </Accordion.Panel>
          </Accordion>
        </View>
      );
    });
  }

In the (item,index) you can assume the fields of item look like this:
enter image description here

Also, if you check the second line there is a method call returnurl. That looks like this:

returnurl = async(date, id) => {
    var ref = firebase.storage().ref(date+'/'+id+".jpg");
    const url = await ref.getDownloadURL();
    return url;
  }

I am currently getting an error message of "of type NSMutableDictionary cannot be converted to a valid URL.
What is wrong with my code? Or is there a more efficient way of mapping through a field and finding/downloading the image url to render the screen?


问:
change page when select option changes
When I change the option, the page doesn't change.

I want to change the page to '(value).html'.

function countryHandler() {
  var x = document.getElementsByID("country").value;
  window.location.href = "";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="country" onclick="countryHandler();">
  <option value="">Country...</option>
  <option value="KR">Korea</option>
  <option value="US">United States of America</option>
</select></code>```

答:
The onchange attribute fires the moment when the value of the element is changed.

function urlHandler(value) {
    window.location.assign(`${value}`);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="url" onchange="urlHandler(this.value)">
    <option disabled selected value>Select Option</option>
    <option value="https://techne.africa">TechNe Africa</option>
    <option value="https://google.com">Google</option>
    <option value="https://facebook.com">Facebook</option>
    <option value="https://twitter.com">Twitter</option>
    <option value="https://instagram.com">Instagram</option>
    <option value="https://youtube.com">YouTube</option>
    <option value="https://linkedin.com">LinkedIn</option>
</select></code>```

Title: change page when select option changes

Body:
When I change the option, the page doesn't change.

I want to change the page to '(value).html'.

function countryHandler() {
  var x = document.getElementsByID("country").value;
  window.location.href = "";
}

<select id="country" onclick="countryHandler();">
  <option value="">Country...</option>
  <option value="KR">Korea</option>
  <option value="US">United States of America</option>
</select>

Body:
The onchange attribute fires the moment when the value of the element is changed.

function urlHandler(value) {
    window.location.assign(`${value}`);
}

<select id="url" onchange="urlHandler(this.value)">
    <option disabled selected value>Select Option</option>
    <option value="https://techne.africa">TechNe Africa</option>
    <option value="https://google.com">Google</option>
    <option value="https://facebook.com">Facebook</option>
    <option value="https://twitter.com">Twitter</option>
    <option value="https://instagram.com">Instagram</option>
    <option value="https://youtube.com">YouTube</option>
    <option value="https://linkedin.com">LinkedIn</option>
</select>


问:
JQ function hover()
I need to make an element selection when the cursor sticks on it for 3 seconds. In the above example, it turns out to select an element, but there are problems with elements that have a common ancestor, the timer is not reset to them, but when the "confirmed" class is present, everything works as planned, you need to make the timer reset.

Text translation...

```<code><style>
  .elem {
    -webkit-transition: background-color .3s ease-out, .2s outline ease-in-out !important;
    -o-transition: background-color .3s ease-out, .2s outline ease-in-out !important;
    transition: background-color .3s ease-out, .2s outline ease-in-out !important;
    background-color: #bcd5eb !important;
    outline: 1px solid #1d66bb !important;
    color: #333 !important;
    cursor: pointer !important;
    z-index: 999999 !important;
  }

  .confirmed {
    background-color: #fc7169 !important;
    outline: 1px solid #dd345f !important;
    color: #333 !important;
    cursor: pointer !important;
    z-index: 999999 !important;
  }
</style>
<ul>
  <li>menu 1</li>
  <li>menu 2</li>
  <li>menu 3</li>
  <li>menu 4</li>
  <li>menu 5</li>
</ul>

<div>
  <span>flow 1</span><br>
  <span>flow 2</span><br>
  <span>flow 3</span><br>
  <span>flow 4</span><br>
  <span>flow 5</span><br>
</div>
<br>
<span>flow 1</span><br>
<span>flow 2</span><br>
<span>flow 3</span><br>
<span>flow 4</span><br>
<span>flow 5</span><br>
<script>
  $('*').hover(
    function(event) {
      event.stopImmediatePropagation();

      event.stopPropagation();

      $('.elem').removeClass('elem');

      $(this).addClass('elem');

      $.data(this, 'timer',
        setTimeout($.proxy(
          function() {
            $('.confirmed').removeClass('confirmed');

            $('.elem').addClass('confirmed')
          }, this
        ), 2500)
      );
    },

    function() {
      clearTimeout($.data(this, 'timer'));

      $('.elem').removeClass('elem')

    }
  );
</script>
</code>```

EXAMPLE
https://jsfiddle.net/module/6k8zqpv4/3/

答:
The fact is that the .hover() function is a wrapper for the .mouseenter () and .mouseleave() functions.
To work correctly, you need to use the functions .mouseover() and .mouseout().</p>

```<code>$( document.body )
    .on( 'mouseover', '*', function( event ) {
        event.stopImmediatePropagation();

        event.stopPropagation();

        $( '.elem' ).removeClass( 'elem' );

        $( this ).addClass( 'elem' );

        $.data( this, 'timer', setTimeout( $.proxy(
            function() {
                 $( '.confirmed' ).removeClass( 'confirmed' );

                 $( '.elem' ).addClass( 'confirmed' )
            }, this
        ), 2500 ) );
   })

   .on( 'mouseout', '*', function( event ) {
       clearTimeout( $.data( this, 'timer' ) );

       $( '.elem' ).removeClass( 'elem' )
   })
</code>```

Title: JQ function hover()

Body:
I need to make an element selection when the cursor sticks on it for 3 seconds. In the above example, it turns out to select an element, but there are problems with elements that have a common ancestor, the timer is not reset to them, but when the "confirmed" class is present, everything works as planned, you need to make the timer reset.

Text translation...

menu 1

menu 2

menu 3

menu 4

menu 5

  flow 1

  flow 2

  flow 3

  flow 4

  flow 5

flow 1

flow 2

flow 3

flow 4

flow 5

EXAMPLE
https://jsfiddle.net/module/6k8zqpv4/3/

Body:
The fact is that the .hover() function is a wrapper for the .mouseenter () and .mouseleave() functions.
To work correctly, you need to use the functions .mouseover() and .mouseout().

$( document.body )
    .on( 'mouseover', '*', function( event ) {
        event.stopImmediatePropagation();

        event.stopPropagation();

        $( '.elem' ).removeClass( 'elem' );

        $( this ).addClass( 'elem' );

        $.data( this, 'timer', setTimeout( $.proxy(
            function() {
                 $( '.confirmed' ).removeClass( 'confirmed' );

                 $( '.elem' ).addClass( 'confirmed' )
            }, this
        ), 2500 ) );
   })

   .on( 'mouseout', '*', function( event ) {
       clearTimeout( $.data( this, 'timer' ) );

       $( '.elem' ).removeClass( 'elem' )
   })


问:
How to get value from nested interface
I have a small problem while trying to dynamically read string from my db using odbc and no ORM.

Maybe it's worth mentioning that with another SQL server driver I receive the data as string and not []uint8 which solving my problem).

I'm using the following code to scan a row into slice array:

```<code>func createEmptyResultSet(numOfCols int) []interface{} {
res := make([]interface{}, numOfCols)
for col := 0; col < numOfCols; col++ {
    var i interface{}
    res[col] = &i
}
return res
</code>```

}
and the actual scan:

```<code>func rowsToStringInterfaceMapSlice(rows *sql.Rows, cols []string) ([]map[string]interface{}, error) {
    var err error
    rowsRes := make([]map[string]interface{}, 0)
    numOfCols := len(cols)
    for rows.Next() {
        row := make(map[string]interface{}, numOfCols)
        values := createEmptyResultSet( numOfCols)
        if rows.Scan(values...); err != nil {
            return nil, err
        }
        rowsRes = append(rowsRes, row)
    }
    return rowsRes, nil
}
</code>```

I'm trying to access the following slice:

using few versions of the following code:

```<code>  for i := range values {
//also tried multiple get value
                t := reflect.TypeOf(values[i])
                if t.Kind() == reflect.Slice {
                    row[cols[i]] = interfaceSliceToString(values[i])
                } else {
                    row[cols[i]] = values[i]
                }
            }
</code>```

but nothing seems to work.
any suggestions?

答:
The values in values have type *interface{}.  The test for a slice will never succeed.

Use the following function to simplify things. This function returns a slice of values and a slice of pointers to the the values.  Use the first slice
for accessing the values and the second slice as the variadic argument to scan.

```<code>func createEmptyResultSet(numOfCols int) (values []interface{}, args []interface{}) {
    values = make([]interface{}, numOfCols)
    args = make([]interface{}, numOfCols)
    for col := 0; col < numOfCols; col++ {
        args[col] = &values[col]
    }
    return
}
</code>```

Use it like this:

```<code>    values, args := createEmptyResultSet( numOfCols)
    if rows.Scan(args...); err != nil {
        return nil, err
    }
</code>```

Now values contains the actual values instead of a pointer to the value.

Use type assertions instead of reflect to find the []byte values.

```<code>for i, v := range values {
   switch v := v.(type) {
   case []byte:
      row[cols[i]] = string(v)
   default:
      row[cols[i]] = v
   }
}
</code>```

Here's complete code for rowsToStringInterfaceMapSlice:

```<code>func rowsToStringInterfaceMapSlice(rows *sql.Rows, cols []string) ([]map[string]interface{}, error) {
    var err error
    rowsRes := make([]map[string]interface{}, 0)
    numOfCols := len(cols)
    for rows.Next() {
        row := make(map[string]interface{}, numOfCols)
        values, args := createEmptyResultSet( numOfCols)
        if rows.Scan(args...); err != nil {
            return nil, err
        }
        for i, v := range values {
           switch v := v.(type) {
           case []byte:
              row[cols[i]] = string(v)
           default:
              row[cols[i]] = v
           }
        }
        rowsRes = append(rowsRes, row)
    }
    return rowsRes, nil
}
</code>```

The values and args slices can be reused from row to row.
Allocate values and args outside the loop to reduce memory pressure.

```<code>func rowsToStringInterfaceMapSlice(rows *sql.Rows, cols []string) ([]map[string]interface{}, error) {
    rowsRes := make([]map[string]interface{}, 0)
    values, args := createEmptyResultSet(len(cols))
    for rows.Next() {
        row := make(map[string]interface{}, len(cols))
        for i := range values {
            values[i] = nil
        }
        if err := rows.Scan(args...); err != nil {
            return nil, err
        }
        for i, v := range values {
            switch v := v.(type) {
            case []byte:
                row[cols[i]] = string(v)
            default:
                row[cols[i]] = v
            }
        }
        rowsRes = append(rowsRes, row)
    }
    return rowsRes, nil
}
</code>```

Title: How to get value from nested interface

Body:
I have a small problem while trying to dynamically read string from my db using odbc and no ORM.

Maybe it's worth mentioning that with another SQL server driver I receive the data as string and not []uint8 which solving my problem).

I'm using the following code to scan a row into slice array:

func createEmptyResultSet(numOfCols int) []interface{} {
res := make([]interface{}, numOfCols)
for col := 0; col < numOfCols; col++ {
    var i interface{}
    res[col] = &i
}
return res

}
and the actual scan:

func rowsToStringInterfaceMapSlice(rows *sql.Rows, cols []string) ([]map[string]interface{}, error) {
    var err error
    rowsRes := make([]map[string]interface{}, 0)
    numOfCols := len(cols)
    for rows.Next() {
        row := make(map[string]interface{}, numOfCols)
        values := createEmptyResultSet( numOfCols)
        if rows.Scan(values...); err != nil {
            return nil, err
        }
        rowsRes = append(rowsRes, row)
    }
    return rowsRes, nil
}

I'm trying to access the following slice:

using few versions of the following code:

  for i := range values {
//also tried multiple get value
                t := reflect.TypeOf(values[i])
                if t.Kind() == reflect.Slice {
                    row[cols[i]] = interfaceSliceToString(values[i])
                } else {
                    row[cols[i]] = values[i]
                }
            }

but nothing seems to work.
any suggestions?

Body:
The values in values have type *interface{}.  The test for a slice will never succeed.

Use the following function to simplify things. This function returns a slice of values and a slice of pointers to the the values.  Use the first slice
for accessing the values and the second slice as the variadic argument to scan.

func createEmptyResultSet(numOfCols int) (values []interface{}, args []interface{}) {
    values = make([]interface{}, numOfCols)
    args = make([]interface{}, numOfCols)
    for col := 0; col < numOfCols; col++ {
        args[col] = &values[col]
    }
    return
}

Use it like this:

    values, args := createEmptyResultSet( numOfCols)
    if rows.Scan(args...); err != nil {
        return nil, err
    }

Now values contains the actual values instead of a pointer to the value.

Use type assertions instead of reflect to find the []byte values.

for i, v := range values {
   switch v := v.(type) {
   case []byte:
      row[cols[i]] = string(v)
   default:
      row[cols[i]] = v
   }
}

Here's complete code for rowsToStringInterfaceMapSlice:

func rowsToStringInterfaceMapSlice(rows *sql.Rows, cols []string) ([]map[string]interface{}, error) {
    var err error
    rowsRes := make([]map[string]interface{}, 0)
    numOfCols := len(cols)
    for rows.Next() {
        row := make(map[string]interface{}, numOfCols)
        values, args := createEmptyResultSet( numOfCols)
        if rows.Scan(args...); err != nil {
            return nil, err
        }
        for i, v := range values {
           switch v := v.(type) {
           case []byte:
              row[cols[i]] = string(v)
           default:
              row[cols[i]] = v
           }
        }
        rowsRes = append(rowsRes, row)
    }
    return rowsRes, nil
}

The values and args slices can be reused from row to row.
Allocate values and args outside the loop to reduce memory pressure.

func rowsToStringInterfaceMapSlice(rows *sql.Rows, cols []string) ([]map[string]interface{}, error) {
    rowsRes := make([]map[string]interface{}, 0)
    values, args := createEmptyResultSet(len(cols))
    for rows.Next() {
        row := make(map[string]interface{}, len(cols))
        for i := range values {
            values[i] = nil
        }
        if err := rows.Scan(args...); err != nil {
            return nil, err
        }
        for i, v := range values {
            switch v := v.(type) {
            case []byte:
                row[cols[i]] = string(v)
            default:
                row[cols[i]] = v
            }
        }
        rowsRes = append(rowsRes, row)
    }
    return rowsRes, nil
}