问:
Temperature Calculator in React Native
I'm trying to develop a basic temp calc and I'm a bit stuck. I've got it somewhat working however, whenever clicking one button they both end up showing results (one of them wrong) and one correct. Also, the both texts and text input change at the same time. Please could help!

Thanks,

```<code> import React, {Component} from 'react';
 import { TextInput,View, Text, Button, StyleSheet } from 'react-native';

 export default class App extends React.Component {

 state = {
    celsius: 0,
    fahrenheit: 0,
}
updateState = () => this.setState ( {

    celsius: (this.state.celsius * 9/5) + 32,
    fahrenheit: (this.state.fahrenheit - 32) * 5 / 9
})
render() {
    const  { celsius, fahrenheit } = this.state

    return (
        <View style={styles.container}>

            <h1> Temperature Converter</h1>

            <TextInput
            value={this.state.celsius}
            onChangeText={ (celsius) => this.setState({ celsius })}
            placeholder={'Celsius Here'}
            style={styles.input}
            />
            <Text style={styles.input}> {celsius} </Text>

            <Button onPress = { () => { this.updateState()}} title="Convert Celsius" />

            <Text>{"\n"}</Text>

            <TextInput
            value={this.state.fahrenheit}
            onChangeText={ (fahrenheit) => this.setState({fahrenheit})}
            placeholder={'Fahrenheit Here'}
            style={styles.input}
            />
            <Text style={styles.input}> {fahrenheit} </Text>

            <Button onPress = { () => {this.updateState()}} title="Convert Fahrenheit" />

          </View>
    )
}
</code>```

}

答:
You are getting issue because

```<code>updateState = () => this.setState ( {

celsius: (this.state.celsius * 9/5) + 32,
fahrenheit: (this.state.fahrenheit - 32) * 5 / 9
})
</code>```

Your initial celsius and fahrenheit is 0.

And you fill 50  for celsius in your first input.
And you press button then you function call.

it convert celsius into 122.
And  fahrenheit: (this.state.fahrenheit - 32) * 5 / 9 this line takes 0 as fahrenheit and calculate to -17.something.
And it change state of your variable. And it keep going on whenever you press the button.

Try after separating both the formula in two different functions.

Try this I have made some changes

```<code>import React, {Component} from 'react';
 import { TextInput,View, Text, Button, StyleSheet } from 'react-native';

export default class App extends React.Component {

 state = {
celsius: null,
fahrenheit: null,
celsius1: null,
fahrenheit1: null,
}
 updateState = () => this.setState ( {

fahrenheit: (this.state.celsius * 9/5) + 32,
//fahrenheit: (this.state.fahrenheit - 32) * 5 / 9
 })
 updateState1 = () => this.setState ( {

//celsius: (this.state.celsius * 9/5) + 32,
celsius1: (this.state.fahrenheit1 - 32) * 5 / 9
  })
 render() {
const  { celsius, fahrenheit, celsius1, fahrenheit1 } = this.state

return (
    <View style={styles.container}>

        {/* <h1> Temperature Converter</h1> */}

        <TextInput
        value={this.state.celsius}
        onChangeText={ (celsius) => this.setState({ celsius })}
        placeholder={'Celsius Here'}
        style={styles.input}
        />
        <Text style={styles.input}> {fahrenheit} </Text>

        <Button onPress = { () => { this.updateState()}} title="Convert Celsius to Fahrenheit" />

        <Text>{"\n"}</Text>

        <TextInput
        value={this.state.fahrenheit1}
        onChangeText={ (fahrenheit1) => this.setState({fahrenheit1})}
        placeholder={'Fahrenheit Here'}
        style={styles.input}
        />
        <Text style={styles.input}> {celsius1} </Text>

        <Button onPress = { () => {this.updateState1()}} title="Convert Fahrenheit to celsius" />

      </View>
)
}
}
</code>```

Title: Temperature Calculator in React Native

Body:
I'm trying to develop a basic temp calc and I'm a bit stuck. I've got it somewhat working however, whenever clicking one button they both end up showing results (one of them wrong) and one correct. Also, the both texts and text input change at the same time. Please could help!

Thanks,

 import React, {Component} from 'react';
 import { TextInput,View, Text, Button, StyleSheet } from 'react-native';

 export default class App extends React.Component {

 state = {
    celsius: 0,
    fahrenheit: 0,
}
updateState = () => this.setState ( {

    celsius: (this.state.celsius * 9/5) + 32,
    fahrenheit: (this.state.fahrenheit - 32) * 5 / 9
})
render() {
    const  { celsius, fahrenheit } = this.state

    return (
        <View style={styles.container}>

 Temperature Converter

            <TextInput
            value={this.state.celsius}
            onChangeText={ (celsius) => this.setState({ celsius })}
            placeholder={'Celsius Here'}
            style={styles.input}
            />
            <Text style={styles.input}> {celsius} </Text>

            <Button onPress = { () => { this.updateState()}} title="Convert Celsius" />

            <Text>{"\n"}</Text>

            <TextInput
            value={this.state.fahrenheit}
            onChangeText={ (fahrenheit) => this.setState({fahrenheit})}
            placeholder={'Fahrenheit Here'}
            style={styles.input}
            />
            <Text style={styles.input}> {fahrenheit} </Text>

            <Button onPress = { () => {this.updateState()}} title="Convert Fahrenheit" />

          </View>
    )
}

}

Body:
You are getting issue because

updateState = () => this.setState ( {

celsius: (this.state.celsius * 9/5) + 32,
fahrenheit: (this.state.fahrenheit - 32) * 5 / 9
})

Your initial celsius and fahrenheit is 0.

And you fill 50  for celsius in your first input.
And you press button then you function call.

it convert celsius into 122.
And  fahrenheit: (this.state.fahrenheit - 32) * 5 / 9 this line takes 0 as fahrenheit and calculate to -17.something.
And it change state of your variable. And it keep going on whenever you press the button.

Try after separating both the formula in two different functions.

Try this I have made some changes

import React, {Component} from 'react';
 import { TextInput,View, Text, Button, StyleSheet } from 'react-native';

export default class App extends React.Component {

 state = {
celsius: null,
fahrenheit: null,
celsius1: null,
fahrenheit1: null,
}
 updateState = () => this.setState ( {

fahrenheit: (this.state.celsius * 9/5) + 32,
//fahrenheit: (this.state.fahrenheit - 32) * 5 / 9
 })
 updateState1 = () => this.setState ( {

//celsius: (this.state.celsius * 9/5) + 32,
celsius1: (this.state.fahrenheit1 - 32) * 5 / 9
  })
 render() {
const  { celsius, fahrenheit, celsius1, fahrenheit1 } = this.state

return (
    <View style={styles.container}>

        {/* <h1> Temperature Converter</h1> */}

        <TextInput
        value={this.state.celsius}
        onChangeText={ (celsius) => this.setState({ celsius })}
        placeholder={'Celsius Here'}
        style={styles.input}
        />
        <Text style={styles.input}> {fahrenheit} </Text>

        <Button onPress = { () => { this.updateState()}} title="Convert Celsius to Fahrenheit" />

        <Text>{"\n"}</Text>

        <TextInput
        value={this.state.fahrenheit1}
        onChangeText={ (fahrenheit1) => this.setState({fahrenheit1})}
        placeholder={'Fahrenheit Here'}
        style={styles.input}
        />
        <Text style={styles.input}> {celsius1} </Text>

        <Button onPress = { () => {this.updateState1()}} title="Convert Fahrenheit to celsius" />

      </View>
)
}
}


来源: stackexchange

问:
How To Play Animation Through Script? - Unity
I am making a game and I made an animation for the win screen. According to all the tutorials I've watched, the animation is played when you activate the GameObject. However, it plays at the Beginning instead. I think the solution would be to play it separately when the game wins. Could you show me how to do that, please? Thank you in advance (:

答:
When you create an Animation for a Game Object it's added as a State in the Animation Controller (Animator).

To Call a specific animation:

Option A:

You can use the Animator Component to play an animation at a specific event

animator.Play("StateName");

Option B:

You can use Animator Parameters (Trigger or Boolean) to play the animation

animator.SetTrigger("TriggerName")

animator.SetBool("BoolName",boolean value)

In Order to use the Animator Parameters, you need to define the parameters and assign them to a specific transition

In this example Once the Boolean Die is true the Animation will occur
(And in the script , you use Animator.SetBool("Die",true) once the health is zero)

ContentLicense: CC BY-SA 4.0


问:
How can I use a std::variant with non-trivial user objects (constructed at a later time), and having the visitor use an auto lambda?
I have code that is something like this:

```<code>using variant_t = std::variant<MyObj1, MyObj2, MyObj3>;

auto foo(){
    variant_t var;

    if (condition1){
        var = MyObj1{"A String"};
        // Other stuff
    } else if (condition2) {
        var = MyObj2{123, 12345};
        // Other stuff
    } else if (condition3) {
        var = MyObj3{SomeObject};
        // Other stuff
    } else {
        throw std::runtime_error{};
    }

    return var;
}

int main(){
    auto var = foo();

    std::visit([&](auto& v){v.call_shared_function_name();}, var);
}
</code>```

Assuming all of the MyObj's are non-trivial, is there a way to get this to work?

I know std::monostate will allow you to initialize the variant in this way and actually populate it later. But if I do so, I can't have the clean auto& lambda in the visitor and will have to create a visitor/lambda for each type.

答:
I know this might looks silly, or not that clean, but you actually need to initialize with one of those objects:

```<code>variant_t var = MyObj1{"A String"};
</code>```

And it compiles fine, if you can't, please let me know and i'll remove the answer

Body:
I have code that is something like this:

using variant_t = std::variant<MyObj1, MyObj2, MyObj3>;

auto foo(){
    variant_t var;

    if (condition1){
        var = MyObj1{"A String"};
        // Other stuff
    } else if (condition2) {
        var = MyObj2{123, 12345};
        // Other stuff
    } else if (condition3) {
        var = MyObj3{SomeObject};
        // Other stuff
    } else {
        throw std::runtime_error{};
    }

    return var;
}

int main(){
    auto var = foo();

    std::visit([&](auto& v){v.call_shared_function_name();}, var);
}

Assuming all of the MyObj's are non-trivial, is there a way to get this to work?

I know std::monostate will allow you to initialize the variant in this way and actually populate it later. But if I do so, I can't have the clean auto& lambda in the visitor and will have to create a visitor/lambda for each type.

Body:
I know this might looks silly, or not that clean, but you actually need to initialize with one of those objects:

variant_t var = MyObj1{"A String"};

And it compiles fine, if you can't, please let me know and i'll remove the answer


问:
recursive binarySearch with array of strings
My function works for the first 4 elements, but returns -1 for 12 and 14..even though there in the array.
I've tried changing some of the if statements and using .compare but haven't had any luck.
Any ideas?
Thanks</p>

```<code>/** Searches the array anArray[first] through anArray[last]
 for a given value by using a binary search.
 @pre 0 <= first, last <= SIZE - 1, where SIZE is the
 maximum size of the array, and anArray[first] <=
 anArray[first + 1] <= ... <= anArray[last].
 @post anArray is unchanged and either anArray[index] contains
 the given value or index == -1.
 @param anArray The array to search.
 @param first The low index to start searching from.
 @param last The high index to stop searching at.
 @param target The search key.
 @return Either index, such that anArray[index] == target, or -1.
 */
int binarySearch(const string anArray[], int first, int last, string target)
{
  int index;
  if (first > last)
    index = -1; // target not in original array
  else {
    // If target is in anArray,
    // anArray[first] <= target <= anArray[last]
    int mid = first + (last - first) / 2;
    if (anArray[mid] == target)
      index = mid; // target found at anArray[mid]
    else if (anArray[mid] > target)
      // Point X
      index = binarySearch(anArray, first, mid - 1, target);
    else
      // Point Y
      index = binarySearch(anArray, mid + 1, last, target);
  } // end if
  return index;
}

int main()
{
  const string v[6] = {"1","5","6","9","12","14"};

  int index;
  string searchItem = "12";

  cout << "Searching For: " << searchItem << endl;

  index = binarySearch(v, 0, 6, searchItem);

  cout << "Element found at index " << index << endl;

  system("pause");

  return 0;
}
</code>```

答:
Problem is the fact that for binary search to work your array has to be sorted with the same criteria you use with your binary search. Array you provided is not sorted. You sorted numbers, but you have strings and they compare differently - lexicographically. Which means that "12" comes before "5" and so on. So you either need to convert strings to numbers before you compare, use proper data type (probably int) or change order of elements in your array accordingly.

Note: your function "works" for the first four elements because for single digit numbers lexicographical and numerical compare is the same.

Note2: you also seem to pass wrong number as last, your doc clearly says "SIZE - 1", which is equal to 5. (your array has indexes from 0 to 5, not to 6)

Body:
My function works for the first 4 elements, but returns -1 for 12 and 14..even though there in the array.
I've tried changing some of the if statements and using .compare but haven't had any luck.
Any ideas?
Thanks

/** Searches the array anArray[first] through anArray[last]
 for a given value by using a binary search.
 @pre 0 <= first, last <= SIZE - 1, where SIZE is the
 maximum size of the array, and anArray[first] <=
 anArray[first + 1] <= ... <= anArray[last].
 @post anArray is unchanged and either anArray[index] contains
 the given value or index == -1.
 @param anArray The array to search.
 @param first The low index to start searching from.
 @param last The high index to stop searching at.
 @param target The search key.
 @return Either index, such that anArray[index] == target, or -1.
 */
int binarySearch(const string anArray[], int first, int last, string target)
{
  int index;
  if (first > last)
    index = -1; // target not in original array
  else {
    // If target is in anArray,
    // anArray[first] <= target <= anArray[last]
    int mid = first + (last - first) / 2;
    if (anArray[mid] == target)
      index = mid; // target found at anArray[mid]
    else if (anArray[mid] > target)
      // Point X
      index = binarySearch(anArray, first, mid - 1, target);
    else
      // Point Y
      index = binarySearch(anArray, mid + 1, last, target);
  } // end if
  return index;
}

int main()
{
  const string v[6] = {"1","5","6","9","12","14"};

  int index;
  string searchItem = "12";

  cout << "Searching For: " << searchItem << endl;

  index = binarySearch(v, 0, 6, searchItem);

  cout << "Element found at index " << index << endl;

  system("pause");

  return 0;
}


问:
convert a irregular time series of a data table with factors into a regular time series in R
I am trying to convert a irregular time series of a data table into a regular time series. My data looks like this

```<code>library(data.table)
dtRes <- data.table(time  = c(0.1, 0.8, 1, 2.3, 2.4, 4.8, 4.9),
                    abst  = c(1, 1, 1, 0, 0, 3, 3),
                    farbe = as.factor(c("keine", "keine", "keine", "keine", "keine", "rot", "blau")),
                    gier  = c(2.5, 2.5, 2.5, 0, 0, 3, 3),
                    goff  = as.factor(c("haus", "maus", "toll", "maus", NA, "maus", "maus")),
                    huft  = as.factor(c(NA, NA, NA, "wolle", "wolle", "holz", "holz")),
                    mode  = c(4, 4, 4, 2.5, NA, 3, 3))
</code>```

How is it possible to aggregate the observations in chunks by taking a chunk size of like 1 second? (with a variable number of rows - even 0 if there are no rows within a 1 second period) The result should be the mean for the numeric columns (NAs omitted) and for the factors a whole duplicated row if there is more than 1 unique value. If this is not possible for factors or doesn't make sense to you, it is also fine to just take the first value of the specific second in the factor column. This way it would be real regular time series without any duplicated times. If there is no value for an interval (like in the example for the 2nd second), the result is NA.

In the end the result can look like this (depends on duplicated rows or not):

with duplicates:

```<code>wiDups <- data.table(time  = c(1, 1, 2, 3, 4, 5, 5),
                     abst  = c(1, 1, NA, 1, NA, 5, 5),
                     farbe = as.factor(c("keine", "keine", NA, "keine", NA, "rot", "blau")),
                     gier  = c(2.5, 2.5, NA, 0, NA, 4.5, 4.5),
                     goff  = as.factor(c("haus", "maus", NA, "maus", NA, "maus", "maus")),
                     huft  = as.factor(c(NA, NA, NA, "wolle", NA, "holz", "holz")),
                     mode  = c(5, 5, NA, 2.5, NA, 4, 4))
</code>```

and without duplicates:

```<code>noDups <- data.table(time  = c(1, 2, 3, 4, 5),
                     abst  = c(1, NA, 1, NA, 5),
                     farbe = as.factor(c("keine", NA, "keine", NA, "rot")),
                     gier  = c(2.5, NA, 0, NA, 4.5),
                     goff  = as.factor(c("haus", NA, "maus", NA, "maus")),
                     huft  = as.factor(c(NA, NA, "wolle", NA, "holz")),
                     mode  = c(5, NA, 2.5, NA, 4))
</code>```

Is it better to convert it into a time series object?

答:
The question is a follow-up to OP's question R combining duplicate rows in a time series with different column types in a datatable.

The OP has requested to turn an irregular time series into a regular time series by aggregating.

This can be achieved by aggregating and filling in missing values by a right join.

```<code>win <- 1   # step size of time series or length of time window
brk <- dtRes[, .(time = tail(scales::fullseq(range(time), win), -1L))]
dtRes[, lapply(.SD, function(x) if (is.numeric(x)) mean(x, na.rm = TRUE)
               else unlist(na.omit(unique(x)))),
      by = .(time = ceiling(time / win) * win)][
        brk, on = .(time)]
</code>```

```<code>   time abst farbe gier goff  huft mode
1:    1    1 keine  2.5 haus  <NA>  4.0
2:    1    1 keine  2.5 maus  <NA>  4.0
3:    1    1 keine  2.5 toll  <NA>  4.0
4:    2   NA  <NA>   NA <NA>  <NA>   NA
5:    3    0 keine  0.0 maus wolle  2.5
6:    4   NA  <NA>   NA <NA>  <NA>   NA
7:    5    3   rot  3.0 maus  holz  3.0
8:    5    3  blau  3.0 maus  holz  3.0
</code>```

For creating the regular time series, fullseq() from the scales package is used for convenience. Apparently, the OP prefers right closed intervals, so the first value can be skipped.

The warning message

In `[.data.table`(dtRes, , lapply(.SD, function(x) if (is.numeric(x)) mean(x,  :

  Item 5 of j's result for group 1 is zero length. This
  will be filled with 3 NAs to match the longest column in this result.
  Later groups may have a similar problem but only the first is reported
  to save filling the warning buffer.

can be happily ignored.

The warning is issued because huft is NA for time == 1. After calling na.omit() the result vector for the huft column is empty but the group result has 3 rows. So, data.table fills the result vector with NA to get a matching length -- which is what we expect.

The solution is parameterised to work with different chunk sizes win. For a chunk size of win <- 0.5, e.g., we get

```<code>    time abst farbe gier goff  huft mode
 1:  0.5    1 keine  2.5 haus  <NA>  4.0
 2:  1.0    1 keine  2.5 maus  <NA>  4.0
 3:  1.0    1 keine  2.5 toll  <NA>  4.0
 4:  1.5   NA  <NA>   NA <NA>  <NA>   NA
 5:  2.0   NA  <NA>   NA <NA>  <NA>   NA
 6:  2.5    0 keine  0.0 maus wolle  2.5
 7:  3.0   NA  <NA>   NA <NA>  <NA>   NA
 8:  3.5   NA  <NA>   NA <NA>  <NA>   NA
 9:  4.0   NA  <NA>   NA <NA>  <NA>   NA
10:  4.5   NA  <NA>   NA <NA>  <NA>   NA
11:  5.0    3   rot  3.0 maus  holz  3.0
12:  5.0    3  blau  3.0 maus  holz  3.0
</code>```

with a lot more rows to fill in.

For a chunk size of win <- 2 we get

```<code>   time abst farbe gier goff  huft mode
1:    2    1 keine  2.5 haus  <NA>  4.0
2:    2    1 keine  2.5 maus  <NA>  4.0
3:    2    1 keine  2.5 toll  <NA>  4.0
4:    4    0 keine  0.0 maus wolle  2.5
5:    6    3   rot  3.0 maus  holz  3.0
6:    6    3  blau  3.0 maus  holz  3.0
</code>```

A time series with multiple rows per time interval is not a regular time series, IMHO. With a slight modificiation, we can get

```<code>win <- 1
brk <- dtRes[, .(time = scales::fullseq(range(time), win)[-1L])]
dtRes[, lapply(.SD, function(x) if (is.numeric(x)) mean(x, na.rm = TRUE)
               else list(na.omit(unique(x)))),
      by = .(time = ceiling(time / win) * win)][
        brk, on = .(time)]
</code>```

```<code>   time abst    farbe gier           goff  huft mode
1:    1    1    keine  2.5 haus,maus,toll        4.0
2:    2   NA            NA                        NA
3:    3    0    keine  0.0           maus wolle  2.5
4:    4   NA            NA                        NA
5:    5    3 rot,blau  3.0           maus  holz  3.0
</code>```

Now, there is only one row per timestep because multiple factor values have been aggregated in a list element.

Body:
I am trying to convert a irregular time series of a data table into a regular time series. My data looks like this

library(data.table)
dtRes <- data.table(time  = c(0.1, 0.8, 1, 2.3, 2.4, 4.8, 4.9),
                    abst  = c(1, 1, 1, 0, 0, 3, 3),
                    farbe = as.factor(c("keine", "keine", "keine", "keine", "keine", "rot", "blau")),
                    gier  = c(2.5, 2.5, 2.5, 0, 0, 3, 3),
                    goff  = as.factor(c("haus", "maus", "toll", "maus", NA, "maus", "maus")),
                    huft  = as.factor(c(NA, NA, NA, "wolle", "wolle", "holz", "holz")),
                    mode  = c(4, 4, 4, 2.5, NA, 3, 3))

How is it possible to aggregate the observations in chunks by taking a chunk size of like 1 second? (with a variable number of rows - even 0 if there are no rows within a 1 second period) The result should be the mean for the numeric columns (NAs omitted) and for the factors a whole duplicated row if there is more than 1 unique value. If this is not possible for factors or doesn't make sense to you, it is also fine to just take the first value of the specific second in the factor column. This way it would be real regular time series without any duplicated times. If there is no value for an interval (like in the example for the 2nd second), the result is NA.

In the end the result can look like this (depends on duplicated rows or not):

with duplicates:

wiDups <- data.table(time  = c(1, 1, 2, 3, 4, 5, 5),
                     abst  = c(1, 1, NA, 1, NA, 5, 5),
                     farbe = as.factor(c("keine", "keine", NA, "keine", NA, "rot", "blau")),
                     gier  = c(2.5, 2.5, NA, 0, NA, 4.5, 4.5),
                     goff  = as.factor(c("haus", "maus", NA, "maus", NA, "maus", "maus")),
                     huft  = as.factor(c(NA, NA, NA, "wolle", NA, "holz", "holz")),
                     mode  = c(5, 5, NA, 2.5, NA, 4, 4))

and without duplicates:

noDups <- data.table(time  = c(1, 2, 3, 4, 5),
                     abst  = c(1, NA, 1, NA, 5),
                     farbe = as.factor(c("keine", NA, "keine", NA, "rot")),
                     gier  = c(2.5, NA, 0, NA, 4.5),
                     goff  = as.factor(c("haus", NA, "maus", NA, "maus")),
                     huft  = as.factor(c(NA, NA, "wolle", NA, "holz")),
                     mode  = c(5, NA, 2.5, NA, 4))

Is it better to convert it into a time series object?

Body:
The question is a follow-up to OP's question R combining duplicate rows in a time series with different column types in a datatable.

The OP has requested to turn an irregular time series into a regular time series by aggregating.

This can be achieved by aggregating and filling in missing values by a right join.

win <- 1   # step size of time series or length of time window
brk <- dtRes[, .(time = tail(scales::fullseq(range(time), win), -1L))]
dtRes[, lapply(.SD, function(x) if (is.numeric(x)) mean(x, na.rm = TRUE)
               else unlist(na.omit(unique(x)))),
      by = .(time = ceiling(time / win) * win)][
        brk, on = .(time)]

   time abst farbe gier goff  huft mode
1:    1    1 keine  2.5 haus  <NA>  4.0
2:    1    1 keine  2.5 maus  <NA>  4.0
3:    1    1 keine  2.5 toll  <NA>  4.0
4:    2   NA  <NA>   NA <NA>  <NA>   NA
5:    3    0 keine  0.0 maus wolle  2.5
6:    4   NA  <NA>   NA <NA>  <NA>   NA
7:    5    3   rot  3.0 maus  holz  3.0
8:    5    3  blau  3.0 maus  holz  3.0

For creating the regular time series, fullseq() from the scales package is used for convenience. Apparently, the OP prefers right closed intervals, so the first value can be skipped.

The warning message

In `[.data.table`(dtRes, , lapply(.SD, function(x) if (is.numeric(x)) mean(x,  :

  Item 5 of j's result for group 1 is zero length. This
  will be filled with 3 NAs to match the longest column in this result.
  Later groups may have a similar problem but only the first is reported
  to save filling the warning buffer.

can be happily ignored.

The warning is issued because huft is NA for time == 1. After calling na.omit() the result vector for the huft column is empty but the group result has 3 rows. So, data.table fills the result vector with NA to get a matching length -- which is what we expect.

The solution is parameterised to work with different chunk sizes win. For a chunk size of win <- 0.5, e.g., we get

    time abst farbe gier goff  huft mode
 1:  0.5    1 keine  2.5 haus  <NA>  4.0
 2:  1.0    1 keine  2.5 maus  <NA>  4.0
 3:  1.0    1 keine  2.5 toll  <NA>  4.0
 4:  1.5   NA  <NA>   NA <NA>  <NA>   NA
 5:  2.0   NA  <NA>   NA <NA>  <NA>   NA
 6:  2.5    0 keine  0.0 maus wolle  2.5
 7:  3.0   NA  <NA>   NA <NA>  <NA>   NA
 8:  3.5   NA  <NA>   NA <NA>  <NA>   NA
 9:  4.0   NA  <NA>   NA <NA>  <NA>   NA
10:  4.5   NA  <NA>   NA <NA>  <NA>   NA
11:  5.0    3   rot  3.0 maus  holz  3.0
12:  5.0    3  blau  3.0 maus  holz  3.0

with a lot more rows to fill in.

For a chunk size of win <- 2 we get

   time abst farbe gier goff  huft mode
1:    2    1 keine  2.5 haus  <NA>  4.0
2:    2    1 keine  2.5 maus  <NA>  4.0
3:    2    1 keine  2.5 toll  <NA>  4.0
4:    4    0 keine  0.0 maus wolle  2.5
5:    6    3   rot  3.0 maus  holz  3.0
6:    6    3  blau  3.0 maus  holz  3.0

A time series with multiple rows per time interval is not a regular time series, IMHO. With a slight modificiation, we can get

win <- 1
brk <- dtRes[, .(time = scales::fullseq(range(time), win)[-1L])]
dtRes[, lapply(.SD, function(x) if (is.numeric(x)) mean(x, na.rm = TRUE)
               else list(na.omit(unique(x)))),
      by = .(time = ceiling(time / win) * win)][
        brk, on = .(time)]

   time abst    farbe gier           goff  huft mode
1:    1    1    keine  2.5 haus,maus,toll        4.0
2:    2   NA            NA                        NA
3:    3    0    keine  0.0           maus wolle  2.5
4:    4   NA            NA                        NA
5:    5    3 rot,blau  3.0           maus  holz  3.0

Now, there is only one row per timestep because multiple factor values have been aggregated in a list element.


问:
How to import SignalR in React Component?
I have used create-react-app to scaffold the initial react application.

My DashBoard component:

```<code>import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import $ from 'jquery';
import 'signalr';

class Dashboard extends Component {
   constructor(props) {
   super(props);
   var connection = $.hubConnection('http://[address]:[port]');
   var proxy = connection.createHubProxy('[hubname]');

    // atempt connection, and handle errors
    connection.start()
    .done(function(){ console.log('Now connected, connection ID=' + connection.id); })
    .fail(function(){ console.log('Could not connect'); });
}

  render() {
    return (...);
  }
}

export default Dashboard;
</code>```

Now I get the below error from SignalR saying jQuery is not added, but I have imported it in the line above:

Error: jQuery was not found. Please ensure jQuery is referenced before
  the SignalR client JavaScript file.

If I comment out import "signalr"; jQuery gets loaded correctly and i can access the $ inside the module. Why does this happen?

答:
This is how we do it now (year 2020) with the new package @microsoft/signalr.
We use Redux, but you don't have to use Redux to be able to utilize this method.

If you are using @microsoft/signalr package instead of @aspnet/signalr, then this is how you can set it up. This is our working code in prod:

```<code>import {
  JsonHubProtocol,
  HubConnectionState,
  HubConnectionBuilder,
  LogLevel
} from '@microsoft/signalr';

const isDev = process.env.NODE_ENV === 'development';

const startSignalRConnection = async connection => {
  try {
    await connection.start();
    console.assert(connection.state === HubConnectionState.Connected);
    console.log('SignalR connection established');
  } catch (err) {
    console.assert(connection.state === HubConnectionState.Disconnected);
    console.error('SignalR Connection Error: ', err);
    setTimeout(() => startSignalRConnection(connection), 5000);
  }
};

// Set up a SignalR connection to the specified hub URL, and actionEventMap.
// actionEventMap should be an object mapping event names, to eventHandlers that will
// be dispatched with the message body.
export const setupSignalRConnection = (connectionHub, actionEventMap = {}, getAccessToken) => (dispatch, getState) => {
  const options = {
    logMessageContent: isDev,
    logger: isDev ? LogLevel.Warning : LogLevel.Error,
    accessTokenFactory: () => getAccessToken(getState())
  };
  // create the connection instance
  // withAutomaticReconnect will automatically try to reconnect
  // and generate a new socket connection if needed
  const connection = new HubConnectionBuilder()
    .withUrl(connectionHub, options)
    .withAutomaticReconnect()
    .withHubProtocol(new JsonHubProtocol())
    .configureLogging(LogLevel.Information)
    .build();

  // Note: to keep the connection open the serverTimeout should be
  // larger than the KeepAlive value that is set on the server
  // keepAliveIntervalInMilliseconds default is 15000 and we are using default
  // serverTimeoutInMilliseconds default is 30000 and we are using 60000 set below
  connection.serverTimeoutInMilliseconds = 60000;

  // re-establish the connection if connection dropped
  connection.onclose(error => {
    console.assert(connection.state === HubConnectionState.Disconnected);
    console.log('Connection closed due to error. Try refreshing this page to restart the connection', error);
  });

  connection.onreconnecting(error => {
    console.assert(connection.state === HubConnectionState.Reconnecting);
    console.log('Connection lost due to error. Reconnecting.', error);
  });

  connection.onreconnected(connectionId => {
    console.assert(connection.state === HubConnectionState.Connected);
    console.log('Connection reestablished. Connected with connectionId', connectionId);
  });

  startSignalRConnection(connection);

  connection.on('OnEvent', res => {
    const eventHandler = actionEventMap[res.eventType];
    eventHandler && dispatch(eventHandler(res));
  });

  return connection;
};
</code>```

Then you would call like the following. Please note that this a pseudo code. You may have to call it differently depending on your project setup.

```<code>import { setupSignalRConnection } from 'fileAbove.js';

const connectionHub = '/hub/service/url/events';

export const setupEventsHub = setupSignalRConnection(connectionHub, {
  onMessageEvent: someMethod
}, getAccessToken);

export default () => dispatch => {
  dispatch(setupEventsHub); // dispatch is coming from Redux
};
</code>```

Let me know if it helped by up-voting. Thank you

ContentLicense: CC BY-SA 3.0

Body:
I have used create-react-app to scaffold the initial react application.

My DashBoard component:

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import $ from 'jquery';
import 'signalr';

class Dashboard extends Component {
   constructor(props) {
   super(props);
   var connection = $.hubConnection('http://[address]:[port]');
   var proxy = connection.createHubProxy('[hubname]');

    // atempt connection, and handle errors
    connection.start()
    .done(function(){ console.log('Now connected, connection ID=' + connection.id); })
    .fail(function(){ console.log('Could not connect'); });
}

  render() {
    return (...);
  }
}

export default Dashboard;

Now I get the below error from SignalR saying jQuery is not added, but I have imported it in the line above:

Error: jQuery was not found. Please ensure jQuery is referenced before
  the SignalR client JavaScript file.

If I comment out import "signalr"; jQuery gets loaded correctly and i can access the $ inside the module. Why does this happen?

Body:
This is how we do it now (year 2020) with the new package @microsoft/signalr.
We use Redux, but you don't have to use Redux to be able to utilize this method.

If you are using @microsoft/signalr package instead of @aspnet/signalr, then this is how you can set it up. This is our working code in prod:

import {
  JsonHubProtocol,
  HubConnectionState,
  HubConnectionBuilder,
  LogLevel
} from '@microsoft/signalr';

const isDev = process.env.NODE_ENV === 'development';

const startSignalRConnection = async connection => {
  try {
    await connection.start();
    console.assert(connection.state === HubConnectionState.Connected);
    console.log('SignalR connection established');
  } catch (err) {
    console.assert(connection.state === HubConnectionState.Disconnected);
    console.error('SignalR Connection Error: ', err);
    setTimeout(() => startSignalRConnection(connection), 5000);
  }
};

// Set up a SignalR connection to the specified hub URL, and actionEventMap.
// actionEventMap should be an object mapping event names, to eventHandlers that will
// be dispatched with the message body.
export const setupSignalRConnection = (connectionHub, actionEventMap = {}, getAccessToken) => (dispatch, getState) => {
  const options = {
    logMessageContent: isDev,
    logger: isDev ? LogLevel.Warning : LogLevel.Error,
    accessTokenFactory: () => getAccessToken(getState())
  };
  // create the connection instance
  // withAutomaticReconnect will automatically try to reconnect
  // and generate a new socket connection if needed
  const connection = new HubConnectionBuilder()
    .withUrl(connectionHub, options)
    .withAutomaticReconnect()
    .withHubProtocol(new JsonHubProtocol())
    .configureLogging(LogLevel.Information)
    .build();

  // Note: to keep the connection open the serverTimeout should be
  // larger than the KeepAlive value that is set on the server
  // keepAliveIntervalInMilliseconds default is 15000 and we are using default
  // serverTimeoutInMilliseconds default is 30000 and we are using 60000 set below
  connection.serverTimeoutInMilliseconds = 60000;

  // re-establish the connection if connection dropped
  connection.onclose(error => {
    console.assert(connection.state === HubConnectionState.Disconnected);
    console.log('Connection closed due to error. Try refreshing this page to restart the connection', error);
  });

  connection.onreconnecting(error => {
    console.assert(connection.state === HubConnectionState.Reconnecting);
    console.log('Connection lost due to error. Reconnecting.', error);
  });

  connection.onreconnected(connectionId => {
    console.assert(connection.state === HubConnectionState.Connected);
    console.log('Connection reestablished. Connected with connectionId', connectionId);
  });

  startSignalRConnection(connection);

  connection.on('OnEvent', res => {
    const eventHandler = actionEventMap[res.eventType];
    eventHandler && dispatch(eventHandler(res));
  });

  return connection;
};

Then you would call like the following. Please note that this a pseudo code. You may have to call it differently depending on your project setup.

import { setupSignalRConnection } from 'fileAbove.js';

const connectionHub = '/hub/service/url/events';

export const setupEventsHub = setupSignalRConnection(connectionHub, {
  onMessageEvent: someMethod
}, getAccessToken);

export default () => dispatch => {
  dispatch(setupEventsHub); // dispatch is coming from Redux
};

Let me know if it helped by up-voting. Thank you


问:
Pandas `groupby.aggregate` on `df.index.duplicated()`
Scenario. Assume a

pd.DataFrame, loaded from an external source

where one row is a line from a sensor. The index is a DateTimeIndex

with some rows having df.index.duplicated()==True. This actually means, there are lines with the same timestamp from different sensors.

Now applying some logic, like df.loc[df.A>0, 'my_col'] = 1, I ran into ValueError: cannot reindex from a duplicate axis. This can be solved by simply removing the duplicated rows using

df[~df.index.duplicated()]

But I wonder, if it would be possible, to actually apply a column based function during the Index de-duplication process? E.g.: Calculating the mean/max/min of column A/B/C for the duplicated rows.

Is this possible? Its something like a groupby.aggregate on df.index.duplicated() rows.

答:
Check with describe

```<code>df.groupby(level=0).describe()
</code>```

Body:
Check with describe

df.groupby(level=0).describe()


问:
"Uncaught Twig_Error_Loader" Error with Materialize Template, OpenCart 3
I am getting below error in my webstore. What it might be or how can I solve this?

Fatal error: Uncaught Twig_Error_Loader: Unable to find template "extension/module/quickorder.twig" (looked into: /home/zulbeaut/ocartdata/storage/modification/catalog/view/theme, /home/zulbeaut/public_html/catalog/view/theme). in /home/zulbeaut/public_html/system/library/template/Twig/Loader/Filesystem.php:215 Stack trace: #0 /home/zulbeaut/public_html/system/library/template/Twig/Loader/Filesystem.php(139): Twig_Loader_Filesystem->findTemplate('extension/modul...') #1 /home/zulbeaut/public_html/system/library/template/Twig/Environment.php(312): Twig_Loader_Filesystem->getCacheKey('extension/modul...') #2 /home/zulbeaut/public_html/system/library/template/Twig/Environment.php(378): Twig_Environment->getTemplateClass('extension/modul...',bize gelecekmiş NULL) #3 /home/zulbeaut/ocartdata/storage/modification/system/library/template/twig.php(42): Twig_Environment->loadTemplate('extension/modul...') #4 /home/zulbeaut/public_html/system/library/template.php(51): Template\Twig->render('extension/modul...', '1') #5 /home/zulbeaut/ocartdata/st in /home/zulbeaut/public_html/system/library/template/Twig/Loader/Filesystem.php on line 215

答:
First of all - clean Theme History in Design - Theme Editor for a Default theme.

Although you have to clear ocmod cache and twig cache.

To clear twig cache in your admin dashboard click on the gear button on top right corner, and then clear the Theme cache.

To clear ocmod cache in admin panel go to Extensions - Modifications and click reload button in top right corner.


问:
How to sort array of structs by char field so that empty fields go to last place?
I have a struct:

```<code>struct StructA{
  char name[TEXT_LEN];
  int year;
};
typedef struct StructA Data_t;
</code>```

And lets say that it can be something like:

```<code>Name: A
Year: 2002

Name:
Year: 2003

Name: C
Year: 2003

Name: B
Year: 2004

Name:
Year: 2005
</code>```

Now I would like to sort it in a way that it sorts first existing values and put empty values in last place. For this I use qsort():

```<code>int compareDataT(const void *v1, const void *v2)
{
    const Data_t *u1 = v1;
    const Data_t *u2 = v2;
    return strcmp(u1->name, u2->name);
}

qsort(items, length, sizeof(Data_t), compareDataT);
</code>```

This gives me:

```<code>Name:
Year: 2003

Name:
Year: 2005

Name: A
Year: 2002

Name: B
Year: 2004

Name: C
Year: 2003
</code>```

If I reverse it in function then it gives me C, B, A, blank, blank...

I want to have it as A, B, C, blank, blank... So, sorted and then put blank values in the end.

I am struggling with this issue for hours... So any help is appreciated.

答:
I suppose that in any case the data member name is initialized and contains at least an empty string "".

In this case the comparison function can look like

```<code>int compareDataT( const void *v1, const void *v2 )
{
    const Data_t *u1 = v1;
    const Data_t *u2 = v2;

    return *u1->name && *u2->name ? strcmp( u1->name, u2->name )
                                  : !*u1->name - !*u2->name;
}
</code>```

Here is a demonstrative program

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TEXT_LEN    10

struct StructA{
  char name[TEXT_LEN];
  int year;
};
typedef struct StructA Data_t;

int compareDataT( const void *v1, const void *v2 )
{
    const Data_t *u1 = v1;
    const Data_t *u2 = v2;

    return *u1->name && *u2->name ? strcmp( u1->name, u2->name )
                                  : !*u1->name - !*u2->name;
}

int main(void)
{
    Data_t data[] =
    {
        { "", 2020 }, { "A", 2020 }, { "", 2020 },
        { "B", 2020 }, { "", 2020 }, { "C", 2020 }
    };
    const size_t N = sizeof( data ) / sizeof( *data );

    qsort( data, N, sizeof( Data_t ), compareDataT );

    for ( size_t i = 0; i < N; i++ )
    {
        printf( "{ \"%s\", %d } ", data[i].name, data[i].year );
    }

    putchar( '\n' );

    return 0;
}
</code>```

Its output is

```<code>{ "A", 2020 } { "B", 2020 } { "C", 2020 } { "", 2020 } { "", 2020 } { "", 2020 }
</code>```

Body:
I have a struct:

struct StructA{
  char name[TEXT_LEN];
  int year;
};
typedef struct StructA Data_t;

And lets say that it can be something like:

Name: A
Year: 2002

Name:
Year: 2003

Name: C
Year: 2003

Name: B
Year: 2004

Name:
Year: 2005

Now I would like to sort it in a way that it sorts first existing values and put empty values in last place. For this I use qsort():

int compareDataT(const void *v1, const void *v2)
{
    const Data_t *u1 = v1;
    const Data_t *u2 = v2;
    return strcmp(u1->name, u2->name);
}

qsort(items, length, sizeof(Data_t), compareDataT);

This gives me:

Name:
Year: 2003

Name:
Year: 2005

Name: A
Year: 2002

Name: B
Year: 2004

Name: C
Year: 2003

If I reverse it in function then it gives me C, B, A, blank, blank...

I want to have it as A, B, C, blank, blank... So, sorted and then put blank values in the end.

I am struggling with this issue for hours... So any help is appreciated.

Body:
I suppose that in any case the data member name is initialized and contains at least an empty string "".

In this case the comparison function can look like

int compareDataT( const void *v1, const void *v2 )
{
    const Data_t *u1 = v1;
    const Data_t *u2 = v2;

    return *u1->name && *u2->name ? strcmp( u1->name, u2->name )
                                  : !*u1->name - !*u2->name;
}

Here is a demonstrative program

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TEXT_LEN    10

struct StructA{
  char name[TEXT_LEN];
  int year;
};
typedef struct StructA Data_t;

int compareDataT( const void *v1, const void *v2 )
{
    const Data_t *u1 = v1;
    const Data_t *u2 = v2;

    return *u1->name && *u2->name ? strcmp( u1->name, u2->name )
                                  : !*u1->name - !*u2->name;
}

int main(void)
{
    Data_t data[] =
    {
        { "", 2020 }, { "A", 2020 }, { "", 2020 },
        { "B", 2020 }, { "", 2020 }, { "C", 2020 }
    };
    const size_t N = sizeof( data ) / sizeof( *data );

    qsort( data, N, sizeof( Data_t ), compareDataT );

    for ( size_t i = 0; i < N; i++ )
    {
        printf( "{ \"%s\", %d } ", data[i].name, data[i].year );
    }

    putchar( '\n' );

    return 0;
}

Its output is

{ "A", 2020 } { "B", 2020 } { "C", 2020 } { "", 2020 } { "", 2020 } { "", 2020 }


问:
how do I assign individual string to an element in one array of pointer?
I am new to C and still trying to figure out pointer.

So here is a task I am stuck in: I would like to assign 10 fruit names to a pointer of array and print them out one by one. Below is my code;

```<code>#include <stdio.h>
#include <string.h>

int main(){
    char *arr_of_ptrs[10];
    char buffer[20];
    int i;
    for (i=0;i<10;i++){
        printf("Please type in a fruit name:");
        fgets(buffer,20,stdin);
        arr_of_ptrs[i]= *buffer;
    }
    int j;
    for (j=0;j<10;j++){
        printf("%s",*(arr_of_ptrs+j));
    }

}
</code>```

However after execution this, it only shows me the last result for all 10 responses. I tried to consult similar questions others asked but no luck.

My understanding is that
1) pointer of array has been allocated memory with [10] so malloc() is not needed.

2) buffer stores the pointer to each individual answer therefore I dereference it and assign it to the arr_of_ptrs[i]
I am unsure if arr_of_ptrs[i] gets me a pointer or a value. I thought it is definitely a pointer but I deference it with * the code and assign it to *buffer, program would get stuck.

If someone could point out my problem that would be great.

Thanks in advance

答:
The misunderstanding is probably that "Dereferencing" an array of characters, unlike dereferencing a pointer to a primitive data type, does not create a copy of that array. Arrays cannot be copied using assignment operator =; There a separate functions for copying arrays (especially for 0-terminated arrays of char aka c-strings, and for allocating memory needed for the copy):

Compare a pointer to a primitive data type like int:

```<code>int x = 10;
int *ptr_x = &x;
int copy_of_x = *ptr_x;  // dereferences a pointer to x, yielding the integer value 10
</code>```

However:

```<code>char x[20] =  "some text";  // array of characters, not a single character!
char *ptr_x = &x[0];  // pointer to the first element of x
char copy_of_first_char_of_x = *ptr_x;  // copies the 's', not the entire string
</code>```

Use:

```<code>char x[20] = "some text";
char *ptr_x = &x[0];
char *copy_of_x = malloc(strlen(ptr_x)+1);  // allocate memory large enough to store the copy
strcpy(copy_of_x,ptr_x);  // copy the string.
printf("%s",copy_of_x);
</code>```

Output:

```<code>some text
</code>```

Body:
I am new to C and still trying to figure out pointer.

So here is a task I am stuck in: I would like to assign 10 fruit names to a pointer of array and print them out one by one. Below is my code;

#include <stdio.h>
#include <string.h>

int main(){
    char *arr_of_ptrs[10];
    char buffer[20];
    int i;
    for (i=0;i<10;i++){
        printf("Please type in a fruit name:");
        fgets(buffer,20,stdin);
        arr_of_ptrs[i]= *buffer;
    }
    int j;
    for (j=0;j<10;j++){
        printf("%s",*(arr_of_ptrs+j));
    }

}

However after execution this, it only shows me the last result for all 10 responses. I tried to consult similar questions others asked but no luck.

My understanding is that
1) pointer of array has been allocated memory with [10] so malloc() is not needed.

2) buffer stores the pointer to each individual answer therefore I dereference it and assign it to the arr_of_ptrs[i]
I am unsure if arr_of_ptrs[i] gets me a pointer or a value. I thought it is definitely a pointer but I deference it with * the code and assign it to *buffer, program would get stuck.

If someone could point out my problem that would be great.

Thanks in advance

Body:
The misunderstanding is probably that "Dereferencing" an array of characters, unlike dereferencing a pointer to a primitive data type, does not create a copy of that array. Arrays cannot be copied using assignment operator =; There a separate functions for copying arrays (especially for 0-terminated arrays of char aka c-strings, and for allocating memory needed for the copy):

Compare a pointer to a primitive data type like int:

int x = 10;
int *ptr_x = &x;
int copy_of_x = *ptr_x;  // dereferences a pointer to x, yielding the integer value 10

However:

char x[20] =  "some text";  // array of characters, not a single character!
char *ptr_x = &x[0];  // pointer to the first element of x
char copy_of_first_char_of_x = *ptr_x;  // copies the 's', not the entire string

Use:

char x[20] = "some text";
char *ptr_x = &x[0];
char *copy_of_x = malloc(strlen(ptr_x)+1);  // allocate memory large enough to store the copy
strcpy(copy_of_x,ptr_x);  // copy the string.
printf("%s",copy_of_x);

Output:

some text


问:
Passing a generic object with type that is derived from the required type
Is it possible to pass a generic object as an argument with a class type that is derived from the expected class type?

The code below results in a compiler error, cannot convert from ItemObject<Equipment> to ItemObject<Item>, which I find odd because Equipment inherits from Item.

```<code>using System.Collections.Generic;

public abstract class Item { }

public abstract class Equipment : Item { }

public class ItemObject<T> where T : Item { }

public class EquipmentManager
{
    ItemObject<Equipment> equipment = new ItemObject<Equipment>();

    public void Unequip()
    {
        Inventory.instance.AddItem(equipment);
    }
}

public class Inventory
{
    public static Inventory instance;
    List<ItemObject<Item>> items = new List<ItemObject<Item>>();

    public void AddItem(ItemObject<Item> _item)
    {
        items.Add(_item);
    }

}
</code>```

答:
You could achieve that using covariance, which would allow you to use a more derived type. However that can only be applied to interfaces, so you would need to do something like this:

public abstract class Item { }

public abstract class Equipment : Item { }

public interface IItemObject<out T> where T : Item { }
public class ItemObject<T> : IItemObject<T> where T : Item { }

public class EquipmentManager {
    IItemObject<Equipment> equipment = new ItemObject<Equipment>();

    public void Unequip() {
        Inventory.instance.AddItem(equipment);
    }
}

public class Inventory {
    public static Inventory instance;
    List<IItemObject<Item>> items = new List<IItemObject<Item>>();

    public void AddItem(IItemObject<Item> _item) {
        items.Add(_item);
    }
}
```

More reading on covariance and contravariance.

Body:
Is it possible to pass a generic object as an argument with a class type that is derived from the expected class type?

The code below results in a compiler error, cannot convert from ItemObject<Equipment> to ItemObject<Item>, which I find odd because Equipment inherits from Item.

using System.Collections.Generic;

public abstract class Item { }

public abstract class Equipment : Item { }

public class ItemObject<T> where T : Item { }

public class EquipmentManager
{
    ItemObject<Equipment> equipment = new ItemObject<Equipment>();

    public void Unequip()
    {
        Inventory.instance.AddItem(equipment);
    }
}

public class Inventory
{
    public static Inventory instance;
    List<ItemObject<Item>> items = new List<ItemObject<Item>>();

    public void AddItem(ItemObject<Item> _item)
    {
        items.Add(_item);
    }

}

Body:
You could achieve that using covariance, which would allow you to use a more derived type. However that can only be applied to interfaces, so you would need to do something like this:

public abstract class Item { }

public abstract class Equipment : Item { }

public interface IItemObject<out T> where T : Item { }
public class ItemObject<T> : IItemObject<T> where T : Item { }

public class EquipmentManager {
    IItemObject<Equipment> equipment = new ItemObject<Equipment>();

    public void Unequip() {
        Inventory.instance.AddItem(equipment);
    }
}

public class Inventory {
    public static Inventory instance;
    List<IItemObject<Item>> items = new List<IItemObject<Item>>();

    public void AddItem(IItemObject<Item> _item) {
        items.Add(_item);
    }
}

More reading on covariance and contravariance.


问:
Filter number followed by dots out of an array
I would like to get rid of the numbers followed by a dot in an array.

I tried something like this.

function parseMoves(){
  const pgnmoves = ["1.", "Nf3", "Nc6", "2.", "Bc4", "e6", "3."] // And so on.
  const reg = new RegExp('[0-9]+\.');
  const filtered = pgnmoves.filter((x) => {
        return x != reg.test(x)
    })
  return filtered;
}```
</div>
</div>
</p>

<p>But that doesn't seem to do the trick, I am not so good with regular expressions.</p>

<p>This is the expected output:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>["Nf3", "Nc6", "Bc4", "e6"]</code>```

Thank you for helping out!

答:
you can try this.</p>

```<code>function parseMoves(){
 const pgnmoves = ["1.", "Nf3", "Nc6", "2.", "Bc4", "e6", "3."]
 const reg = new RegExp(/.*(\d\.)$/);
 const filtered = pgnmoves.filter((x) => {
    return reg.test(x)==false;
 })
 return filtered;
}
</code>```

Body:
I would like to get rid of the numbers followed by a dot in an array.

I tried something like this.

function parseMoves(){
  const pgnmoves = ["1.", "Nf3", "Nc6", "2.", "Bc4", "e6", "3."] // And so on.
  const reg = new RegExp('[0-9]+\.');
  const filtered = pgnmoves.filter((x) => {
        return x != reg.test(x)
    })
  return filtered;
}

But that doesn't seem to do the trick, I am not so good with regular expressions.

This is the expected output:

["Nf3", "Nc6", "Bc4", "e6"]

Thank you for helping out!

Body:
you can try this.

function parseMoves(){
 const pgnmoves = ["1.", "Nf3", "Nc6", "2.", "Bc4", "e6", "3."]
 const reg = new RegExp(/.*(\d\.)$/);
 const filtered = pgnmoves.filter((x) => {
    return reg.test(x)==false;
 })
 return filtered;
}


问:
Which UserControl's calling Event MouseEnter?
I have a list of UserControl and I want to know which UserControl is calling event MouseEnter. I add multiple UserControls on TableLayoutPanel.

List<MyUserControl> form = new List<MyUserControl>();

for (int x = 0; x < dt.Rows.Count; x++)
{
    tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 200));
    if (x == 0)
       tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));
    form.Add(new MyUserControl());
}

for (int x = 0; x < form.Count; x++)
{
    form[x].MouseEnter += new EventHandler(Form_MouseEnter);
    tableLayoutPanel1.Controls.Add(form[x], x, 0);
}
```

How do I find out which UserControl activated the event?

答:
see in docmation

```<code>this.panel1.MouseEnter += new System.EventHandler(this.panel1_MouseEnter);
</code>```

use the sender

```<code>private void panel1_MouseEnter(object sender, System.EventArgs e)
{
    var userControl = sender as MyUserControl
}
</code>```

Body:
I have a list of UserControl and I want to know which UserControl is calling event MouseEnter. I add multiple UserControls on TableLayoutPanel.

List<MyUserControl> form = new List<MyUserControl>();

for (int x = 0; x < dt.Rows.Count; x++)
{
    tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 200));
    if (x == 0)
       tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));
    form.Add(new MyUserControl());
}

for (int x = 0; x < form.Count; x++)
{
    form[x].MouseEnter += new EventHandler(Form_MouseEnter);
    tableLayoutPanel1.Controls.Add(form[x], x, 0);
}

How do I find out which UserControl activated the event?

Body:
see in docmation

this.panel1.MouseEnter += new System.EventHandler(this.panel1_MouseEnter);

use the sender

private void panel1_MouseEnter(object sender, System.EventArgs e)
{
    var userControl = sender as MyUserControl
}


问:
PHP/MySQL Many-to-many relationship - the next step here
I'm new to advanced MySQL having only come across many-to-many relationships yesterday. I'm working on a project where users can join multiple projects and projects can accommodate multiple users.

My tables are:

Users - ID, name, email, password etc
Projects - ID, name, URL etc

Following advice from this site, I have set up a linking table with two foreign keys matched to the IDs of the above tables:

Users_Projects - Users_ID, Projects_ID

I understand the next step is something to do with joining, but how do I add a user to a table, or see who the members of a project are/what projects a particular user is a member of?

答:
Projects for a given user:</p>

```<code>SELECT *
FROM Projects p
LEFT JOIN users_projects up ON p.projects_id = up.projects_id
WHERE up.users_id = [INSERT USERID HERE]
</code>```

Body:
Projects for a given user:

SELECT *
FROM Projects p
LEFT JOIN users_projects up ON p.projects_id = up.projects_id
WHERE up.users_id = [INSERT USERID HERE]


问:
How to take a portion of one column to match with a portion of another column in pandas?
I am trying to clean up a large dataset. A sample of the dataset shows:

```<code>         Player Name        Headline
0        LeBron James       Woj: NBA. ESPN planning for a H-O-R-S-E tourna...
1        LeBron James       LeBron James suggests 5-10 games before playoffs
2        LeBron James       LeBron James overcomes Pelicans with 34/13/12
3        LeBron James       Anthony Davis (knee) won't play on Sunday
...      ...                ...
105180   Ryan Anderson      Ryan Anderson has first career double-double
105181   Ryan Anderson      Yi says he'll be back after All-Star break
105182   Ryan Anderson      Anderson stays hot in Nets win
</code>```

The problem I am having is that some headlines do not have anything to do with the player name (as you can see in row 0, 3, and 105181).

Question:

Is there a way to clean up the data so a portion of the "Player Name" column is featured in the "Headline" column? The rest that don't match would be removed from the new dataset made.

For example:

Row 0 would be removed since "LeBron" or "James" isn't in the "Headline" column.

Row 1 and 2 would stay the same.

Row 3 would be removed since "LeBron" or "James" isn't in the "Headline" column.

Row 105180 would stay the same.

Row 105181 would be removed since "Ryan" or "Anderson" isn't in the "Headline" column.

Row 105182 would stay the same since "Anderson" is in the "Player Name" and "Headline" column.

The new dataset will feature only the filtered data that has a portion of the "Player Name" column in the "Headline" column. I didn't know if there was a way to do this or if str.split should be used on the "Headline" column to split up the name from the rest of the headline then clean up from there.

答:
You can write a function and apply it to each row, like this:

```<code>def keep_headlines(row):
    first = row['Player Name'].split()[0]
    last = row['Player Name'].split()[1]
    if (first in row['Headline']) | (last in row['Headline']):
        return 1
    else:
        return 0
</code>```

you can then apply this function using apply method:

```<code>df['mask'] = df.apply(keep_headlines, axis=1)
df = df[df['mask'] == 1]
</code>```

then you can drop the "mask" column.

```<code>df.drop(columns='mask', inplace=True)
</code>```

I hope this answer helps you!

Body:
I am trying to clean up a large dataset. A sample of the dataset shows:

         Player Name        Headline
0        LeBron James       Woj: NBA. ESPN planning for a H-O-R-S-E tourna...
1        LeBron James       LeBron James suggests 5-10 games before playoffs
2        LeBron James       LeBron James overcomes Pelicans with 34/13/12
3        LeBron James       Anthony Davis (knee) won't play on Sunday
...      ...                ...
105180   Ryan Anderson      Ryan Anderson has first career double-double
105181   Ryan Anderson      Yi says he'll be back after All-Star break
105182   Ryan Anderson      Anderson stays hot in Nets win

The problem I am having is that some headlines do not have anything to do with the player name (as you can see in row 0, 3, and 105181).

Question:

Is there a way to clean up the data so a portion of the "Player Name" column is featured in the "Headline" column? The rest that don't match would be removed from the new dataset made.

For example:

Row 0 would be removed since "LeBron" or "James" isn't in the "Headline" column.

Row 1 and 2 would stay the same.

Row 3 would be removed since "LeBron" or "James" isn't in the "Headline" column.

Row 105180 would stay the same.

Row 105181 would be removed since "Ryan" or "Anderson" isn't in the "Headline" column.

Row 105182 would stay the same since "Anderson" is in the "Player Name" and "Headline" column.

The new dataset will feature only the filtered data that has a portion of the "Player Name" column in the "Headline" column. I didn't know if there was a way to do this or if str.split should be used on the "Headline" column to split up the name from the rest of the headline then clean up from there.

Body:
You can write a function and apply it to each row, like this:

def keep_headlines(row):
    first = row['Player Name'].split()[0]
    last = row['Player Name'].split()[1]
    if (first in row['Headline']) | (last in row['Headline']):
        return 1
    else:
        return 0

you can then apply this function using apply method:

df['mask'] = df.apply(keep_headlines, axis=1)
df = df[df['mask'] == 1]

then you can drop the "mask" column.

df.drop(columns='mask', inplace=True)

I hope this answer helps you!


问:
Using Python to Access Web Data with Regular Expression is not working
I am doing Python for everybody's Course on Coursera so I just learned how to access the file from the Web with Python.

So here what I am trying to do is to extract the Email from the lines which are starting with the From: but I am getting nothing.

There are emails in lines which are starting with From: because I have done this with File Handling method but it's not working when I tried it on file which is on Server so I guess it is to do with the white space.

So Anyways Guys, Help me I am stuck

```<code>import socket
import re
dic = dict()
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    mysock.connect(('data.pr4e.org', 80))
except:
    print("Can't find the server.\nCheck your internet Connection")
cmd = 'GET http://data.pr4e.org/mbox-short.txt HTTP/1.0\r\n\r\n'.encode()
try:
    mysock.send(cmd)
except:
    print("Connection Lost:\nCheck your Internet Connection")
while True:
    data = mysock.recv(512)
    if len(data)  < 1:
        break
    data = data.decode()
    data = data.rstrip()
    k = re.findall('^From:.(\S+@\S+)', data)
    if (len(k)) > 0:
        print(k)
</code>```

This is the Link from where you can download the file

答:
You may get the emails using

```<code>k = re.findall(r'(?m)^From:\s*(\S+@\S+)', data)
</code>```

See the regex demo.

Details

(?m)^ - start of a line

From:  - a literal string

\s* - 0+ whitespaces

(\S+@\S+) - Capturing group 1 (the output of re.findall will only contain this value): one or more non-whitespace chars, @ and one or more non-whitespace chars.

Body:
I am doing Python for everybody's Course on Coursera so I just learned how to access the file from the Web with Python.

So here what I am trying to do is to extract the Email from the lines which are starting with the From: but I am getting nothing.

There are emails in lines which are starting with From: because I have done this with File Handling method but it's not working when I tried it on file which is on Server so I guess it is to do with the white space.

So Anyways Guys, Help me I am stuck

import socket
import re
dic = dict()
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    mysock.connect(('data.pr4e.org', 80))
except:
    print("Can't find the server.\nCheck your internet Connection")
cmd = 'GET http://data.pr4e.org/mbox-short.txt HTTP/1.0\r\n\r\n'.encode()
try:
    mysock.send(cmd)
except:
    print("Connection Lost:\nCheck your Internet Connection")
while True:
    data = mysock.recv(512)
    if len(data)  < 1:
        break
    data = data.decode()
    data = data.rstrip()
    k = re.findall('^From:.(\S+@\S+)', data)
    if (len(k)) > 0:
        print(k)

This is the Link from where you can download the file

Body:
You may get the emails using

k = re.findall(r'(?m)^From:\s*(\S+@\S+)', data)

See the regex demo.

Details

(?m)^ - start of a line

From:  - a literal string

\s* - 0+ whitespaces

(\S+@\S+) - Capturing group 1 (the output of re.findall will only contain this value): one or more non-whitespace chars, @ and one or more non-whitespace chars.


问:
Finding the center of circles in an image
I'm fairly new to programming and need to write a program that will find the center of 4 discs (circles) that are located in each corner of a square image.

I don't know the exact coordinates of the discs but have a very good approximation of them. How can I go about finding the location of the centers of each of the 4 discs?

答:
You can look for the centroid of shapes using moments in OpenCV:

```<code>import cv2

# read image through command line
img = cv2.imread(args["ipimage"])
# or load it from a path
#img = cv2.imread(R"/usr/home/dinges/4c.png")

# convert the image to grayscale
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# convert the grayscale image to binary image
ret,thresh = cv2.threshold(gray_image,127,255,0)

# find contours in the binary image
im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
   # calculate moments for each contour
   M = cv2.moments(c)

   # calculate x,y coordinate of center
   cX = int(M["m10"] / M["m00"])
   cY = int(M["m01"] / M["m00"])
   print('centroid: X:{}, Y:{}'.format(cX, cY))
   cv2.circle(img, (cX, cY), 5, (255, 255, 255), -1)
   cv2.putText(img, "centroid", (cX -25, cY -25),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)

   # display the image
   cv2.imshow("Image", img)
   cv2.waitKey(0)
</code>```

Reference: Find the Center of a Blob (Centroid) using OpenCV

Body:
You can look for the centroid of shapes using moments in OpenCV:

import cv2

# read image through command line
img = cv2.imread(args["ipimage"])
# or load it from a path
#img = cv2.imread(R"/usr/home/dinges/4c.png")

# convert the image to grayscale
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# convert the grayscale image to binary image
ret,thresh = cv2.threshold(gray_image,127,255,0)

# find contours in the binary image
im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
   # calculate moments for each contour
   M = cv2.moments(c)

   # calculate x,y coordinate of center
   cX = int(M["m10"] / M["m00"])
   cY = int(M["m01"] / M["m00"])
   print('centroid: X:{}, Y:{}'.format(cX, cY))
   cv2.circle(img, (cX, cY), 5, (255, 255, 255), -1)
   cv2.putText(img, "centroid", (cX -25, cY -25),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)

   # display the image
   cv2.imshow("Image", img)
   cv2.waitKey(0)

Reference: Find the Center of a Blob (Centroid) using OpenCV


问:
Question about the "Getting Started with BigQuery ML" excercise
Did somebody work on this exercise ? It is a way to estimate transaction in JUNE 2017.
https://codelabs.developers.google.com/codelabs/bqml-intro/index.html#0

When we compare orders JUNE 2017 prediction (step6) versus reality (meaning what we have in BQ), the difference is quite important (more than 50%) - do you know why?

答:
As mentioned by @girishkumar, comparing a single datapoint may not be the best way to evaluate the model performance; at the same time, please consider that the purpose of the codelab is to show how BigQuery ML works.

However, I replicated the lab and observed that if you remove the limit of the SQL statement in the step 4 you got better results in the model evaluation step.

By last, if you are interested in learning how to use this tool, you can try the following tutorials.


问:
Mock my database for all unit tests in PHPUnit
I've just recently started looking into unit testing with PHPUnit and was wondering if it is possible to mock my entire database for all my tests. My model classes (Table Row objects wrapped to provde an ActiveRecord implementation) are rooted to the database and some models have many levels of other model classes so mocking all of this seems like its gona be a pain in the rear end.

Is it possible to get PHPUnit to use data from a CSV file to act as my database and run my tests against the data there without having to touch my DAOs? I've read the section on database testing in PHPUnit but I'm not sure this is what I want because its not so much that I want to test the database or code interacting with the database, its more the fact that my model classes are very tied to the database and it would be a pain having to mock things all the time. If I could give it a CSV file to act as my database then I can just put my data into the CSV file and carry on as normal.

Not sure if I'm making myself clear so please ask for clarification. If it is possible to achieve this then that would be fantastic. Without this unit testing this beast may not be practical but I really want to bring in unit testing to the project.

Thanks

Ziad

答:
You could maybe create a copy of the DB, and simply connect to this copy in your test bootstraps?

I'm kind of in the same situation, and this is the option I'm currently working out... Not perfect, but at least it gets the first tests working


问:
Why is geom_bar not splitting categorical variables
Very new to R programming and trying to create a bar plot, however my categorical x variable remains grouped together and I get a single bar without any usable information. A subsample is as follows:

```<code>     New Name Tot Pl L Ld P Min
 1:        1   376.62     5.91
 2:        4   689.07     7.26
 3:        5   202.14     4.67
 4:        6   516.28     6.01
 5:        7   698.02     7.41
 6:        8   180.50     3.69
 7:        9   163.12     4.24
 8:       10   176.66     4.59
 9:       11   665.34     7.97
10:        2   584.28     6.18
11:        3   155.67     4.04
12:        1   137.28     3.65
13:        4   181.87     4.84
14:        5   152.95     4.07
15:        6   150.07     3.99
16:        7   156.41     4.16
17:        8   108.19     2.88
18:        9   162.76     4.33
19:       10   175.88     4.68
20:       11   160.88     4.28
21:        2   148.53     3.95
22:        3   155.28     4.13
23:        1    62.84    10.49
24:        4   145.73    10.85
25:        5    12.00     8.08
26:        6    68.25     8.92
27:        7   143.88    11.83
28:        8     0.12     0.56
29:        9     0.22     1.04
30:       10     0.39     1.80
31:       11   162.22    12.08
32:        2   115.77     8.62
33:        3     0.11     0.51
</code>```

The code I am using is

```<code>ggplot(ngames, aes(x= 'New Name', y= 'Ld P Min')) + geom_bar(stat = "summary")
</code>```

which gives me this incorrect graph

bad graph.

I have been able to create an example graph of what I'm looking for using stock data from iris, but it doesn't seem to work with my data despite all of data formats being identical to those in iris. example of expected graph. The code for this graph is

```<code>ggplot(iris, aes(x = Species, y = Sepal.Length)) +
  geom_bar(stat = "identity")
</code>```

Thanks for the help.

Body:
Very new to R programming and trying to create a bar plot, however my categorical x variable remains grouped together and I get a single bar without any usable information. A subsample is as follows:

     New Name Tot Pl L Ld P Min
 1:        1   376.62     5.91
 2:        4   689.07     7.26
 3:        5   202.14     4.67
 4:        6   516.28     6.01
 5:        7   698.02     7.41
 6:        8   180.50     3.69
 7:        9   163.12     4.24
 8:       10   176.66     4.59
 9:       11   665.34     7.97
10:        2   584.28     6.18
11:        3   155.67     4.04
12:        1   137.28     3.65
13:        4   181.87     4.84
14:        5   152.95     4.07
15:        6   150.07     3.99
16:        7   156.41     4.16
17:        8   108.19     2.88
18:        9   162.76     4.33
19:       10   175.88     4.68
20:       11   160.88     4.28
21:        2   148.53     3.95
22:        3   155.28     4.13
23:        1    62.84    10.49
24:        4   145.73    10.85
25:        5    12.00     8.08
26:        6    68.25     8.92
27:        7   143.88    11.83
28:        8     0.12     0.56
29:        9     0.22     1.04
30:       10     0.39     1.80
31:       11   162.22    12.08
32:        2   115.77     8.62
33:        3     0.11     0.51

The code I am using is

ggplot(ngames, aes(x= 'New Name', y= 'Ld P Min')) + geom_bar(stat = "summary")

which gives me this incorrect graph

bad graph.

I have been able to create an example graph of what I'm looking for using stock data from iris, but it doesn't seem to work with my data despite all of data formats being identical to those in iris. example of expected graph. The code for this graph is

ggplot(iris, aes(x = Species, y = Sepal.Length)) +
  geom_bar(stat = "identity")

Thanks for the help.

Body:
Let's say your data.frame is like this (it's a nightmare to have spaces for names):

structure(list(`New Name` = structure(c(1L, 4L, 5L, 6L, 7L, 8L,
9L, 10L, 11L, 2L, 3L, 1L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 2L,
3L, 1L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 2L, 3L), .Label = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11"), class = "factor"),
    `Tot Pl L` = c(376.62, 689.07, 202.14, 516.28, 698.02, 180.5,
    163.12, 176.66, 665.34, 584.28, 155.67, 137.28, 181.87, 152.95,
    150.07, 156.41, 108.19, 162.76, 175.88, 160.88, 148.53, 155.28,
    62.84, 145.73, 12, 68.25, 143.88, 0.12, 0.22, 0.39, 162.22,
    115.77, 0.11), `Ld P Min` = c(5.91, 7.26, 4.67, 6.01, 7.41,
    3.69, 4.24, 4.59, 7.97, 6.18, 4.04, 3.65, 4.84, 4.07, 3.99,
    4.16, 2.88, 4.33, 4.68, 4.28, 3.95, 4.13, 10.49, 10.85, 8.08,
    8.92, 11.83, 0.56, 1.04, 1.8, 12.08, 8.62, 0.51)), row.names = c(NA,
33L), class = "data.frame")

Best to convert the "New Name" to factor:

df[["New Name"]] = factor(df[["New Name"]])

Then, you can use put your variable inside the back tick, like variable :

ggplot(df,aes(x=`New Name`,y=`Ld P Min`)) + stat_summary(fun="mean",geom="bar")


问:
Are HTMLCollection and NodeList iterables?
In ES6, an iterable is an object that allows for... of, and has a Symbol.iterator key.

Arrays are iterables, as are Sets and Maps. The question is: are HTMLCollection and NodeList iterables? Are they supposed to be?

MDN documentation seems to suggest a NodeList is an iterable.

for...of loops will loop over NodeList objects correctly, in browsers that support for...of (like Firefox 13 and later)

This appears to corroborate Firefox's behaviour.

I tested the following code in both Chrome and Firefox, and was surprised to find that Firefox seem to think they are iterables, but Chrome does not. In addition, Firefox thinks that the iterators returned by HTMLCollection and NodeList are one and the same.

var col = document.getElementsByClassName('test'); // Should get HTMLCollection of 2 elems
var nod = document.querySelectorAll('.test');      // Should get NodeList of 2 elems
var arr = [].slice.call(col);                      // Should get Array of 2 elems

console.log(col[Symbol.iterator]);    // Firefox: iterator function, Chrome: undefined
console.log(nod[Symbol.iterator]);    // Firefox: iterator function, Chrome: undefined
console.log(arr[Symbol.iterator]);    // Firefox & Chrome: iterator function
console.log(col[Symbol.iterator] === nod[Symbol.iterator]);  // Firefox: true
console.log(col[Symbol.iterator] === arr[Symbol.iterator]);  // Firefox: false```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="test">1</div>
<div class="test">2</div></code>```

One really weird, confusing thing: running the code snippet produces a different result from copying it and running in an actual file/console in Firefox (particularly last comparison). Any enlightenment on this weird behaviour here would be appreciated too.

答:
For anyone arriving here from trying to iterate on NodeList using TypeScript. I found this issue with the fix https://github.com/microsoft/TypeScript/issues/4947 and this is the tsconfig.json you'll need for it:

```<code>{
  "compilerOptions": {
    "lib": ["es2017", "dom", "dom.iterable"],
    "downlevelIteration": true
  }
}
</code>```

The problem error I was getting:

```<code>Type 'NodeListOf<Element>' is not an array type.
</code>```

And this was the code that was triggering that problem:

```<code>[...document.querySelectorAll('#md-view a')]
</code>```

Body:
In ES6, an iterable is an object that allows for... of, and has a Symbol.iterator key.

Arrays are iterables, as are Sets and Maps. The question is: are HTMLCollection and NodeList iterables? Are they supposed to be?

MDN documentation seems to suggest a NodeList is an iterable.

for...of loops will loop over NodeList objects correctly, in browsers that support for...of (like Firefox 13 and later)

This appears to corroborate Firefox's behaviour.

I tested the following code in both Chrome and Firefox, and was surprised to find that Firefox seem to think they are iterables, but Chrome does not. In addition, Firefox thinks that the iterators returned by HTMLCollection and NodeList are one and the same.

var col = document.getElementsByClassName('test'); // Should get HTMLCollection of 2 elems
var nod = document.querySelectorAll('.test');      // Should get NodeList of 2 elems
var arr = [].slice.call(col);                      // Should get Array of 2 elems

console.log(col[Symbol.iterator]);    // Firefox: iterator function, Chrome: undefined
console.log(nod[Symbol.iterator]);    // Firefox: iterator function, Chrome: undefined
console.log(arr[Symbol.iterator]);    // Firefox & Chrome: iterator function
console.log(col[Symbol.iterator] === nod[Symbol.iterator]);  // Firefox: true
console.log(col[Symbol.iterator] === arr[Symbol.iterator]);  // Firefox: false

1

2

One really weird, confusing thing: running the code snippet produces a different result from copying it and running in an actual file/console in Firefox (particularly last comparison). Any enlightenment on this weird behaviour here would be appreciated too.

Body:
For anyone arriving here from trying to iterate on NodeList using TypeScript. I found this issue with the fix https://github.com/microsoft/TypeScript/issues/4947 and this is the tsconfig.json you'll need for it:

{
  "compilerOptions": {
    "lib": ["es2017", "dom", "dom.iterable"],
    "downlevelIteration": true
  }
}

The problem error I was getting:

Type 'NodeListOf<Element>' is not an array type.

And this was the code that was triggering that problem:

[...document.querySelectorAll('#md-view a')]


问:
Propagating property changes in C# across multiple classes
I'm using C#, WPF, and .NETcore3.1 to design a GUI. This is the first time I've used C#, so the project structure I have might seem unusual or suboptimal. While suggestions to make the code more C# friendly are welcome (in that I expect a number of 'use MVVM' answers), that isn't the main question I have here.

I've ended up with the following general structure :

A DLL project which does the business logic, mostly independent of the GUI

A WPF application which I want to use to display information from the DLL

Class-wise, this looks like

A class in the DLL (for the purpose of this question, in practice is a set of classes) which holds the actual business logic, and for all practical purposes you can assume will get changed asynchronously. Lets call this BusinessLogicClass

A class in the GUI project which creates a presentation layer of sorts, essentially reshaping the relevant properties of the BusinessLogicClass into formats that can be directly consumed from the XAML using Bindings. Let's call this the PresentationLayerClass. Note that this is implemented as a User Control.

The XAML GUI itself. Specifically, the XAML GUI for the custom control.

Some pseudocode :

```<code>// In the DLL

class BusinessLogicClass:
    public Boolean status{ get; set; }

// In the GUI

Using DLLNamespace;

public partial class PresentationLayerClass : UserControl

    private BusinessLogicClass actual;

    public PresentationLayerClass(BusinessLogicClass actual){
        InitializeComponent();
        this.DataContext = this;
        this.actual = actual;
    }

    public string ConnectionStatus{
        get{
            if (this.actual.status == true) return "LanConnect";
            else return "LanDisconnect";
        }
    }

    public string StatusColor{
        get {
            if (this.actual.status == true) return "Green";
            else return "Red";
        }
    }

// In the XAML
<iconPacks:PackIconMaterial Kind="{Binding ConnectionStatus}" Margin="5" Foreground="{Binding StatusColor}"/>
</code>```

Now, I understand (though have not yet worked out how to test this) that when the properties of the PresentationLayerClass are changed, the GUI will 'update itself'.

What I would like is that async changes to the status property of the BusinessLogicClass get propagated up the chain all the way to the GUI.

If necessary, for the sake of simplicity and because I don't know enough yet to explain more, assume that everything's on the same thread and the changes which are async are being triggered by the user on the GUI itself. Say a button. However, the button and this display do not and must not know anything about each other. The information must necessarily pass through the DLL, and the DLL must trigger the change to the update.

Also, the DLL should not be hardcoded to the GUI - I want to be able to run the DLL by itself or with a CLI application or another GUI.

I am hoping some combination of INotifyPropertyChanged would do the job, but I can't seem to figure out how I would set that up. INotifyPropertyChanged seems to always be discussed in the context of GUIs and Bindings.

I understand that MVVM is supposed to help simplify this sort of thing. While I have reasons to want to avoid MVVM in this particular instance, I will admit I'm not yet entirely convinced that MVVM is worth the trouble in general. I'm quite averse to the apparently implicit links popular MVVM libraries establish. I have no intention of starting a philosophical discussion on MVVM, but anyone who wishes to disabuse me of that notion may make their case as an aside - as long as you understand that MVVM isn't the subject of the question I ask here.

答:
Not to tell you what you already know, but a lot of your questions might be answered by just reading up on the INotifyPropertyChanged interface.

INotifyPropertyChanged Summary

Normally, no object knows if another object's properties have changed unless a check is performed. This is essentially the purpose of events, to raise an alarm when something changes so other objects don't have to keep checking all the time. But there are numerous way to declare events with all kinds of different signatures.

INotifyPropertyChanged provides a simple, basic standard that can be used to tell other objects when something changes, and what property was changed. It defines the PropertyChanged event, which includes as an argument the name of the property that was changed. A type that implements INotifyPropertyChanged is responsible for explicitly raising the PropertyChanged event when a property changes, this is usually done in the set method of each property.

The WPF framework is designed to support the INotifyPropertyChanged interface. WPF data bindings check for objects that implement INotifyPropertyChanged and listen for the PropertyChanged event. When that even is raised, they check PropertyChangedEventArgs.PropertyName to see which property was changed. If that property is bound to, WPF knows to update that binding.

In WPF, there are also dependency properties. These have a lot useful features, but the most pertinent is that they also implement their own change notification, which WPF knows to look out for.

Your Implementation

The way you have PresentationLayerClass defined currently, the UI will not automatically update if either ConnectionStatus or StatusColor change. This is because those properties are not implemented as either dependency properties or INotifyPropertyChanged properties. Of course, both of those take their values from BusinessLogicClass, so let's start there.

BusinessLogicClass should implement INotifyPropertyChanged, and the status property should raise the PropertyChanged event when it is set.

Along with that, you need to add an event handler to PresentationLayerClass for that event. Example:

private void BusinessLogic_PropertyChanged(object sender, PropertyChangedEventArgs e) and attach the handler in the constructor (public PresentationLayerClass method).

Now at the PresentationLayerClass level, in the BusinessLogic_PropertyChanged method, you have to check which property of BusinessLogicClass has been changed (by using PropertyChangedEventArgs.PropertyName), and then update the values for any property of PresentationLayerClass which is dependent on that changed property. Updating the dependent properties will be different depending on which pattern you decide to use:

PresentationLayerClass uses dependency properties: You will have to explicitly set the new values for each dependent dependency property.

PresentationLayerClass uses INotifyPropertyChanged: You will have to raise the PropertyChanged event once for every dependent property. (Pro tip: use nameof instead of hard-coding the property name).

Body:
I'm using C#, WPF, and .NETcore3.1 to design a GUI. This is the first time I've used C#, so the project structure I have might seem unusual or suboptimal. While suggestions to make the code more C# friendly are welcome (in that I expect a number of 'use MVVM' answers), that isn't the main question I have here.

I've ended up with the following general structure :

A DLL project which does the business logic, mostly independent of the GUI

A WPF application which I want to use to display information from the DLL

Class-wise, this looks like

A class in the DLL (for the purpose of this question, in practice is a set of classes) which holds the actual business logic, and for all practical purposes you can assume will get changed asynchronously. Lets call this BusinessLogicClass

A class in the GUI project which creates a presentation layer of sorts, essentially reshaping the relevant properties of the BusinessLogicClass into formats that can be directly consumed from the XAML using Bindings. Let's call this the PresentationLayerClass. Note that this is implemented as a User Control.

The XAML GUI itself. Specifically, the XAML GUI for the custom control.

Some pseudocode :

// In the DLL

class BusinessLogicClass:
    public Boolean status{ get; set; }

// In the GUI

Using DLLNamespace;

public partial class PresentationLayerClass : UserControl

    private BusinessLogicClass actual;

    public PresentationLayerClass(BusinessLogicClass actual){
        InitializeComponent();
        this.DataContext = this;
        this.actual = actual;
    }

    public string ConnectionStatus{
        get{
            if (this.actual.status == true) return "LanConnect";
            else return "LanDisconnect";
        }
    }

    public string StatusColor{
        get {
            if (this.actual.status == true) return "Green";
            else return "Red";
        }
    }

// In the XAML
<iconPacks:PackIconMaterial Kind="{Binding ConnectionStatus}" Margin="5" Foreground="{Binding StatusColor}"/>

Now, I understand (though have not yet worked out how to test this) that when the properties of the PresentationLayerClass are changed, the GUI will 'update itself'.

What I would like is that async changes to the status property of the BusinessLogicClass get propagated up the chain all the way to the GUI.

If necessary, for the sake of simplicity and because I don't know enough yet to explain more, assume that everything's on the same thread and the changes which are async are being triggered by the user on the GUI itself. Say a button. However, the button and this display do not and must not know anything about each other. The information must necessarily pass through the DLL, and the DLL must trigger the change to the update.

Also, the DLL should not be hardcoded to the GUI - I want to be able to run the DLL by itself or with a CLI application or another GUI.

I am hoping some combination of INotifyPropertyChanged would do the job, but I can't seem to figure out how I would set that up. INotifyPropertyChanged seems to always be discussed in the context of GUIs and Bindings.

I understand that MVVM is supposed to help simplify this sort of thing. While I have reasons to want to avoid MVVM in this particular instance, I will admit I'm not yet entirely convinced that MVVM is worth the trouble in general. I'm quite averse to the apparently implicit links popular MVVM libraries establish. I have no intention of starting a philosophical discussion on MVVM, but anyone who wishes to disabuse me of that notion may make their case as an aside - as long as you understand that MVVM isn't the subject of the question I ask here.


问:
Skipping loop iteration after catch Javascript
I am building an API which needs to make calls to another API (specifically, Quickbooks Online) in a loop. The calls are wrapped in a promise which resolves or rejects based on what is returned from Quickbooks. All works correctly, however, I would like to be able continue the loop after catching errors. Currently, an error is caught and logged to the database, but the loop stops and no further calls are made. I have tried "return" and "continue" in the catch block to no avail.

Example of the code:

```<code>// This is part of a larger loop. Needs to be async
await paymentInfo.forEach(async ln => {

        var payRef = ln.payment_ref
        var vendor = ln.vendor_id

        var finalPayment = await service.createPayment(args)
          .then(console.log("Payment created"))
          .catch((err) => {

            // Log error to DB
            service.dbUpdate(err)
            .then(console.log("Error Logged to DB"))
            .catch(() => {})

            // Continue??
       })
      // Database update here with payment ID
})
</code>```

Ultimately, after the catch I just want to continue to the next iteration of the loop. From what I can see there isn't a simple way to do this. Any advice welcome.

答:
You already use async/await, so no need to use .then. You can just use await and catch errors with regular try/catch, then the continue will also intuitively work if you would put it in a for. But it seems you need to process the loop iterations in parallel, so each iteration will be inside a function invocation, meaning you can just return.

The other issue here is that you don't handle the errors in your async function because it is not awaited. Instead you await the forEach which returns nothing.

The fix is to map your array to an array of promises (the result of executing the anonymous async functions) and then await all those promises at once using Promise.all.

await Promise.all(paymentInfo.map(ln => (async () => {

        var payRef = ln.payment_ref
        var vendor = ln.vendor_id

        try {
            var finalPayment = await service.createPayment(args)
            console.log("Payment created")
        } catch (err) {
            // Log error to DB
            try {
                await service.dbUpdate(err)
                console.log("Error Logged to DB"))
            } catch (e) {}

           return
        }

       // Database update here with payment ID
})())
```

<p>However it doesn't seem logical to me now that you need a <code>continue</code> here after all, if the only reason was that you wanted to react on the possibility that the payment was not created. In that case you'd simply use the payment value unconditionally, because if an error was thrown, it would skip the rest of the <code>try</code> block anyway!</p>

<pre class="lang-js prettyprint-override"><code>await Promise.all(paymentInfo.map((async ln => {

        var payRef = ln.payment_ref
        var vendor = ln.vendor_id

        try {
            var finalPayment = await service.createPayment(args)
            console.log("Payment created")

            // Database update here with payment ID
        } catch (err) {
            // Log error to DB
            try {
                await service.dbUpdate(err)
                console.log("Error Logged to DB"))
            } catch (e) {}
        }
})())
</code>```

Body:
I am building an API which needs to make calls to another API (specifically, Quickbooks Online) in a loop. The calls are wrapped in a promise which resolves or rejects based on what is returned from Quickbooks. All works correctly, however, I would like to be able continue the loop after catching errors. Currently, an error is caught and logged to the database, but the loop stops and no further calls are made. I have tried "return" and "continue" in the catch block to no avail.

Example of the code:

// This is part of a larger loop. Needs to be async
await paymentInfo.forEach(async ln => {

        var payRef = ln.payment_ref
        var vendor = ln.vendor_id

        var finalPayment = await service.createPayment(args)
          .then(console.log("Payment created"))
          .catch((err) => {

            // Log error to DB
            service.dbUpdate(err)
            .then(console.log("Error Logged to DB"))
            .catch(() => {})

            // Continue??
       })
      // Database update here with payment ID
})

Ultimately, after the catch I just want to continue to the next iteration of the loop. From what I can see there isn't a simple way to do this. Any advice welcome.

Body:
You already use async/await, so no need to use .then. You can just use await and catch errors with regular try/catch, then the continue will also intuitively work if you would put it in a for. But it seems you need to process the loop iterations in parallel, so each iteration will be inside a function invocation, meaning you can just return.

The other issue here is that you don't handle the errors in your async function because it is not awaited. Instead you await the forEach which returns nothing.

The fix is to map your array to an array of promises (the result of executing the anonymous async functions) and then await all those promises at once using Promise.all.

await Promise.all(paymentInfo.map(ln => (async () => {

        var payRef = ln.payment_ref
        var vendor = ln.vendor_id

        try {
            var finalPayment = await service.createPayment(args)
            console.log("Payment created")
        } catch (err) {
            // Log error to DB
            try {
                await service.dbUpdate(err)
                console.log("Error Logged to DB"))
            } catch (e) {}

           return
        }

       // Database update here with payment ID
})())

However it doesn't seem logical to me now that you need a continue here after all, if the only reason was that you wanted to react on the possibility that the payment was not created. In that case you'd simply use the payment value unconditionally, because if an error was thrown, it would skip the rest of the try block anyway!

await Promise.all(paymentInfo.map((async ln => {

        var payRef = ln.payment_ref
        var vendor = ln.vendor_id

        try {
            var finalPayment = await service.createPayment(args)
            console.log("Payment created")

            // Database update here with payment ID
        } catch (err) {
            // Log error to DB
            try {
                await service.dbUpdate(err)
                console.log("Error Logged to DB"))
            } catch (e) {}
        }
})())