问:
React: setState - which is more correct?
I have a react class component that has a state object and I want to update the object with setState. I can get the state to update correctly two different ways and would like to know if one is more correct than the other.</p>
```<code>this.state = {
  people: {
    name: "",
    typeofComponent: "class",
  }
};

onChange = e => {

  // option 1
  this.setState((prevState) => ({
    people: {
        ...prevState.people, name: e.target.value
    }
  }));

  // option 2
  this.setState({ people: { name: e.target.value }});
}
</code>```

答:
Your second option would work if the state has only 1 field (name in your case). If you set that way it will overwrite the whole people. That's why we need to use  spread operator inorder to make sure the other states are not lost

let a = {
  people: {
    name: "",
    typeofComponent: "class",
  }
}

let newName = 'newname'

let withSpread= {people:{...a.people,name:newName}}

let withoutSpread = {people:{name:newName}}

console.log(withSpread)
console.log(withoutSpread)```

Body:
I have a react class component that has a state object and I want to update the object with setState. I can get the state to update correctly two different ways and would like to know if one is more correct than the other.

this.state = {
  people: {
    name: "",
    typeofComponent: "class",
  }
};

onChange = e => {

  // option 1
  this.setState((prevState) => ({
    people: {
        ...prevState.people, name: e.target.value
    }
  }));

  // option 2
  this.setState({ people: { name: e.target.value }});
}


来源: stackexchange

问:
Efficient way to get indexes of matched items using Lists
I've two lists A and B. I'd like to find out indexes of elements in A that match elements of listB. Something like this:

```<code>ArrayList listA = new ArrayList();
listA.add(1);listA.add(2);listA.add(3);listA.add(4);
ArrayList listB = new ArrayList();
listB.add(2);listB.add(4);
ArrayList listC = new ArrayList();
for(int i=0; i<listB.size();i++) {
   int element = listB.get(i);
   for(int j=0; j<listA.size(); j++) {
      if(listA.get(j) == element) listC.add(j);
   }
}
</code>```

I guess that's one ugly way to doing it. What is the best way to finding all the indexes of A that match all elements in B? I believe there exists a method called containsAll in collections api - don't think it returns matching indexes.

答:
Simple:

```<code>List<Integer> listA = new ArrayList<Integer>();
listA.add(1);
listA.add(2);
listA.add(3);
listA.add(4);

List<Integer> listB = new ArrayList<Integer>();
listB.add(2);
listB.add(4);

List<Integer> listC = new ArrayList<Integer>();

for ( Integer item : listA ) {
    int index = listB.indexOf( item );
    if ( index >= 0 ) {
        listC.add(index);
    }
}
</code>```

But this only works if there is no repetition, if there are repeated indexes you have to do it the way you did, navigating the full list.

EDIT

I thought you wanted the elements, not indexes, sets are not going to give you indexes, only the elements.

ContentLicense: CC BY-SA 3.0

Body:
I've two lists A and B. I'd like to find out indexes of elements in A that match elements of listB. Something like this:

ArrayList listA = new ArrayList();
listA.add(1);listA.add(2);listA.add(3);listA.add(4);
ArrayList listB = new ArrayList();
listB.add(2);listB.add(4);
ArrayList listC = new ArrayList();
for(int i=0; i<listB.size();i++) {
   int element = listB.get(i);
   for(int j=0; j<listA.size(); j++) {
      if(listA.get(j) == element) listC.add(j);
   }
}

I guess that's one ugly way to doing it. What is the best way to finding all the indexes of A that match all elements in B? I believe there exists a method called containsAll in collections api - don't think it returns matching indexes.

Body:
Simple:

List<Integer> listA = new ArrayList<Integer>();
listA.add(1);
listA.add(2);
listA.add(3);
listA.add(4);

List<Integer> listB = new ArrayList<Integer>();
listB.add(2);
listB.add(4);

List<Integer> listC = new ArrayList<Integer>();

for ( Integer item : listA ) {
    int index = listB.indexOf( item );
    if ( index >= 0 ) {
        listC.add(index);
    }
}

But this only works if there is no repetition, if there are repeated indexes you have to do it the way you did, navigating the full list.

EDIT

I thought you wanted the elements, not indexes, sets are not going to give you indexes, only the elements.


问:
Node Js Class Syntax
Not being able to understand the retrieve the value from a Node JS Class

[Here the [Symbol.iterator '']]alert(Hello, ${this.name}!);
 Is there any other way round??

```<code>class User {
  name = "Anonymous";

  sayHi() {
         [Here the [Symbol.iterator '']]alert(`Hello, ${this.name}!`);
  }
}

new User().sayHi();
</code>```

Im expected to get Hello, John, but i get Hello, '${this.name}'

答:
so this is a constructor class, which means all of the declarations will point to the instance of the class, in addition, i you want to the class to have its own properties  use the static keyword</p>
```<code>class Person {
  static user = "tony";
  static getUser() {
    return this.user;
  }
}

console.log(Person.getUser());
</code>```

ContentLicense: CC BY-SA 4.0

Title: Node Js Class Syntax

Body:
Not being able to understand the retrieve the value from a Node JS Class

[Here the [Symbol.iterator '']]alert(Hello, ${this.name}!);
 Is there any other way round??

class User {
  name = "Anonymous";

  sayHi() {
         [Here the [Symbol.iterator '']]alert(`Hello, ${this.name}!`);
  }
}

new User().sayHi();

Im expected to get Hello, John, but i get Hello, '${this.name}'

Body:
so this is a constructor class, which means all of the declarations will point to the instance of the class, in addition, i you want to the class to have its own properties  use the static keyword

class Person {
  static user = "tony";
  static getUser() {
    return this.user;
  }
}

console.log(Person.getUser());


问:
R+Tidyverse: Tibbles don't appear to store milliseconds
I have a CSV with many values. Among them are times stored like this:

```<code>1:34.434
</code>```

Using readr, I form them into a tibble, and use dplyr to cut out all the unnecessary rows and columns.

```<code>lapData <- read_csv("sampledata/sampledata.csv")
lapData <- dplyr::select(lapData,
                         Driver, Lap, Penalty, 'Lap Time', 'Lap type',
                         'Pressure FR', 'Pressure FL', 'Pressure RR', 'Pressure RL',
                         'Temp FR', 'Temp FL', 'Temp RR', 'Temp RL',
                         'Road Temp')
lapData <- dplyr::filter(lapData, Driver == "[personal info]")
lapData <- dplyr::filter(lapData, is.na(Penalty))
lapData <- dplyr::filter(lapData, Lap > 1)
</code>```

I then use print(ggplot(data = lapData, mapping = aes(Lap, 'Lap Time')) + geom_line()) to print the data, and it looks like this:

If it isn't clear, the vertices of the graph line are rounded to the seconds value instead of using the full milisecond precision, which I would like to have.

If I then print(lapData), I see the following entries under 'Lap Time':

I did some research, and found this, which seems to indicate that the loss of precision in the printout from the tibble is inconsequential, and the full data is still stored in the tibble. However, the plot contradicts this statement.

How do I get the plot to show the full millisecond resolution?

答:
Your time format doesn't agree with the time format that readr expects by default. Specifically, readr interprets 1:34.434 as 1 hour and 34 minutes, rather than as 1 minute and 34.434 seconds.

text <- "id,time
1,1:23.456
2,2:34.567
3,3:45.678
"
cat(text, file = "foo.csv")

library("readr")
tt1 <- read_csv("foo.csv")
tt1
## # A tibble: 3 × 2
##      id time
##   <dbl> <time>
## 1     1 01:23
## 2     2 02:34
## 3     3 03:45

as.double(tt1$time) / 60 # numbers of minutes
## [1]  83 154 225
```
<p>The documentation suggests to use the <code>col_types</code> argument of <code>read_csv</code> to specify the time format. Normally, this <em>would</em> work:</p>
<pre class="lang-r prettyprint-override"><code>col_types <- list(id = col_integer(), time = col_time(format = "%M:%OS"))
</code>```

But it doesn't:

tt2 <- read_csv("foo.csv", col_types = col_types)
## Warning message:
## One or more parsing issues, see `problems()` for details

tt2
## # A tibble: 3 × 2
##      id time
##   <int> <time>
## 1     1    NA
## 2     2    NA
## 3     3    NA
```
<p>The problem is that <code>readr</code>'s parser requires minutes to be padded with zeros:</p>
<pre class="lang-r prettyprint-override"><code>parse_time("01:23.456", format = "%M:%OS")
## 00:01:23.456

parse_time("1:23.456", format = "%M:%OS")
## Warning: 1 parsing failure.
## row col         expected   actual
##   1  -- time like %M:%OS 1:23.456
##
## NA
</code>```

That surprised me, because base R's parser doesn't have that constraint:

strptime("1:23.456", format = "%M:%OS")
## [1] "2022-02-11 00:01:23 EST"
```
<p>A workaround is to read the offending column as a character vector and coerce it to numeric via <code>strptime</code> after:</p>
<pre class="lang-r prettyprint-override"><code>tt3 <- read_csv("foo.csv", col_types = list(id = col_integer(), time = col_character()))
tt3
## # A tibble: 3 × 2
##      id time
##   <int> <chr>
## 1     1 1:23.456
## 2     2 2:34.567
## 3     3 3:45.678

library("dplyr")
tt4 <- tt3 %>% mutate(seconds = with(strptime(time, format = "%M:%OS"), 60 * min + sec))
options(pillar.sigfig = 10L)
tt4
## # A tibble: 3 × 3
##      id time     seconds
##   <int> <chr>      <dbl>
## 1     1 1:23.456  83.456
## 2     2 2:34.567 154.567
## 3     3 3:45.678 225.678
</code>```

You can also do the coercion with lubridate, which has a specialized parser:

library("lubridate")
tt5 <- tt3 %>% mutate(seconds = as.double(as.duration(ms(time))))
identical(tt4, tt5)
## [1] TRUE
```

Body:
I have a CSV with many values. Among them are times stored like this:

1:34.434

Using readr, I form them into a tibble, and use dplyr to cut out all the unnecessary rows and columns.

lapData <- read_csv("sampledata/sampledata.csv")
lapData <- dplyr::select(lapData,
                         Driver, Lap, Penalty, 'Lap Time', 'Lap type',
                         'Pressure FR', 'Pressure FL', 'Pressure RR', 'Pressure RL',
                         'Temp FR', 'Temp FL', 'Temp RR', 'Temp RL',
                         'Road Temp')
lapData <- dplyr::filter(lapData, Driver == "[personal info]")
lapData <- dplyr::filter(lapData, is.na(Penalty))
lapData <- dplyr::filter(lapData, Lap > 1)

I then use print(ggplot(data = lapData, mapping = aes(Lap, 'Lap Time')) + geom_line()) to print the data, and it looks like this:

If it isn't clear, the vertices of the graph line are rounded to the seconds value instead of using the full milisecond precision, which I would like to have.

If I then print(lapData), I see the following entries under 'Lap Time':

I did some research, and found this, which seems to indicate that the loss of precision in the printout from the tibble is inconsequential, and the full data is still stored in the tibble. However, the plot contradicts this statement.

How do I get the plot to show the full millisecond resolution?

Body:
Your time format doesn't agree with the time format that readr expects by default. Specifically, readr interprets 1:34.434 as 1 hour and 34 minutes, rather than as 1 minute and 34.434 seconds.

text <- "id,time
1,1:23.456
2,2:34.567
3,3:45.678
"
cat(text, file = "foo.csv")

library("readr")
tt1 <- read_csv("foo.csv")
tt1
## # A tibble: 3 × 2
##      id time
##   <dbl> <time>
## 1     1 01:23
## 2     2 02:34
## 3     3 03:45

as.double(tt1$time) / 60 # numbers of minutes
## [1]  83 154 225

The documentation suggests to use the col_types argument of read_csv to specify the time format. Normally, this would work:

col_types <- list(id = col_integer(), time = col_time(format = "%M:%OS"))

But it doesn't:

tt2 <- read_csv("foo.csv", col_types = col_types)
## Warning message:
## One or more parsing issues, see `problems()` for details

tt2
## # A tibble: 3 × 2
##      id time
##   <int> <time>
## 1     1    NA
## 2     2    NA
## 3     3    NA

The problem is that readr's parser requires minutes to be padded with zeros:

parse_time("01:23.456", format = "%M:%OS")
## 00:01:23.456

parse_time("1:23.456", format = "%M:%OS")
## Warning: 1 parsing failure.
## row col         expected   actual
##   1  -- time like %M:%OS 1:23.456
##
## NA

That surprised me, because base R's parser doesn't have that constraint:

strptime("1:23.456", format = "%M:%OS")
## [1] "2022-02-11 00:01:23 EST"

A workaround is to read the offending column as a character vector and coerce it to numeric via strptime after:

tt3 <- read_csv("foo.csv", col_types = list(id = col_integer(), time = col_character()))
tt3
## # A tibble: 3 × 2
##      id time
##   <int> <chr>
## 1     1 1:23.456
## 2     2 2:34.567
## 3     3 3:45.678

library("dplyr")
tt4 <- tt3 %>% mutate(seconds = with(strptime(time, format = "%M:%OS"), 60 * min + sec))
options(pillar.sigfig = 10L)
tt4
## # A tibble: 3 × 3
##      id time     seconds
##   <int> <chr>      <dbl>
## 1     1 1:23.456  83.456
## 2     2 2:34.567 154.567
## 3     3 3:45.678 225.678

You can also do the coercion with lubridate, which has a specialized parser:

library("lubridate")
tt5 <- tt3 %>% mutate(seconds = as.double(as.duration(ms(time))))
identical(tt4, tt5)
## [1] TRUE


问:
Why the local variable problem happens in python
I got this error

```<code>increment = lambda x : x + 1

def make_repeater(h, n):
    def f(x):
        value = x
        while n > 0 :
            value = h(value)
            n = n - 1

        return value
    return f

    a = make_repeater(increment,5)
    b = a(1)
</code>```

UnboundLocalError: local variable 'n' referenced before assignment

while when I write like this , it runs well

```<code>increment = lambda x : x + 1

def make_repeater(h, n):
    def f(x):
        i = n
        value = x
        while i > 0 :
            value = h(value)
            i = i - 1

        return value
    return f

    a = make_repeater(increment, 5)
    b = a(1)
</code>```

答:
You can use the nonlocal keyword to refer to a variable in the nearest enclosing scope. The following code, with that change, works.

increment = lambda x : x + 1

def make_repeater(h, n):
    def f(x):
        nonlocal n  # <-- added this
        value = x
        while n > 0 :
            value = h(value)
            n = n - 1

        return value
    return f

a = make_repeater(increment,5)
b = a(1)
```

Body:
I got this error

increment = lambda x : x + 1

def make_repeater(h, n):
    def f(x):
        value = x
        while n > 0 :
            value = h(value)
            n = n - 1

        return value
    return f

    a = make_repeater(increment,5)
    b = a(1)

UnboundLocalError: local variable 'n' referenced before assignment

while when I write like this , it runs well

increment = lambda x : x + 1

def make_repeater(h, n):
    def f(x):
        i = n
        value = x
        while i > 0 :
            value = h(value)
            i = i - 1

        return value
    return f

    a = make_repeater(increment, 5)
    b = a(1)


问:
What may be the issues using HTTP push for mobile devices/apps?
I have to devise a push notification plan for some mobile devices where push is not yet officially supported by C2DM / APNS / BES ,etc. MQTT was also a good option but I could not get an MQTT Client for my required platform. (Blackberry Playbook, ActionScript only)

Going back to basics, I had the options of Long Polling and streaming. Streaming using a high keep-alive value seems good to me, as the development of the mobile app (it is not a browser) and the server code are both in my control. To maintain the connection open, I just need to ping the server occasionally.

What issues I may be facing in this approach ? I understand this would constantly open an HTTP connection from the device to the server. Would the battery life of mobile device drain quickly just by persistently opening a server connection ? ...Afterall the data is not being transferred, just by keeping the connection open...right ?

答:
What platform could you not find an MQTT client for?  http://mqtt.org/software lists clients in just about every language I can think of and more than I'd like to bother using.  The mosquitto C client library is very portable.

For battery life, it really depends what you're doing between the keepalives...


问:
semantics of map on a sequence of objects in jq
Suppose I have a file fruit.json containing the following lines:

```<code>[
  {
    "name": "apple",
    "color": "red",
    "price": 20
  },
  {
    "name": "banana",
    "color": "yellow",
    "price": 15
  },
  {
    "name": "pineapple",
    "color": "orange",
    "price": 53
  }
]
</code>```

If I do jq '. | map(.)' fruit.json then I get the original data. That's expected. The second . refers to an element in the entire array.

However if I do jq '.[] | map(.)' fruit.json then I get this:

```<code>[
  "apple",
  "red",
  20
]
[
  "banana",
  "yellow",
  15
]
[
  "pineapple",
  "orange",
  53
]
</code>```

Can someone please explain what's going on? Specifically,

The [] after . strips away the brackets from the input array. Do
we have a name for the [] operator? The manual seems to treat it as
something very basic without definition.

Do we have a name for the resulting thing by appending [] to .?
Obviously it's not an object. If we do jq '.[]' fruit.json
we can see that it looks very similar to an array.
But apparently it behaves quite differently.

Why is it the case that the map function seems to go two
levels inside instead of one? This is
more obvious if we do jq '.[] | map(. | length)' fruit.json
and see that the . inside the map
function refers to the value part of an (object) element of the input array.

Thank you all in advance!

答:
.[] produces the values of the array or object given to it.

For example,

```<code>[ "a", "b", "c" ] | .[]
</code>```

is equivalent to

```<code>[ "a", "b", "c" ] | .[0], .[1], .[2]
</code>```

and produces three strings: a, b and c.

```<code>map( ... )
</code>```

is equivalent to

```<code>[ .[] | ... ]
</code>```

This means that

```<code>map( . )    ≡    [ .[] | . ]    ≡    [ .[] ]
</code>```

For an array, that means

```<code>map( . )    ≡    [ .[0], .[1], ... ]    ≡    .
</code>```

For an object, that means

```<code>map( . )    ≡    [ .["key1"], .["key2"], ... ]
</code>```

The [] after . strips away the brackets from the input array.

There are no brackets. jq programs don't deal with JSON text, but the data structure it represents.

When given an array or object, .[] produces the values of the elements of that array or object.

Do we have a name for the [] operator?

The docs call it the Array/Object Value Iterator, but it's really just a specific usage of the indexing operator.

The Array/Object Value Iterator is ascribed to .[] in the docs, but that's not accurate. It doesn't have to be . before it, but an expression must precede it. This distinguishes it from array construction operator.

In technical terms,

[] as a circumfix operator ([ EXPR ]) is the array construction operator, and

[] as a postfix operator (EXPR [ EXPR? ]) is the indexing operator, and it's specifically called the the array/object value iterator when there's nothing in the brackets.

Do we have a name for the resulting thing by appending [] to .? Obviously it's not an object. If we do jq '.[]' fruit.json we can see that it looks very similar to an array. But apparently it behaves quite differently.

We call that a stream.

I'm not sure what to call the components of the stream. I usually use "value".

For example,

```<code>"a", "b", "c"       // Produces a stream of three values.
"abc" / "" | .[]    // Same
</code>```

When serialized to a file with one value per line (as you would get using -c), it's called "JSON lines" with a suggested naming convention of .jsonl.

Why is it the case that the map function seems to go two levels inside instead of one? This is more obvious if we do jq '.[] | map(. | length)' fruit.json and see that the . inside the map function refers to the value part of an (object) element of the input array.

No, just one.

In that example,

The .[] iterates over the values of the array.

The map iterates over the values of the objects.

Body:
Suppose I have a file fruit.json containing the following lines:

[
  {
    "name": "apple",
    "color": "red",
    "price": 20
  },
  {
    "name": "banana",
    "color": "yellow",
    "price": 15
  },
  {
    "name": "pineapple",
    "color": "orange",
    "price": 53
  }
]

If I do jq '. | map(.)' fruit.json then I get the original data. That's expected. The second . refers to an element in the entire array.

However if I do jq '.[] | map(.)' fruit.json then I get this:

[
  "apple",
  "red",
  20
]
[
  "banana",
  "yellow",
  15
]
[
  "pineapple",
  "orange",
  53
]

Can someone please explain what's going on? Specifically,

The [] after . strips away the brackets from the input array. Do
we have a name for the [] operator? The manual seems to treat it as
something very basic without definition.

Do we have a name for the resulting thing by appending [] to .?
Obviously it's not an object. If we do jq '.[]' fruit.json
we can see that it looks very similar to an array.
But apparently it behaves quite differently.

Why is it the case that the map function seems to go two
levels inside instead of one? This is
more obvious if we do jq '.[] | map(. | length)' fruit.json
and see that the . inside the map
function refers to the value part of an (object) element of the input array.

Thank you all in advance!

Body:
.[] produces the values of the array or object given to it.

For example,

[ "a", "b", "c" ] | .[]

is equivalent to

[ "a", "b", "c" ] | .[0], .[1], .[2]

and produces three strings: a, b and c.

map( ... )

is equivalent to

[ .[] | ... ]

This means that

map( . )    ≡    [ .[] | . ]    ≡    [ .[] ]

For an array, that means

map( . )    ≡    [ .[0], .[1], ... ]    ≡    .

For an object, that means

map( . )    ≡    [ .["key1"], .["key2"], ... ]

The [] after . strips away the brackets from the input array.

There are no brackets. jq programs don't deal with JSON text, but the data structure it represents.

When given an array or object, .[] produces the values of the elements of that array or object.

Do we have a name for the [] operator?

The docs call it the Array/Object Value Iterator, but it's really just a specific usage of the indexing operator.

The Array/Object Value Iterator is ascribed to .[] in the docs, but that's not accurate. It doesn't have to be . before it, but an expression must precede it. This distinguishes it from array construction operator.

In technical terms,

[] as a circumfix operator ([ EXPR ]) is the array construction operator, and

[] as a postfix operator (EXPR [ EXPR? ]) is the indexing operator, and it's specifically called the the array/object value iterator when there's nothing in the brackets.

Do we have a name for the resulting thing by appending [] to .? Obviously it's not an object. If we do jq '.[]' fruit.json we can see that it looks very similar to an array. But apparently it behaves quite differently.

We call that a stream.

I'm not sure what to call the components of the stream. I usually use "value".

For example,

"a", "b", "c"       // Produces a stream of three values.
"abc" / "" | .[]    // Same

When serialized to a file with one value per line (as you would get using -c), it's called "JSON lines" with a suggested naming convention of .jsonl.

Why is it the case that the map function seems to go two levels inside instead of one? This is more obvious if we do jq '.[] | map(. | length)' fruit.json and see that the . inside the map function refers to the value part of an (object) element of the input array.

No, just one.

In that example,

The .[] iterates over the values of the array.

The map iterates over the values of the objects.


问:
How to save a datafile in python
They let me at school make a program at school to roll a die 100 times, save it to a file and then graph the results. I already made the program but I can't save it, I tried this but I can't see the file, could someone help me please?
This is my code:</p>
```<code>import random
import pickle

def dado(n):
  result = []
  for i in range(0,n):
    result.append(random.randint(1, 6))
  return result
print(dado(100))

#save the list
pickle.dump(dado, open("dado.txt", "wb"))
</code>```

答:
this save program may like this

```<code>import random
import pickle

def dado(n):
    result = []
    for i in range(0,n):
        result.append(random.randint(1, 6))
    return result
    print(dado(100))

#save the list
pickle.dump(dado(100), open("dado.pkl", "wb"))
</code>```

or

```<code>import random
import numpy as np

def dado(n):
    result = []
    for i in range(0,n):
        result.append(random.randint(1, 6))
    return result
    print(dado(100))

#save the list
np.set_printoptions(suppress=True)
np.savetxt("dado.txt", dado(100), fmt='%.1f')
</code>```

Title: How to save a datafile in python

Body:
They let me at school make a program at school to roll a die 100 times, save it to a file and then graph the results. I already made the program but I can't save it, I tried this but I can't see the file, could someone help me please?
This is my code:

import random
import pickle

def dado(n):
  result = []
  for i in range(0,n):
    result.append(random.randint(1, 6))
  return result
print(dado(100))

#save the list
pickle.dump(dado, open("dado.txt", "wb"))

Body:
this save program may like this

import random
import pickle

def dado(n):
    result = []
    for i in range(0,n):
        result.append(random.randint(1, 6))
    return result
    print(dado(100))

#save the list
pickle.dump(dado(100), open("dado.pkl", "wb"))

or

import random
import numpy as np

def dado(n):
    result = []
    for i in range(0,n):
        result.append(random.randint(1, 6))
    return result
    print(dado(100))

#save the list
np.set_printoptions(suppress=True)
np.savetxt("dado.txt", dado(100), fmt='%.1f')


问:
Base64 is too large to open in a browser, any alternatives?
My base64 PDF is too large that when I try and open it in a window, the url isn't pasted. I then substring'd it and the link would paste but of course.. it doesn't open as it hasn't received the whole base64.

Code:

```<code>   $.ajax({
    url: [database-url-here],
    type: 'GET',
    dataType: 'json',
    success: function(data){
      var pdf = (data.pdf).toString();

      window.open(pdf);
    }
  });
</code>```

答:
For too big base64 pdf files I convert it to blob and then create a new URL from that blob.
Blob URL is much smaller then base64 url.

To convert I do something like this:

```<code>var url = 'data:application/pdf;base64,'+ base64string;
var blobUrl;
fetch(URL)
 .then(res => res.blob())
 .then(URL.createObjectURL)
 .then((ret) => {blobUrl=ret; return blobUrl;})
 .then(console.log)
</code>```

One can test at this jsfiddle at example 2.
Or see other alternatives here

Body:
My base64 PDF is too large that when I try and open it in a window, the url isn't pasted. I then substring'd it and the link would paste but of course.. it doesn't open as it hasn't received the whole base64.

Code:

   $.ajax({
    url: [database-url-here],
    type: 'GET',
    dataType: 'json',
    success: function(data){
      var pdf = (data.pdf).toString();

      window.open(pdf);
    }
  });

Body:
For too big base64 pdf files I convert it to blob and then create a new URL from that blob.
Blob URL is much smaller then base64 url.

To convert I do something like this:

var url = 'data:application/pdf;base64,'+ base64string;
var blobUrl;
fetch(URL)
 .then(res => res.blob())
 .then(URL.createObjectURL)
 .then((ret) => {blobUrl=ret; return blobUrl;})
 .then(console.log)

One can test at this jsfiddle at example 2.
Or see other alternatives here


问:
ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean
I have written a spring batch application using Spring boot. When I am trying to run that application using command line and classpath on my local system it is running fine. However, when I tried to run it on linux server it is giving me following exception

```<code>Unable to start web server; nested exception is
org.springframework.context.ApplicationContextException:
Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
</code>```

Below is the way I am running it:

```<code>java -cp jarFileName.jar; lib\* -Dlogging.level.org.springframework=DEBUG -Dspring.profiles.active=dev -Dspring.batch.job.names=abcBatchJob com.aa.bb.StartSpringBatch > somelogs.log
</code>```

答:
To convert an Spring boot wen application to standalone:

Either configure application.properties:

```<code>spring.main.web-application-type=none
</code>```

Or Update application context with NONE web context.

```<code>ApplicationContext ctx = new SpringApplicationBuilder(MigrationRunner.class)
                .web(WebApplicationType.NONE).run(args);
</code>```

Using application context, you can get your beans:

myBean bean = (MyBean) ctx.getBean("myBean", MyBean.class);
bean.call_a_method(..);

Body:
I have written a spring batch application using Spring boot. When I am trying to run that application using command line and classpath on my local system it is running fine. However, when I tried to run it on linux server it is giving me following exception

Unable to start web server; nested exception is
org.springframework.context.ApplicationContextException:
Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.

Below is the way I am running it:

java -cp jarFileName.jar; lib\* -Dlogging.level.org.springframework=DEBUG -Dspring.profiles.active=dev -Dspring.batch.job.names=abcBatchJob com.aa.bb.StartSpringBatch > somelogs.log

Body:
To convert an Spring boot wen application to standalone:

Either configure application.properties:

spring.main.web-application-type=none

Or Update application context with NONE web context.

ApplicationContext ctx = new SpringApplicationBuilder(MigrationRunner.class)
                .web(WebApplicationType.NONE).run(args);

Using application context, you can get your beans:

myBean bean = (MyBean) ctx.getBean("myBean", MyBean.class);
bean.call_a_method(..);


问:
Running links to batch files from another batch file and use the shortcut layout properties
I have a set of 7 batch files I keep running all night at work, monitoring directories and files.  I have shortcuts created and used the Layout tab to arrange and resize them so I can still use my desktop.  I just created an extremely simple batch file I use to start the other 7.  But when I run it all the new windows open on top of each other. I can't figure out how to use the Layouts I have set up for each shortcut so the command shells open in the positions and sizes I need.

"start everything.bat"

```<code>@echo off
start cmd /c call "j:\network drive with spaces\shortcuts\batch file1.bat.lnk"
start cmd /c call "j:\network drive with spaces\shortcuts\batch file2.bat.lnk"
start cmd /c call "j:\network drive with spaces\shortcuts\batch file3.bat.lnk"
start cmd /c call "j:\network drive with spaces\shortcuts\batch file4.bat.lnk"
start cmd /c call "j:\network drive with spaces\shortcuts\batch file5.bat.lnk"
start cmd /c call "j:\network drive with spaces\shortcuts\batch file6.bat.lnk"
start cmd /c call "j:\network drive with spaces\shortcuts\batch file7.bat.lnk"
</code>```

Is it possible to get the new windows how and where I need them, or am I pretty much stuck just running the shortcuts manually?  This is running on Windows Server 2012, and like I said it's at work so I don't have access to install anything, or use any 3rd party apps.

答:
For each of the .lnk files, view the properties and goto the layout tab.

In the "window position" section, remove the tick for "let system position window" and then adjust where each window should be located, apply and exit.

Now, in your batch calling all the batch links, change to this:

```<code>@echo off
for %%i in ("j:\network drive with spaces\shortcuts\*.lnk") do start "" "%%~fi"
</code>```

If however there are more .lnk files and you only want to open some, then do:

```<code>@echo off
set links="batch file1.bat.lnk" "batch file2.bat.lnk" "batch file3.bat.lnk" "batch file4.bat.lnk" "batch file5.bat.lnk" "batch file6.bat.lnk" "batch file7.bat.lnk"
for %%i in (%links%) do start "" "j:\network drive with spaces\shortcuts\%%~i"
</code>```

Body:
I have a set of 7 batch files I keep running all night at work, monitoring directories and files.  I have shortcuts created and used the Layout tab to arrange and resize them so I can still use my desktop.  I just created an extremely simple batch file I use to start the other 7.  But when I run it all the new windows open on top of each other. I can't figure out how to use the Layouts I have set up for each shortcut so the command shells open in the positions and sizes I need.

"start everything.bat"

@echo off
start cmd /c call "j:\network drive with spaces\shortcuts\batch file1.bat.lnk"
start cmd /c call "j:\network drive with spaces\shortcuts\batch file2.bat.lnk"
start cmd /c call "j:\network drive with spaces\shortcuts\batch file3.bat.lnk"
start cmd /c call "j:\network drive with spaces\shortcuts\batch file4.bat.lnk"
start cmd /c call "j:\network drive with spaces\shortcuts\batch file5.bat.lnk"
start cmd /c call "j:\network drive with spaces\shortcuts\batch file6.bat.lnk"
start cmd /c call "j:\network drive with spaces\shortcuts\batch file7.bat.lnk"

Is it possible to get the new windows how and where I need them, or am I pretty much stuck just running the shortcuts manually?  This is running on Windows Server 2012, and like I said it's at work so I don't have access to install anything, or use any 3rd party apps.

Body:
For each of the .lnk files, view the properties and goto the layout tab.

In the "window position" section, remove the tick for "let system position window" and then adjust where each window should be located, apply and exit.

Now, in your batch calling all the batch links, change to this:

@echo off
for %%i in ("j:\network drive with spaces\shortcuts\*.lnk") do start "" "%%~fi"

If however there are more .lnk files and you only want to open some, then do:

@echo off
set links="batch file1.bat.lnk" "batch file2.bat.lnk" "batch file3.bat.lnk" "batch file4.bat.lnk" "batch file5.bat.lnk" "batch file6.bat.lnk" "batch file7.bat.lnk"
for %%i in (%links%) do start "" "j:\network drive with spaces\shortcuts\%%~i"


问:
Im stuck on in-completed code on printing variable and list
This is the code I'm stuck on. For example, if I input in Horror, Action then the output would be

```<code>Anabelle=["Horror", "Triller"]
Avengers=["Action", "Fantasy", "Sci-fi"]
Scooby_doo=["Comedy", "Horror"]
Brooklyn_99=["Action", "Comedy"]
Fast_Furious=["Action"]
Conjuring=["Horror"]
Spider_Man=["Action", "Fantasy"]
</code>```

basically, printing the variable and the list that contains the user input. also if possible, I need to use lists, also don't change the code too much and add comments for each section

```<code>my_list= ["Horror, Action, Comedy, Thriller, Mystery, Fantasy, Sci-fi, Romance,
Drama, Dystopian"]

print("All Available Genres " + str(my_list))

Anabelle=["Horror", "Triller"]
Criminal_Minds=["Mystery", "Drama"]
Avengers=["Action", "Fantasy", "Sci-fi"]
Scooby_doo=["Comedy", "Horror"]
Brooklyn_99=["Action", "Comedy" ]
The_fault_in_our_stars=["Romance", "Drama"]
The_tomorrow_war=["Drama", "Sci-Fi"]
Maze_Runner=["Drama", "Dystopian", "Thriller"]
Hunger_Game=["Dystopian", "Sci-Fi", "Thriller"]
Harry_Potter=["Mystery", "Fantasy"]
Fast_Furious=["Action"]
Conjuring=["Horror"]
Fantastic_Beast=["Fantasy"]
Parasite=["Comedy", "Thriller"]
Space_between_us=["Romance"]
Murder_Mystery=["Romance", "Mystery"]
The_Purge=["Dystopian", "Thriller"]
Spider_Man=["Action", "Fantasy"]

variable_strings=['Anabelle', 'Criminal_Minds', 'Avengers', 'Scooby_doo', 'Brooklyn_99', 'The_fault_in_our_stars', 'The_tomorrow_war', 'Maze_Runner', 'Hunger_Game', 'Harry_Potter', 'Fast_Furious', 'Conjuring', 'Fantastic_Beast', 'Parasite', 'Space_between_us', 'Murder_Mystery', 'The_Purge', 'Spider_Man']
newlist = [Anabelle, Criminal_Minds, Avengers, Scooby_doo, Brooklyn_99, The_fault_in_our_stars, The_tomorrow_war, Maze_Runner, Hunger_Game, Harry_Potter, Fast_Furious, Conjuring, Fantastic_Beast, Parasite, Space_between_us, Murder_Mystery, The_Purge, Spider_Man]

user_genre = (input("What movie/show genre do you like to watch?: "))
user_genre = user_genre.split(", ") if ", " in user_genre else user_genre.split(",")
</code>```

答:
I'm not 100% sure if this is what you are asking for but here is some code that

-iterates through movies

-checks if genre is in each movie''

if it is, prints movie name.

Simply add this to the end of your code

```<code>#Splitting user request
user_genre_s = user_genre.split(", ") if ", " in user_genre else user_genre.split(",")
movies_found = 0
print(f"The following movies were found for genres {user_genre}:")
for movie in newlist:
    #testing if value was found in each movie's list
    for genre in user_genre_s:
        if genre in movie:
           print(variable_strings[newlist.index(movie)].replace("_"," "))#printing movie name if found, replacing underscores with spaces to make it look nicer
            movies_found += 1
if movies_found == 0:
    print(":( no match was found")#Telling user if none are found.
</code>```

However you may want to lower() all of the genres as users may not enter capitals

Body:
This is the code I'm stuck on. For example, if I input in Horror, Action then the output would be

Anabelle=["Horror", "Triller"]
Avengers=["Action", "Fantasy", "Sci-fi"]
Scooby_doo=["Comedy", "Horror"]
Brooklyn_99=["Action", "Comedy"]
Fast_Furious=["Action"]
Conjuring=["Horror"]
Spider_Man=["Action", "Fantasy"]

basically, printing the variable and the list that contains the user input. also if possible, I need to use lists, also don't change the code too much and add comments for each section

my_list= ["Horror, Action, Comedy, Thriller, Mystery, Fantasy, Sci-fi, Romance,
Drama, Dystopian"]

print("All Available Genres " + str(my_list))

Anabelle=["Horror", "Triller"]
Criminal_Minds=["Mystery", "Drama"]
Avengers=["Action", "Fantasy", "Sci-fi"]
Scooby_doo=["Comedy", "Horror"]
Brooklyn_99=["Action", "Comedy" ]
The_fault_in_our_stars=["Romance", "Drama"]
The_tomorrow_war=["Drama", "Sci-Fi"]
Maze_Runner=["Drama", "Dystopian", "Thriller"]
Hunger_Game=["Dystopian", "Sci-Fi", "Thriller"]
Harry_Potter=["Mystery", "Fantasy"]
Fast_Furious=["Action"]
Conjuring=["Horror"]
Fantastic_Beast=["Fantasy"]
Parasite=["Comedy", "Thriller"]
Space_between_us=["Romance"]
Murder_Mystery=["Romance", "Mystery"]
The_Purge=["Dystopian", "Thriller"]
Spider_Man=["Action", "Fantasy"]

variable_strings=['Anabelle', 'Criminal_Minds', 'Avengers', 'Scooby_doo', 'Brooklyn_99', 'The_fault_in_our_stars', 'The_tomorrow_war', 'Maze_Runner', 'Hunger_Game', 'Harry_Potter', 'Fast_Furious', 'Conjuring', 'Fantastic_Beast', 'Parasite', 'Space_between_us', 'Murder_Mystery', 'The_Purge', 'Spider_Man']
newlist = [Anabelle, Criminal_Minds, Avengers, Scooby_doo, Brooklyn_99, The_fault_in_our_stars, The_tomorrow_war, Maze_Runner, Hunger_Game, Harry_Potter, Fast_Furious, Conjuring, Fantastic_Beast, Parasite, Space_between_us, Murder_Mystery, The_Purge, Spider_Man]

user_genre = (input("What movie/show genre do you like to watch?: "))
user_genre = user_genre.split(", ") if ", " in user_genre else user_genre.split(",")

Body:
I'm not 100% sure if this is what you are asking for but here is some code that

-iterates through movies

-checks if genre is in each movie''

if it is, prints movie name.

Simply add this to the end of your code

#Splitting user request
user_genre_s = user_genre.split(", ") if ", " in user_genre else user_genre.split(",")
movies_found = 0
print(f"The following movies were found for genres {user_genre}:")
for movie in newlist:
    #testing if value was found in each movie's list
    for genre in user_genre_s:
        if genre in movie:
           print(variable_strings[newlist.index(movie)].replace("_"," "))#printing movie name if found, replacing underscores with spaces to make it look nicer
            movies_found += 1
if movies_found == 0:
    print(":( no match was found")#Telling user if none are found.

However you may want to lower() all of the genres as users may not enter capitals


问:
Append new JavaDoc to existing ones from the super method
I have generated an Interface which is very well documented. Every method does have his own JavaDoc. The clases which implement this Interface can have little differents in their logic.

How can i add JavaDoc to the existing JavaDoc from the super class. The key word

```<code>/**
 * {@inheritDoc}
 */
</code>```

only set the javaDoc of the super class to the current method. But when i try to add some words, the JavaDoc of the super method is gone, like

```<code>/**
 * {@inheritDoc}
 * These value depends on...
 */
</code>```

Does anybody have a idea how i can update the JavaDoc of a super method, without deleting.

EDIT:

Regarding to Brian Agnew answer, which is good but not a real answer ;)

You also can have the same problem when you want to overwrite an existing method, like paint() in Swing, and want to describ how to initialize or handle the draw behaviour from outside.
This is not only for interface description.

答: I don't know any direct JavaDoc idiom that does that. However Eclipse and IntelliJ will let you grab the super JDoc and insert it... it's far from perfect, as if you change the supr JDoc you will have to reedit all the overrides, but it's better than copy-paste by hand...</p>

OwnerDisplayName: Markus Lausberg

Body:
I have generated an Interface which is very well documented. Every method does have his own JavaDoc. The clases which implement this Interface can have little differents in their logic.

How can i add JavaDoc to the existing JavaDoc from the super class. The key word

/**
 * {@inheritDoc}
 */

only set the javaDoc of the super class to the current method. But when i try to add some words, the JavaDoc of the super method is gone, like

/**
 * {@inheritDoc}
 * These value depends on...
 */

Does anybody have a idea how i can update the JavaDoc of a super method, without deleting.

EDIT:

Regarding to Brian Agnew answer, which is good but not a real answer ;)

You also can have the same problem when you want to overwrite an existing method, like paint() in Swing, and want to describ how to initialize or handle the draw behaviour from outside.
This is not only for interface description.

LastEditorDisplayName: Markus Lausberg

OwnerDisplayName: Varkhan

ContentLicense: CC BY-SA 2.5


问:
Proper use of new/delete
As a sequel of my previous question, I would like to ask what I am doing wrong in the following code.

The code is, for example

```<code>void myclass1::myfun()
{
myclass2* newVar = new myclass2();
/* other code and stuff */
myvector.push_back(newVar); // myvector is a member of myclass1 and is a std::vector<myclass2*>
delete newVar;
}
</code>```

but when I run it, myvector returns empty, unless I comment out the delete line.

What am I doing wrong?

答:
You created an instance of myclass2 on the heap and then put a pointer to it into a vector. When you do delete newVar; you are destroying the instance that you just created. But your vector still has a pointer to where the object was and that pointer isn't valid any more.

You should only be calling delete when you don't need the object on the heap any more.

Your options are as follows:

Don't delete the object. This means that you'll have to delete it at some other point in your program, when everything has finished using it. That might be difficult to co-ordinate and so you'd need to use a smart pointer. You can find shared_ptr in either the Boost library or the standard library if you're compiling for c++0x. Here's how you'd use it in c++0x:

```<code>#include <vector>
#include <memory>
#include <algorithm>
#include <iostream>

int main(int argc, const char* argv[]) {
  typedef std::vector<std::shared_ptr<int>> Vector;

  Vector v = {
    Vector::value_type(new int(2)),
    Vector::value_type(new int(5))
  };

  std::for_each(v.begin(), v.end(), [](Vector::value_type x) {
    std::cout << *x << std::endl;
  });

  return 0;
}
</code>```

Don't allocate the object on the heap. Instead, just fill the vector with instances of myclass instead of pointers to myclass. Now your vector will be a std::vector<myclass2>.

The 2nd option is preferable if you have the choice. Your instances of myclass2 will be destroyed whenever the vector is destroyed which alleviates the hassle of keeping track of them.

Title: Proper use of new/delete

Body:
As a sequel of my previous question, I would like to ask what I am doing wrong in the following code.

The code is, for example

void myclass1::myfun()
{
myclass2* newVar = new myclass2();
/* other code and stuff */
myvector.push_back(newVar); // myvector is a member of myclass1 and is a std::vector<myclass2*>
delete newVar;
}

but when I run it, myvector returns empty, unless I comment out the delete line.

What am I doing wrong?

Body:
You created an instance of myclass2 on the heap and then put a pointer to it into a vector. When you do delete newVar; you are destroying the instance that you just created. But your vector still has a pointer to where the object was and that pointer isn't valid any more.

You should only be calling delete when you don't need the object on the heap any more.

Your options are as follows:

Don't delete the object. This means that you'll have to delete it at some other point in your program, when everything has finished using it. That might be difficult to co-ordinate and so you'd need to use a smart pointer. You can find shared_ptr in either the Boost library or the standard library if you're compiling for c++0x. Here's how you'd use it in c++0x:

#include <vector>
#include <memory>
#include <algorithm>
#include <iostream>

int main(int argc, const char* argv[]) {
  typedef std::vector<std::shared_ptr<int>> Vector;

  Vector v = {
    Vector::value_type(new int(2)),
    Vector::value_type(new int(5))
  };

  std::for_each(v.begin(), v.end(), [](Vector::value_type x) {
    std::cout << *x << std::endl;
  });

  return 0;
}

Don't allocate the object on the heap. Instead, just fill the vector with instances of myclass instead of pointers to myclass. Now your vector will be a std::vector<myclass2>.

The 2nd option is preferable if you have the choice. Your instances of myclass2 will be destroyed whenever the vector is destroyed which alleviates the hassle of keeping track of them.


问:
i'm making a carousel of images and i've the error : The left-hand side of an assignment expression may not be an optional property access
I am making an Image Carousel in Angular that receives a model to iterate the images, but when I try to take the first position it throws me an error.

The left-hand side of an assignment expression may not be an optional property access.ts(2779)

The error is here

```<code>export class CarouselComponent implements OnInit {
@Input() height = 500;
@Input() isFullScreen = false;
@Input() items: ICarouselItem[] = [];

public finalHeight: string | number = 0;
public currentPosition = 0;

constructor() {
 this.finalHeight = this.isFullScreen ? '100vh' : `${this.height}px`;
}

ngOnInit(): void {
this.items.map((i, index) =>{
  i.id = index;
  i.marginLeft = 0;
});
}

setCurrentPosition(position: number){
debugger
this.currentPosition = position;
this.items.find(i => i.id === 0)?.marginLeft = -100 * position;

}

setNext(){
debugger
let finalPercentage = 0;
let nextPosition = this.currentPosition + 1;
if(nextPosition <= this.items.length - 1){
  finalPercentage = -100 * nextPosition;
}else{
  nextPosition = 0;
}
this.items.find(i => i.id === 0)?.marginLeft = finalPercentage;
this.currentPosition = nextPosition;
}

setBack(){
let finalPercentage = 0;
let backPosition = this.currentPosition -1;
if(backPosition >= 0){
  finalPercentage = -100 * backPosition;
}else{
  backPosition = this.items.length - 1;
  finalPercentage = -100 * backPosition;
}
this.items.find(i => i.id === 0)?.marginLeft = finalPercentage;
this.currentPosition = backPosition;
}
}
</code>```

答:
I think this error is display because you are using find function and directly assign value to this object
Like

```<code>this.items.find(i => i.id === 0)?.marginLeft = -100 * position
</code>```

Suppose you didn't find the object then it will return null then How can assign value in marginLeft. I think first you have to check if You get any value using the find function and then perform set value to marginLeft.

I think this can be an issue, you are using this code 3 times. After these changes, if you can't fix let's comment here will check further.

You can try :

```<code>let item = this.items.find(i => i.id === 0);
if(item){
 item.marginLeft = -100 * position;
 // you can modify object here and do other things

}

</code>```

Body:
I am making an Image Carousel in Angular that receives a model to iterate the images, but when I try to take the first position it throws me an error.

The left-hand side of an assignment expression may not be an optional property access.ts(2779)

The error is here

export class CarouselComponent implements OnInit {
@Input() height = 500;
@Input() isFullScreen = false;
@Input() items: ICarouselItem[] = [];

public finalHeight: string | number = 0;
public currentPosition = 0;

constructor() {
 this.finalHeight = this.isFullScreen ? '100vh' : `${this.height}px`;
}

ngOnInit(): void {
this.items.map((i, index) =>{
  i.id = index;
  i.marginLeft = 0;
});
}

setCurrentPosition(position: number){
debugger
this.currentPosition = position;
this.items.find(i => i.id === 0)?.marginLeft = -100 * position;

}

setNext(){
debugger
let finalPercentage = 0;
let nextPosition = this.currentPosition + 1;
if(nextPosition <= this.items.length - 1){
  finalPercentage = -100 * nextPosition;
}else{
  nextPosition = 0;
}
this.items.find(i => i.id === 0)?.marginLeft = finalPercentage;
this.currentPosition = nextPosition;
}

setBack(){
let finalPercentage = 0;
let backPosition = this.currentPosition -1;
if(backPosition >= 0){
  finalPercentage = -100 * backPosition;
}else{
  backPosition = this.items.length - 1;
  finalPercentage = -100 * backPosition;
}
this.items.find(i => i.id === 0)?.marginLeft = finalPercentage;
this.currentPosition = backPosition;
}
}

Body:
I think this error is display because you are using find function and directly assign value to this object
Like

this.items.find(i => i.id === 0)?.marginLeft = -100 * position

Suppose you didn't find the object then it will return null then How can assign value in marginLeft. I think first you have to check if You get any value using the find function and then perform set value to marginLeft.

I think this can be an issue, you are using this code 3 times. After these changes, if you can't fix let's comment here will check further.

You can try :

let item = this.items.find(i => i.id === 0);
if(item){
 item.marginLeft = -100 * position;
 // you can modify object here and do other things

}


问:
Unable to redirect from index.html to a Perl script
My web server directories are:

/var/www/cgi-bin

/var/www/example.com/public_html

In my sites-enabled conf file I have:

```<code>ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
 <Directory "/var/www/cgi-bin/">
     Options +ExecCGI
     AddHandler cgi-script .cgi
 </Directory>
</code>```

In my index.html redirect to the index.pl file with:

```<code><meta http-equiv="refresh" content="0; URL='http://example.com/cgi-bin/uploadstart.pl'">
</code>```

The files permissions are:

```<code>-rwxr-xr-x 1 umast   www-data       749 Feb 10 22:34 uploadstart.pl
</code>```

I can run the script via command line directly within the cgi-bin directory.

Yet from my browser I still get:

Forbidden You don't have permission to access this resource.

Apache/2.4.29 (Ubuntu) Server at warptv.com Port 80

Looking at example.com-error.log I see:

AH01630: client denied by server configuration

I know I am missing something. It's been a while, but I was even sure that the group and owner could both be umast.

What am I missing?

答:
Adding:

```<code><Directory /var/www/cgi-bin">
Require all granted
</Directory>
</code>```

will make Apache serve files inside that directory.

Body:
My web server directories are:

/var/www/cgi-bin

/var/www/example.com/public_html

In my sites-enabled conf file I have:

ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
 <Directory "/var/www/cgi-bin/">
     Options +ExecCGI
     AddHandler cgi-script .cgi
 </Directory>

In my index.html redirect to the index.pl file with:

<meta http-equiv="refresh" content="0; URL='http://example.com/cgi-bin/uploadstart.pl'">

The files permissions are:

-rwxr-xr-x 1 umast   www-data       749 Feb 10 22:34 uploadstart.pl

I can run the script via command line directly within the cgi-bin directory.

Yet from my browser I still get:

Forbidden You don't have permission to access this resource.

Apache/2.4.29 (Ubuntu) Server at warptv.com Port 80

Looking at example.com-error.log I see:

AH01630: client denied by server configuration

I know I am missing something. It's been a while, but I was even sure that the group and owner could both be umast.

What am I missing?

Body:
Adding:

<Directory /var/www/cgi-bin">
Require all granted
</Directory>

will make Apache serve files inside that directory.


问:
Flutter TextFormField not updating it's value
i'va made a TimePicker that will pop up when user taps on textFormField it's working fine but the only problem is that i want to update textFormField value by the one selected from timePicker
I've declared a controller and initilize a selectedTimer

```<code>  TimeOfDay selectedTime = TimeOfDay(hour: 0, minute: 0);
  TextEditingController _timeController = TextEditingController();
</code>```

And this is the code of TextFormField

```<code> TextFormField(
      controller: _timeController,
      onTap: () {
         FocusScope.of(context).requestFocus(new FocusNode());
         _selectTime(context);
      },
  ),
</code>```

And this is the code for the method _selectTime

```<code>_selectTime(BuildContext context) async {
    final TimeOfDay? timeOfDay = await showTimePicker(
      context: context,
      initialTime: selectedTime,
      initialEntryMode: TimePickerEntryMode.dial,
    );
    if (timeOfDay != null && timeOfDay != selectedTime) {
      setState(() {
        selectedTime = timeOfDay;
        TextEditingValue(text: timeOfDay.toString());
      });
    }
  }
</code>```

答:
remove this line TextEditingValue(text: timeOfDay.toString());

and replace by this _timeController.text = selectedTime.toString();

Body:
i'va made a TimePicker that will pop up when user taps on textFormField it's working fine but the only problem is that i want to update textFormField value by the one selected from timePicker
I've declared a controller and initilize a selectedTimer

  TimeOfDay selectedTime = TimeOfDay(hour: 0, minute: 0);
  TextEditingController _timeController = TextEditingController();

And this is the code of TextFormField

 TextFormField(
      controller: _timeController,
      onTap: () {
         FocusScope.of(context).requestFocus(new FocusNode());
         _selectTime(context);
      },
  ),

And this is the code for the method _selectTime

_selectTime(BuildContext context) async {
    final TimeOfDay? timeOfDay = await showTimePicker(
      context: context,
      initialTime: selectedTime,
      initialEntryMode: TimePickerEntryMode.dial,
    );
    if (timeOfDay != null && timeOfDay != selectedTime) {
      setState(() {
        selectedTime = timeOfDay;
        TextEditingValue(text: timeOfDay.toString());
      });
    }
  }


问:
React: Setting useState() hook clears out input fields?
Whenever I set a state in my React app, it clears out my inputs (check box, numbers). Here's a very barebones version that illustrates the issue.

```<code>import React, { useState } from "react";
export default function App() {
  const [dummy, setDummy] = useState(false);

  function handleMint() {
    setDummy((dummy) => !dummy);
  }

  const MintBTN = () => (
    <div>
      <div>
        <input className="form-control" type="number" max="20" min="1" />
        <div>
          <input type="checkbox" />
        </div>
      </div>

      <div>
        <button onClick={handleMint}>mint</button>
      </div>
    </div>
  );
  return <MintBTN />;
}
</code>```

You can try it out yourself. Add numbers and click the check box and hit mint. Whamo-bamo, your inputs magically disappear.

https://codesandbox.io/s/friendly-buck-6g6oh?file=/src/App.js:0-499

I figure there's something I'm doing wrong that I just don't see yet. I need to be able to click the button or do an onChange event for the inputs without them clearing out. For some reason setting state is also making my page styles freak out. Not sure what's going on. Some of my key dependencies if those are helpful. Thanks.

```<code>"react": "^17.0.2",
"webpack": "^4.19.1"
</code>```

答:
Each time you set a state (setDummy), the component is rerendered and will reset you're inputs because they are uncontrolled. You need to make them controlled by using state hooks for those inputs.

```<code>import React, { useState } from "react";
export default function App() {
  const [dummy, setDummy] = useState(false);
  const [number, setNumber] = useState(0);
  const [checked, setChecked] = useState(false);

  function handleMint() {
    setDummy((dummy) => !dummy);
  }

  return (
    <div>
      <div>
        <input
          className="form-control"
          type="number"
          max="20"
          min="1"
          value={number}
          onChange={e => setNumber(e.target.value)}
        />
        <div>
          <input
            type="checkbox"
            checked={checked}
            onChange={e => setChecked(e.target.checked)}
          />
        </div>
      </div>

      <div>
        <button onClick={handleMint}>mint</button>
      </div>
    </div>
  );
}
</code>```

Notice the value and checked properties. They are being set by the hook value on each render. Now, notice the onChange property. Each time you interact with the input it will update the hook value and rerender the component. By letting React manage the value and checked properties, it will save the values of the inputs in each hook.

Take a look at Controlled Components and State Hooks

Update

Removed MintBTN function as Nicholas Tower pointed out

Body:
Whenever I set a state in my React app, it clears out my inputs (check box, numbers). Here's a very barebones version that illustrates the issue.

import React, { useState } from "react";
export default function App() {
  const [dummy, setDummy] = useState(false);

  function handleMint() {
    setDummy((dummy) => !dummy);
  }

  const MintBTN = () => (

        <input className="form-control" type="number" max="20" min="1" />

          <input type="checkbox" />

        <button onClick={handleMint}>mint</button>

  );
  return <MintBTN />;
}

You can try it out yourself. Add numbers and click the check box and hit mint. Whamo-bamo, your inputs magically disappear.

https://codesandbox.io/s/friendly-buck-6g6oh?file=/src/App.js:0-499

I figure there's something I'm doing wrong that I just don't see yet. I need to be able to click the button or do an onChange event for the inputs without them clearing out. For some reason setting state is also making my page styles freak out. Not sure what's going on. Some of my key dependencies if those are helpful. Thanks.

"react": "^17.0.2",
"webpack": "^4.19.1"

Body:
Each time you set a state (setDummy), the component is rerendered and will reset you're inputs because they are uncontrolled. You need to make them controlled by using state hooks for those inputs.

import React, { useState } from "react";
export default function App() {
  const [dummy, setDummy] = useState(false);
  const [number, setNumber] = useState(0);
  const [checked, setChecked] = useState(false);

  function handleMint() {
    setDummy((dummy) => !dummy);
  }

  return (
    <div>
      <div>
        <input
          className="form-control"
          type="number"
          max="20"
          min="1"
          value={number}
          onChange={e => setNumber(e.target.value)}
        />
        <div>
          <input
            type="checkbox"
            checked={checked}
            onChange={e => setChecked(e.target.checked)}
          />
        </div>
      </div>

      <div>
        <button onClick={handleMint}>mint</button>
      </div>
    </div>
  );
}

Notice the value and checked properties. They are being set by the hook value on each render. Now, notice the onChange property. Each time you interact with the input it will update the hook value and rerender the component. By letting React manage the value and checked properties, it will save the values of the inputs in each hook.

Take a look at Controlled Components and State Hooks

Update

Removed MintBTN function as Nicholas Tower pointed out


问:
How to limit Google Maps Places Autocomplete API results to cities?
I am building a weather app using openweather API and Google Maps autocomplete API with React. In order to limit suggestions to cities, based on the information I have reached on Google API documentation and this site, I wrote the code on index.html as follows:

Also, added types: ["(cities)"]to the component that input window that uses autocomplete API. But neither of them worked and suggestions still include facility names and so on.

I appreciate your help in advance.

答:
There's no need to put types=(cities) in your Maps JavaScript API script tag. Places APIs can work by including libraries=places alone.

You can use the  types: ["(cities)"] in your autocomplete options or or call setTypes() to  restrict predictions to certain place types.

```<code>const options = {
    types: ["(cities)"],
  };
</code>```

Here's a sample code.

Body:
There's no need to put types=(cities) in your Maps JavaScript API script tag. Places APIs can work by including libraries=places alone.

You can use the  types: ["(cities)"] in your autocomplete options or or call setTypes() to  restrict predictions to certain place types.

const options = {
    types: ["(cities)"],
  };

Here's a sample code.


问:
Sum case when like then
I am using a dataset on BigQuery and essentially I would like to pull a table to show the total volume of liters sold per month of a specific year. This is currently what I have written:

```<code>SELECT
SUM( CASE WHEN `date` LIKE '2012-01-%' THEN `volume_sold_liters` END) as Jan_Total
FROM `personal-projects-340200.Iowa_liquor_cedar_rapids.store_3`
</code>```

This is the error message I am also getting:

No matching signature for operator LIKE for argument types: DATE, STRING. Supported signatures: STRING LIKE STRING; BYTES LIKE BYTES at [2:16]

I understand that the error message is asking for me to change the string to a date but how do I do that? I have multiple dates in the same month that I want added together. I tried to switching the date to a string instead and I get NULL in my table.

What am I doing wrong? Is there a better way to go about pulling the table I want?

答:
You can use the dedicated date functions offered by BigQuery in your case. Since you want the month part of the purchased date you can consider something like the query below

```<code>SELECT
  SUM(CASE
          WHEN DATE_TRUNC(purchase_date, MONTH) = '2022-01-01' THEN volume
          ELSE 0
      END
    ) AS Jan_Total
FROM
  `personal-projects-340200.Iowa_liquor_cedar_rapids.store_3`
</code>```

The error you get is because you try to compare a DATE to a STRING. To fix this you could go for

```<code>SELECT
  SUM(CASE
          WHEN CAST(purchase_date AS STRING) LIKE '2022-01-%' THEN volume
          ELSE 0
      END
    ) AS Jan_Total
FROM
  `personal-projects-340200.Iowa_liquor_cedar_rapids.store_3`
</code>```

But it's better to use date functions when manipulating dates.

Title: Sum case when like then

Body:
I am using a dataset on BigQuery and essentially I would like to pull a table to show the total volume of liters sold per month of a specific year. This is currently what I have written:

SELECT
SUM( CASE WHEN `date` LIKE '2012-01-%' THEN `volume_sold_liters` END) as Jan_Total
FROM `personal-projects-340200.Iowa_liquor_cedar_rapids.store_3`

This is the error message I am also getting:

No matching signature for operator LIKE for argument types: DATE, STRING. Supported signatures: STRING LIKE STRING; BYTES LIKE BYTES at [2:16]

I understand that the error message is asking for me to change the string to a date but how do I do that? I have multiple dates in the same month that I want added together. I tried to switching the date to a string instead and I get NULL in my table.

What am I doing wrong? Is there a better way to go about pulling the table I want?

Body:
You can use the dedicated date functions offered by BigQuery in your case. Since you want the month part of the purchased date you can consider something like the query below

SELECT
  SUM(CASE
          WHEN DATE_TRUNC(purchase_date, MONTH) = '2022-01-01' THEN volume
          ELSE 0
      END
    ) AS Jan_Total
FROM
  `personal-projects-340200.Iowa_liquor_cedar_rapids.store_3`

The error you get is because you try to compare a DATE to a STRING. To fix this you could go for

SELECT
  SUM(CASE
          WHEN CAST(purchase_date AS STRING) LIKE '2022-01-%' THEN volume
          ELSE 0
      END
    ) AS Jan_Total
FROM
  `personal-projects-340200.Iowa_liquor_cedar_rapids.store_3`

But it's better to use date functions when manipulating dates.


问:
How to fix the error (TypeError: Cannot assign to read only property 'map' of object '#<QueryCursor>')
I am sending my data to MongoDB via Mongoose. Now, during the fetch of API route for it, an error is thrown.

Code

const addChoice = async (e) => {
    try {
        e.preventDefault();
        const res = await fetch("/api/sendChoice", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                choiceSeq: choice,
                checkSubmit: true,
            }),
        });
        console.log(res);
        router.push("/home");
    } catch (error) {
        console.log(error);
    }
};
```
<p>The error is happening at <code>const res = await fetch("/api/sendChoice" ,{</code></p>
<p>In terminal server the error</p>
<blockquote>
<p>error - TypeError: Cannot assign to read only property 'map' of object
'#<QueryCursor>'</p>
</blockquote>
<p>In the inspect element the error is as<br />
<img src="https://i.stack.imgur.com/15p7J.png" alt="this" /></p>
<p>I can't find anything related to fix this issue, I don't even understand what the error means to try to resolve it myself.</p>
<p>Some other related code from my project:</p>
<p>api/sendChoice</p>
<pre class="lang-js prettyprint-override"><code>import { getSession } from "next-auth/client";
import dbConnect from "../../helpers/dbConnect";
import Choice from "../../models/Choice";

export default async function sendChoice(req, res) {
    try {
        const session = await getSession({ req });
        await dbConnect();
        if (!session) {
            res.status(401).send("You are not signed in");
            return;
        }
        if (req.method === "POST") {
            console.log(req.body);
            const { choiceSeq, checkSubmit } = req.body;
            console.log(choiceSeq, checkSubmit);
            const userId = session.user.id;
            const nameP = session.user.name;
            const choice = new Choice({
                user: userId,
                name: nameP,
                choiceSeq,
                checkSubmit,
            });
            await choice.save();
            res.status(200).send("Choice saved");
        } else {
            res.status(400).send("Bad request");
        }
    }
    catch (error) {
        console.log(error);
    }
}
</code>```

The MongoDB schema

import mongoose, { Schema } from 'mongoose';

const ChoiceSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'User',
    },
    name: {
        type: String,
    },
    choiceSeq: {
        type: Array,
        default: [],
    },
    checkSubmit: {
        type: Boolean,
    }
});

mongoose.models = {};

export default mongoose.model('Choice', ChoiceSchema);
```

答: the latest update to version 17.5.0 is the one causing this error. You must reinstall node js to version 16.14.0 LTS. You should always work with LTS versions</p>

Body:
I am sending my data to MongoDB via Mongoose. Now, during the fetch of API route for it, an error is thrown.

Code

const addChoice = async (e) => {
    try {
        e.preventDefault();
        const res = await fetch("/api/sendChoice", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                choiceSeq: choice,
                checkSubmit: true,
            }),
        });
        console.log(res);
        router.push("/home");
    } catch (error) {
        console.log(error);
    }
};

The error is happening at const res = await fetch("/api/sendChoice" ,{

In terminal server the error

error - TypeError: Cannot assign to read only property 'map' of object
'#<QueryCursor>'

In the inspect element the error is as

I can't find anything related to fix this issue, I don't even understand what the error means to try to resolve it myself.

Some other related code from my project:

api/sendChoice

import { getSession } from "next-auth/client";
import dbConnect from "../../helpers/dbConnect";
import Choice from "../../models/Choice";

export default async function sendChoice(req, res) {
    try {
        const session = await getSession({ req });
        await dbConnect();
        if (!session) {
            res.status(401).send("You are not signed in");
            return;
        }
        if (req.method === "POST") {
            console.log(req.body);
            const { choiceSeq, checkSubmit } = req.body;
            console.log(choiceSeq, checkSubmit);
            const userId = session.user.id;
            const nameP = session.user.name;
            const choice = new Choice({
                user: userId,
                name: nameP,
                choiceSeq,
                checkSubmit,
            });
            await choice.save();
            res.status(200).send("Choice saved");
        } else {
            res.status(400).send("Bad request");
        }
    }
    catch (error) {
        console.log(error);
    }
}

The MongoDB schema

import mongoose, { Schema } from 'mongoose';

const ChoiceSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'User',
    },
    name: {
        type: String,
    },
    choiceSeq: {
        type: Array,
        default: [],
    },
    checkSubmit: {
        type: Boolean,
    }
});

mongoose.models = {};

export default mongoose.model('Choice', ChoiceSchema);


问:
How do I resolve an Entity Framework error creating the db context
I have created my first (Blazer) project with Entity Framework.  I got enable-migrations and update-database to work.  Now, I get the following build error:

Error while validating the service descriptor 'ServiceType: Timesheet.Models.DatabaseContext Lifetime: Singleton

ImplementationType: Timesheet.Models.DatabaseContext': Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Timesheet.Models.DatabaseContext]' while attempting to activate 'Timesheet.Models.DatabaseContext'.

The error is thrown at this point:

I've tried reading the error multiple times but I'm not sure what it's referring to. I'm hoping someone can point me in the right direction.  Here is the db service in my startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddScoped(p =>
           p.GetRequiredService<IDbContextFactory<DatabaseContext>>().CreateDbContext());
}
</code>```

I just have no idea where to go next. Any suggestions are appreciated.

Edit 1: Adding the full Program.cs file

```<code>using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using Timesheet.Data;
using Timesheet.Models;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<DatabaseContext>();

// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddControllersWithViews()
    .AddMicrosoftIdentityUI();

builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy
    options.FallbackPolicy = options.DefaultPolicy;
});

builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor()
    .AddMicrosoftIdentityConsentHandler();
//builder.Services.AddSingleton<WeatherForecastService>();

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<DatabaseContext>(options =>
    options.UseSqlServer(connectionString));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();
</code>```

答: move your var app = builder.Build()line at the end of UseSqlServer line. first register all of your service then build the app.

Body:
I have created my first (Blazer) project with Entity Framework.  I got enable-migrations and update-database to work.  Now, I get the following build error:

Error while validating the service descriptor 'ServiceType: Timesheet.Models.DatabaseContext Lifetime: Singleton

ImplementationType: Timesheet.Models.DatabaseContext': Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Timesheet.Models.DatabaseContext]' while attempting to activate 'Timesheet.Models.DatabaseContext'.

The error is thrown at this point:

I've tried reading the error multiple times but I'm not sure what it's referring to. I'm hoping someone can point me in the right direction.  Here is the db service in my startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddScoped(p =>
           p.GetRequiredService<IDbContextFactory<DatabaseContext>>().CreateDbContext());
}

I just have no idea where to go next. Any suggestions are appreciated.

Edit 1: Adding the full Program.cs file

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using Timesheet.Data;
using Timesheet.Models;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<DatabaseContext>();

// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddControllersWithViews()
    .AddMicrosoftIdentityUI();

builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy
    options.FallbackPolicy = options.DefaultPolicy;
});

builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor()
    .AddMicrosoftIdentityConsentHandler();
//builder.Services.AddSingleton<WeatherForecastService>();

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<DatabaseContext>(options =>
    options.UseSqlServer(connectionString));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();


答:
You are creating the MintBTN component inside of your App component. This does not work. Every time App renders, you create a brand new type of component. It may have the same text as the previous one, but it's a new type, so react needs to unmount the old one, and mount a new one, which resets the values of stored in any dom elements, and resets any react state.

Instead, create the component once outside of app.

```<code>export default function App() {
  const [dummy, setDummy] = useState(false);

  function handleMint() {
    setDummy((dummy) => !dummy);
  }

  return <MintBTN onClick={handleMint} />;
}

const MintBTN = ({ onClick }) => {
  return (
    <div>
      <div>
        <input className="form-control" type="number" max="20" min="1" />
        <div>
          <input type="checkbox" />
        </div>
      </div>

      <div>
        <button onClick={handleMint}>mint</button>
      </div>
    </div>
  );
};
</code>```

Title: React: Setting useState() hook clears out input fields?

Body:
You are creating the MintBTN component inside of your App component. This does not work. Every time App renders, you create a brand new type of component. It may have the same text as the previous one, but it's a new type, so react needs to unmount the old one, and mount a new one, which resets the values of stored in any dom elements, and resets any react state.

Instead, create the component once outside of app.

export default function App() {
  const [dummy, setDummy] = useState(false);

  function handleMint() {
    setDummy((dummy) => !dummy);
  }

  return <MintBTN onClick={handleMint} />;
}

const MintBTN = ({ onClick }) => {
  return (
    <div>
      <div>
        <input className="form-control" type="number" max="20" min="1" />
        <div>
          <input type="checkbox" />
        </div>
      </div>

      <div>
        <button onClick={handleMint}>mint</button>
      </div>
    </div>
  );
};


问:
How to convert a percentage to a decimal?
So here is an example of my code:

```<code>var = int(input("What is your restaurant bill: "))
var2 = int(input("How much percent did you tip(Don't add the % symbol)? "))
</code>```

I want this to print the percentage increase plus the total. Here is an example:

```<code>#input
var = 50
var2 = 5
#output
50*1.05 = 52.5
</code>```

So in this example, how would I convert the 5% to 1.05?

答: Since var2 shows us the percentage of the tip in probability 1 represents 100% hence var2/100 would show the % out of 1. Now add 1 ( or 100% in our case) to var2/100</p>

Body:
So here is an example of my code:

var = int(input("What is your restaurant bill: "))
var2 = int(input("How much percent did you tip(Don't add the % symbol)? "))

I want this to print the percentage increase plus the total. Here is an example:

#input
var = 50
var2 = 5
#output
50*1.05 = 52.5

So in this example, how would I convert the 5% to 1.05?


问:
How do I replace the list of nan with list of zeroes in a pandas dataframe cell
I have this dataframe. How do I replace the list of nan with list of zeroes?</p>
```<code>a   b
1   [nan, nan]
5   [nan, nan, nan]
0   [0, 0]
</code>```

答:
You can also use fillna by temporarily converting to Series:

```<code>df['b'] = df['b'].apply(lambda x: pd.Series(x).fillna(0).to_list())
</code>```

NB. This is probably not efficient on large datasets. The list comprehension is very likely the fastest.

Body:
I have this dataframe. How do I replace the list of nan with list of zeroes?

a   b
1   [nan, nan]
5   [nan, nan, nan]
0   [0, 0]

Body:
You can also use fillna by temporarily converting to Series:

df['b'] = df['b'].apply(lambda x: pd.Series(x).fillna(0).to_list())

NB. This is probably not efficient on large datasets. The list comprehension is very likely the fastest.


问:
Angular - subject observable not responding
I have one service SelectorService where I have defined the subject and an observable.

```<code>private eventEligibleApiStatus = new Subject<any>();
public eventEligibleApiStatusUpdated$ = this.eventEligibleApiStatus.asObservable();
</code>```

And I have defined a method which calls the subject.next.

```<code>notifyEventEligibleApiStatus(status) {
  this.eventEligibleApiStatus.next(status);
}
</code>```

Now in another component called scheduler-component.ts, I have defined one boolean flag and an observable

```<code>  eventEligibleInProgress = false;

  eventEligibleListener: Observable<any> = this.resourceSelectorService.eventEligibleApiStatusUpdated$;
</code>```

And I am subscribing to this observable

```<code>   this.eventEligibleListener.subscribe( status => {
     this.eventEligibleInProgress = status;
   });
</code>```

From SelectorComponent, I am calling the SelectorService's, notifyEventEligibleApiStatus like this,

```<code>this.selectorService.notifyEventEligibleApiStatus(true);
</code>```

whenever the notifyEventEligibleApiStatus function is triggered, the control does not come to the eventEligibleListener.subscribe and the flag is also not changed.

What am I doing wrong here.

PS: I am new to Angular and Front End development.

答:
May be SelectorService is not SingleTon and creating different object for each component. One way you can try
@Injectable({ providedIn: 'root' })
this will create SingleTon object and same object will be shared across the components.

Body:
I have one service SelectorService where I have defined the subject and an observable.

private eventEligibleApiStatus = new Subject<any>();
public eventEligibleApiStatusUpdated$ = this.eventEligibleApiStatus.asObservable();

And I have defined a method which calls the subject.next.

notifyEventEligibleApiStatus(status) {
  this.eventEligibleApiStatus.next(status);
}

Now in another component called scheduler-component.ts, I have defined one boolean flag and an observable

  eventEligibleInProgress = false;

  eventEligibleListener: Observable<any> = this.resourceSelectorService.eventEligibleApiStatusUpdated$;

And I am subscribing to this observable

   this.eventEligibleListener.subscribe( status => {
     this.eventEligibleInProgress = status;
   });

From SelectorComponent, I am calling the SelectorService's, notifyEventEligibleApiStatus like this,

this.selectorService.notifyEventEligibleApiStatus(true);

whenever the notifyEventEligibleApiStatus function is triggered, the control does not come to the eventEligibleListener.subscribe and the flag is also not changed.

What am I doing wrong here.

PS: I am new to Angular and Front End development.


问:
Efficient way to get indexes of matched items using Lists
I've two lists A and B. I'd like to find out indexes of elements in A that match elements of listB. Something like this:

```<code>ArrayList listA = new ArrayList();
listA.add(1);listA.add(2);listA.add(3);listA.add(4);
ArrayList listB = new ArrayList();
listB.add(2);listB.add(4);
ArrayList listC = new ArrayList();
for(int i=0; i<listB.size();i++) {
   int element = listB.get(i);
   for(int j=0; j<listA.size(); j++) {
      if(listA.get(j) == element) listC.add(j);
   }
}
</code>```

I guess that's one ugly way to doing it. What is the best way to finding all the indexes of A that match all elements in B? I believe there exists a method called containsAll in collections api - don't think it returns matching indexes.

答:
Assuming there's no duplicate values, why not use ArrayList.indexOf?

```<code>public final class ArrayListDemo {
    public static void main(String[]args){
        findIndices(createListA(), createListB());
    }

    private static final List<Integer> createListA(){
        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(3);
        list.add(5);

        return list;
    }

    private static final List<Integer> createListB(){
        List<Integer> list = new ArrayList<Integer>();
        list.add(0);
        list.add(2);
        list.add(3);
        list.add(4);

        return list;
    }

    private static void findIndices(List<Integer> listA, List<Integer> listB){
        for(int i = 0; i < listA.size(); i++){
            // Get index of object in list b
            int index = listB.indexOf(listA.get(i));

            // Check for match
            if(index != -1){
                System.out.println("Found match:");
                System.out.println("List A index = " + i);
                System.out.println("List B index = " + index);
            }
        }
    }
}
</code>```

Output

```<code>Found match:
List A index = 1
List B index = 2
</code>```

Body:
I've two lists A and B. I'd like to find out indexes of elements in A that match elements of listB. Something like this:

ArrayList listA = new ArrayList();
listA.add(1);listA.add(2);listA.add(3);listA.add(4);
ArrayList listB = new ArrayList();
listB.add(2);listB.add(4);
ArrayList listC = new ArrayList();
for(int i=0; i<listB.size();i++) {
   int element = listB.get(i);
   for(int j=0; j<listA.size(); j++) {
      if(listA.get(j) == element) listC.add(j);
   }
}

I guess that's one ugly way to doing it. What is the best way to finding all the indexes of A that match all elements in B? I believe there exists a method called containsAll in collections api - don't think it returns matching indexes.

Body:
Assuming there's no duplicate values, why not use ArrayList.indexOf?

public final class ArrayListDemo {
    public static void main(String[]args){
        findIndices(createListA(), createListB());
    }

    private static final List<Integer> createListA(){
        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(3);
        list.add(5);

        return list;
    }

    private static final List<Integer> createListB(){
        List<Integer> list = new ArrayList<Integer>();
        list.add(0);
        list.add(2);
        list.add(3);
        list.add(4);

        return list;
    }

    private static void findIndices(List<Integer> listA, List<Integer> listB){
        for(int i = 0; i < listA.size(); i++){
            // Get index of object in list b
            int index = listB.indexOf(listA.get(i));

            // Check for match
            if(index != -1){
                System.out.println("Found match:");
                System.out.println("List A index = " + i);
                System.out.println("List B index = " + index);
            }
        }
    }
}

Output

Found match:
List A index = 1
List B index = 2


问:
Using qemu+kvm is slower than using qemu in rv6(xv6 rust porting)
We are currently working on the rv6 project which is porting MIT's educational operating system xv6 to Rust.
 Our code is located here.
We use qemu and qemu's virt platform to execute rv6, and it works well with using qemu.
Executing command on arm machine is this:

```<code>RUST_MODE=release TARGET=arm KVM=yes GIC_VERSION=3
qemu-system-aarch64 -machine virt -kernel kernel/kernel -m 128M -smp 80 -nographic -drive file=fs.img,if=none,format=raw,id=x0,copy-on-read=off -device virtio-blk-device,drive=x0,bus=virtio-mmio-bus.0 -cpu cortex-a53  -machine gic-version=3  -net none
</code>```

To make some speed boost experiment with KVM, we made rv6 support the arm  architecture on arm machine. The arm architecture's driver code locates in here.
The problem is, when we use qemu with kvm, the performance is significantly reduced.
Executing command on arm machine with KVM is this:

```<code>qemu-system-aarch64 -machine virt -kernel kernel/kernel -m 128M -smp 80 -nographic -drive file=fs.img,if=none,format=raw,id=x0,copy-on-read=off -device virtio-blk-device,drive=x0,bus=virtio-mmio-bus.0 -cpu host -enable-kvm  -machine gic-version=3  -net none
</code>```

We repeated

Write 500 bytes syscall 10,000 times and the result was: kvm disable: 4,500,000 us, kvm enable: 29,000,000 us. (> 5 times)

Open/Close syscall 10,000 times result: kvm disable: 12,000,000 us, kvm enable: 29,000,000 us. (> 5 times)

Getppid syscall 10,000 times result: kvm disable: 735,000 us, kvm enable: 825,000 us. (almost same)

Simple calculation(a = a * 1664525 + 1013904223) 100 million times result: kvm disable: 2,800,000 us, kvm enable: 65,000,000 us. (> 20 times)

And the elapsed time was estimated by uptime_as_micro syscall in rv6.
These results were so hard to understand.
So first we tried to find the bottleneck on rv6's booting process, because finding bottleneck during processing user program was so difficult.
We found that the first noticeable bottleneck on rv6 booting process was here:

```<code>run.as_mut().init();
self.runs().push_front(run.as_ref());
</code>```

As far as we know, this part is just kind of "list initialization and push element" part. So we thought that by some reason, the KVM is not actually working and it makes worse result. And also this part is even before turn on some interrupts, so we thought arm's GIC or interrupt related thing is not related with problem.

So, how can I get better performance when using kvm with qemu?

To solve this problem, we tried these already:

change qemu(4.2, 6.2), virt version, change some command for qemu-kvm like cpu, drive cache, copy-on-read something, kernel_irqchip.., cpu core.. etc

find some kvm hypercall to use - but not exists on arm64

Run lmbench by ubuntu on qemu with kvm to check KVM itself is okay. - We found KVM with ubuntu is super faster than only using qemu.

Check 16550a UART print code is really slow on enabling KVM which makes incorrect result on benchmark - Without bottleneck code, we found the progress time of rv6 booting were almost same with KVM enabled or not.

Check other people who suffer same situation like us - but this superuser page not works. Our clocksource is arch_sys_counter.

Our Environment

```<code>qemu-system-aarch64 version: 4.2.1 (Debian 1:4.2-3ubuntu6.19)
CPU model: Neoverse-N1
Architecture: arrch64
CPU op-mode(s): 32-bit, 64-bit
CPU(s): 80
Ubuntu 20.04.3 LTS(Focal Fossa)
/dev/kvm exists
</code>```

答:
The main reason is here: https://forum.osdev.org/viewtopic.php?f=1&t=56120
RV6's memory setting was incorrect.

Change ARM's device memory to cacheable memory for MAIR_EL1 ARM register solved the problem.

Body:
We are currently working on the rv6 project which is porting MIT's educational operating system xv6 to Rust.
 Our code is located here.
We use qemu and qemu's virt platform to execute rv6, and it works well with using qemu.
Executing command on arm machine is this:

RUST_MODE=release TARGET=arm KVM=yes GIC_VERSION=3
qemu-system-aarch64 -machine virt -kernel kernel/kernel -m 128M -smp 80 -nographic -drive file=fs.img,if=none,format=raw,id=x0,copy-on-read=off -device virtio-blk-device,drive=x0,bus=virtio-mmio-bus.0 -cpu cortex-a53  -machine gic-version=3  -net none

To make some speed boost experiment with KVM, we made rv6 support the arm  architecture on arm machine. The arm architecture's driver code locates in here.
The problem is, when we use qemu with kvm, the performance is significantly reduced.
Executing command on arm machine with KVM is this:

qemu-system-aarch64 -machine virt -kernel kernel/kernel -m 128M -smp 80 -nographic -drive file=fs.img,if=none,format=raw,id=x0,copy-on-read=off -device virtio-blk-device,drive=x0,bus=virtio-mmio-bus.0 -cpu host -enable-kvm  -machine gic-version=3  -net none

We repeated

Write 500 bytes syscall 10,000 times and the result was: kvm disable: 4,500,000 us, kvm enable: 29,000,000 us. (> 5 times)

Open/Close syscall 10,000 times result: kvm disable: 12,000,000 us, kvm enable: 29,000,000 us. (> 5 times)

Getppid syscall 10,000 times result: kvm disable: 735,000 us, kvm enable: 825,000 us. (almost same)

Simple calculation(a = a * 1664525 + 1013904223) 100 million times result: kvm disable: 2,800,000 us, kvm enable: 65,000,000 us. (> 20 times)

And the elapsed time was estimated by uptime_as_micro syscall in rv6.
These results were so hard to understand.
So first we tried to find the bottleneck on rv6's booting process, because finding bottleneck during processing user program was so difficult.
We found that the first noticeable bottleneck on rv6 booting process was here:

run.as_mut().init();
self.runs().push_front(run.as_ref());

As far as we know, this part is just kind of "list initialization and push element" part. So we thought that by some reason, the KVM is not actually working and it makes worse result. And also this part is even before turn on some interrupts, so we thought arm's GIC or interrupt related thing is not related with problem.

So, how can I get better performance when using kvm with qemu?

To solve this problem, we tried these already:

change qemu(4.2, 6.2), virt version, change some command for qemu-kvm like cpu, drive cache, copy-on-read something, kernel_irqchip.., cpu core.. etc

find some kvm hypercall to use - but not exists on arm64

Run lmbench by ubuntu on qemu with kvm to check KVM itself is okay. - We found KVM with ubuntu is super faster than only using qemu.

Check 16550a UART print code is really slow on enabling KVM which makes incorrect result on benchmark - Without bottleneck code, we found the progress time of rv6 booting were almost same with KVM enabled or not.

Check other people who suffer same situation like us - but this superuser page not works. Our clocksource is arch_sys_counter.

Our Environment

qemu-system-aarch64 version: 4.2.1 (Debian 1:4.2-3ubuntu6.19)
CPU model: Neoverse-N1
Architecture: arrch64
CPU op-mode(s): 32-bit, 64-bit
CPU(s): 80
Ubuntu 20.04.3 LTS(Focal Fossa)
/dev/kvm exists


问:
Why can't I mock `crypto.createHash`?
I'm trying to test a function which makes use of Node's crypto.createHash function. However, when I try to mock it using jest.mock('crypto', () => ({ createHash: … })), the mock doesn't seem to work.

The unit under test uses both Hash#update and Hash#digest, so I'm trying to add those to the createHash mock, but when the unit runs, createHash returns undefined.

src/hash.ts

import { createHash } from 'crypto';

export function hash(input: string | Uint8Array): Uint8Array {
  return new Uint8Array(createHash('sha512').update(input).digest().buffer);
}
```
<h4><code>src/__test__/hash.test.ts</code></h4>
<pre class="lang-js prettyprint-override"><code>import { createHash } from 'crypto';

import { hash } from '../hash-node.js';

const mockDigest = jest.fn();

jest.mock('crypto', () => ({
  createHash: jest.fn().mockReturnValue({
    update: jest.fn().mockReturnThis(),
    digest: mockDigest,
  }),
}));

describe('hash', () => {
  it('uses SHA512', () => {
    hash('foo');

    expect(createHash).toHaveBeenCalledWith(
      expect.stringMatching(/sha512/i),
    );
  });
});
</code>```

Output

```<code>    TypeError: Cannot read properties of undefined (reading 'update')

      3 |
      4 | export function hash(input: string | Uint8Array): Uint8Array {
    > 5 |   return new Uint8Array(createHash('sha512').update(input).digest().buffer);
        |                         ^
      6 | }
      7 |

      at hash (src/hash.ts:4:25)
      at Object.<anonymous> (src/__test__/hash.test.ts:16:5)

</code>```

As you can see, createHash is clearly returning undefined, as though .mockReturnValue hadn't been called.

What am I doing wrong? How can I get this module mock to work?

答:
I came back to this and was able to figure it out; it's a result of configuring Jest to reset mocks between tests. Once I moved the mockReturnValue call on createHash to inside a beforeEach block, it all started working as expected.

import { type Hash, createHash } from 'crypto';

import { hash } from '../hash.js';

const mockDigest = jest.fn();

jest.mock('crypto', () => ({
  createHash: jest.fn(),
}));

describe('hash', () => {
  beforeEach(() => {
    (createHash as jest.MockedFunction<typeof createHash>).mockReturnValue({
      update: jest.fn().mockReturnThis(),
      digest: mockDigest,
    } as unknown as Hash);
  });

  it('uses SHA512', () => {
    hash('foo');

    expect(createHash).toHaveBeenCalledWith(
      expect.stringMatching(/sha512/i),
    );
  });
});
```

Title: Why can't I mock `crypto.createHash`?

Body:
I'm trying to test a function which makes use of Node's crypto.createHash function. However, when I try to mock it using jest.mock('crypto', () => ({ createHash: … })), the mock doesn't seem to work.

The unit under test uses both Hash#update and Hash#digest, so I'm trying to add those to the createHash mock, but when the unit runs, createHash returns undefined.

src/hash.ts

import { createHash } from 'crypto';

export function hash(input: string | Uint8Array): Uint8Array {
  return new Uint8Array(createHash('sha512').update(input).digest().buffer);
}

src/__test__/hash.test.ts

import { createHash } from 'crypto';

import { hash } from '../hash-node.js';

const mockDigest = jest.fn();

jest.mock('crypto', () => ({
  createHash: jest.fn().mockReturnValue({
    update: jest.fn().mockReturnThis(),
    digest: mockDigest,
  }),
}));

describe('hash', () => {
  it('uses SHA512', () => {
    hash('foo');

    expect(createHash).toHaveBeenCalledWith(
      expect.stringMatching(/sha512/i),
    );
  });
});

Output

    TypeError: Cannot read properties of undefined (reading 'update')

      3 |
      4 | export function hash(input: string | Uint8Array): Uint8Array {
    > 5 |   return new Uint8Array(createHash('sha512').update(input).digest().buffer);
        |                         ^
      6 | }
      7 |

      at hash (src/hash.ts:4:25)
      at Object.<anonymous> (src/__test__/hash.test.ts:16:5)

As you can see, createHash is clearly returning undefined, as though .mockReturnValue hadn't been called.

What am I doing wrong? How can I get this module mock to work?