问:
How to change BACK with onchange with a switch in HTML
I am writing a website, and want to create a dark/light mode. I have a switch that switches when clicked, and it successfully changes to my second css stylesheet. How should I go about switching BACK to the original stylesheet?

HTML-

```<code><link id="pagestyle" rel="stylesheet" type="text/css" href="assets/css/main.css">
<script>
  function swapStyleSheet(sheet) {
    document.getElementById('pagestyle').setAttribute('href', 'assets/css/main2.css');
  }
</script>
<!-- Rectangular switch -->
<label class="switch">
  <input type="checkbox" onchange="swapStyleSheet()"">
    <span class=" slider"></span>
</label>
</code>```

Using this switch style

答:
Listen the checkbox. If it is checked or not. You can give this code a try. This should work.</p>

```<code><link id="pagestyle" rel="stylesheet" type="text/css" href="assets/css/main.css">
<script>
  function swapStyleSheet(sheet) {
    if(document.getElementById("myCheck").checked){
     document.getElementById('pagestyle').setAttribute('href', 'assets/css/main2.css');
    }else{
      document.getElementById('pagestyle').setAttribute('href', 'assets/css/default.css');
    }
  }
</script>
<!-- Rectangular switch -->
<label class="switch">
  <input type="checkbox" id="myCheck" onchange="swapStyleSheet()"">
    <span class=" slider"></span>
</label>
</code>```

Body:
I am writing a website, and want to create a dark/light mode. I have a switch that switches when clicked, and it successfully changes to my second css stylesheet. How should I go about switching BACK to the original stylesheet?

HTML-

<link id="pagestyle" rel="stylesheet" type="text/css" href="assets/css/main.css">

  <input type="checkbox" onchange="swapStyleSheet()"">

Using this switch style

Body:
Listen the checkbox. If it is checked or not. You can give this code a try. This should work.

<link id="pagestyle" rel="stylesheet" type="text/css" href="assets/css/main.css">
<script>
  function swapStyleSheet(sheet) {
    if(document.getElementById("myCheck").checked){
     document.getElementById('pagestyle').setAttribute('href', 'assets/css/main2.css');
    }else{
      document.getElementById('pagestyle').setAttribute('href', 'assets/css/default.css');
    }
  }
</script>
<!-- Rectangular switch -->
<label class="switch">
  <input type="checkbox" id="myCheck" onchange="swapStyleSheet()"">
    <span class=" slider"></span>
</label>


来源: stackexchange

问:
String.IndexOf() returns unexpected index of string
String.IndexOf() method is not acting as I expected.

I expected it not to find a match, since the exact word you is not in str.

```<code>string str = "I am your Friend";
int index = str.IndexOf("you",0,StringComparison.OrdinalIgnoreCase);
Console.WriteLine(index);
</code>```

Output: 5

My Expected Result is -1 because the string doesn't contain you.

答:
you is a valid substring of I am your Friend. If you would like to find if a word is in a string you can parse the string with Split method.

```<code>char[] delimiterChars = { ' ', ',', '.', ':', '\t' };
string[] words = text.Split(delimiterChars);
</code>```

And then look inside the array. Or turn it into more lookup-friendly data structure.

If you would like to search case-insensitive you can use the following code:

```<code>char[] delimiterChars = { ' ', ',', '.', ':', '\t' };
string text = "I am your Friend";
// HasSet allows faster lookups in case of big strings
var words = text.Split(delimiterChars).ToHashSet(StringComparer.OrdinalIgnoreCase);
Console.WriteLine(words.Contains("you"));
Console.WriteLine(words.Contains("friend"));
</code>```

False

  True

Creating dictionary as in the following code-snippet you can quickly check all positions for all words.

```<code>char[] delimiterChars = { ' ', ',', '.', ':', '\t' };
string text = "i am your friend. I Am Your Friend.";
var words = text.Split(delimiterChars);
var dict = new Dictionary<string, List<int>>(StringComparer.InvariantCultureIgnoreCase);
for (int i = 0; i < words.Length; ++i)
{
    if (dict.ContainsKey(words[i])) dict[words[i]].Add(i);
    else dict[words[i]] = new List<int>() { i };
}

Console.WriteLine("youR: ");
dict["youR"].ForEach(i => Console.WriteLine("\t{0}", i));
Console.WriteLine("friend");
dict["friend"].ForEach(i => Console.WriteLine("\t{0}", i));
</code>```

```<code>youR:
        2
        7
friend
        3
        8
</code>```

ContentLicense: CC BY-SA 4.0

Body:
String.IndexOf() method is not acting as I expected.

I expected it not to find a match, since the exact word you is not in str.

string str = "I am your Friend";
int index = str.IndexOf("you",0,StringComparison.OrdinalIgnoreCase);
Console.WriteLine(index);

Output: 5

My Expected Result is -1 because the string doesn't contain you.

Body:
you is a valid substring of I am your Friend. If you would like to find if a word is in a string you can parse the string with Split method.

char[] delimiterChars = { ' ', ',', '.', ':', '\t' };
string[] words = text.Split(delimiterChars);

And then look inside the array. Or turn it into more lookup-friendly data structure.

If you would like to search case-insensitive you can use the following code:

char[] delimiterChars = { ' ', ',', '.', ':', '\t' };
string text = "I am your Friend";
// HasSet allows faster lookups in case of big strings
var words = text.Split(delimiterChars).ToHashSet(StringComparer.OrdinalIgnoreCase);
Console.WriteLine(words.Contains("you"));
Console.WriteLine(words.Contains("friend"));

False

  True

Creating dictionary as in the following code-snippet you can quickly check all positions for all words.

char[] delimiterChars = { ' ', ',', '.', ':', '\t' };
string text = "i am your friend. I Am Your Friend.";
var words = text.Split(delimiterChars);
var dict = new Dictionary<string, List<int>>(StringComparer.InvariantCultureIgnoreCase);
for (int i = 0; i < words.Length; ++i)
{
    if (dict.ContainsKey(words[i])) dict[words[i]].Add(i);
    else dict[words[i]] = new List<int>() { i };
}

Console.WriteLine("youR: ");
dict["youR"].ForEach(i => Console.WriteLine("\t{0}", i));
Console.WriteLine("friend");
dict["friend"].ForEach(i => Console.WriteLine("\t{0}", i));

youR:
        2
        7
friend
        3
        8


问:
How to submit a route overlay on my map and then to see it on the map?
I'm creating my android application with the Here Map Android Premium SDK. I would like to add route overlays and to calculate routes on them.

I tried to submit the example overlay described on their documentation. So my command with cURL is:

```<code>curl -G http://cre.api.here.com/2/overlays/upload.json  --data-urlencode "map_name=OVERLAYEXAMPLE1"  --data-urlencode 'overlay_spec=[{ "op":"override", "shape":[[50.10765,8.68774],[50.10914,8.68771]], "layer":"LINK_ATTRIBUTE_FCN", "data":{"VEHICLE_TYPES":"0"}  }, { "op":"create", "shape":[[50.10937,8.68422],[50.10807,8.68525],[50.10737,8.68387]], "data":{"NAMES":"ENGBNDemo Road"}  }, { "op":"override", "shape":[[50.10937,8.68422],[50.10807,8.68525],[50.10737,8.68387]], "layer":"TRUCK_RESTR_FCN", "data":{"VEHICLE_TYPES":"truck", "WEIGHT_RESTRICTION":"3300"}  }]'  --data-urlencode "storage=readonly"  --data-urlencode "app_id=PN********7w"  --data-urlencode "app_code=n4***********9Q"
</code>```

The server responds something with:

```<code>"response_code": "201 Created"
</code>```

I can see my map has been correctly uploaded by listing it with :

```<code>curl -G https://fleet.api.here.com/2/doc/maps.json ...
</code>```

I expect to see new route on the map and to be able to calculate itinerary through it, but I can't see it on my map and the calculation don't use it.

On this api-reference I can see an "overlays" option to the calculation query. Shall I list all my overlays in this parameter to use them ? Is there something equivalent for the map display ?

More, is it possible to use this new route with the offline router ?

答:
please see the below api document.

Search for custom geometries by attribute filter, or download complete layer.

https://developer.here.com/documentation/fleet-telematics/api-reference.html#operation%2FsearchAllUsingGET

Here is a sample.

```<code>https://cre.api.here.com/2/search/all.json?map_name=OVERLAYMYMAP&geom=full&layer_id=LINK_ATTRIBUTE_FCn&acceptMissingLayers=true&app_id={{app_id}}&app_code={{app_code}}
</code>```

I hope this help!

Body:
I'm creating my android application with the Here Map Android Premium SDK. I would like to add route overlays and to calculate routes on them.

I tried to submit the example overlay described on their documentation. So my command with cURL is:

curl -G http://cre.api.here.com/2/overlays/upload.json  --data-urlencode "map_name=OVERLAYEXAMPLE1"  --data-urlencode 'overlay_spec=[{ "op":"override", "shape":[[50.10765,8.68774],[50.10914,8.68771]], "layer":"LINK_ATTRIBUTE_FCN", "data":{"VEHICLE_TYPES":"0"}  }, { "op":"create", "shape":[[50.10937,8.68422],[50.10807,8.68525],[50.10737,8.68387]], "data":{"NAMES":"ENGBNDemo Road"}  }, { "op":"override", "shape":[[50.10937,8.68422],[50.10807,8.68525],[50.10737,8.68387]], "layer":"TRUCK_RESTR_FCN", "data":{"VEHICLE_TYPES":"truck", "WEIGHT_RESTRICTION":"3300"}  }]'  --data-urlencode "storage=readonly"  --data-urlencode "app_id=PN********7w"  --data-urlencode "app_code=n4***********9Q"

The server responds something with:

"response_code": "201 Created"

I can see my map has been correctly uploaded by listing it with :

curl -G https://fleet.api.here.com/2/doc/maps.json ...

I expect to see new route on the map and to be able to calculate itinerary through it, but I can't see it on my map and the calculation don't use it.

On this api-reference I can see an "overlays" option to the calculation query. Shall I list all my overlays in this parameter to use them ? Is there something equivalent for the map display ?

More, is it possible to use this new route with the offline router ?

Body:
please see the below api document.

Search for custom geometries by attribute filter, or download complete layer.

https://developer.here.com/documentation/fleet-telematics/api-reference.html#operation%2FsearchAllUsingGET

Here is a sample.

https://cre.api.here.com/2/search/all.json?map_name=OVERLAYMYMAP&geom=full&layer_id=LINK_ATTRIBUTE_FCn&acceptMissingLayers=true&app_id={{app_id}}&app_code={{app_code}}

I hope this help!


问:
C++ char* array
When I create something like

```<code>char* t = new char[44];
t = strcpy(s,t);
</code>```

then strlen(t); return some wrong results. how I can change this?

答:
You have to initialize the variable t

Do something like this:

```<code>char *t = new char[44];
memset(t, 0, 44);

// strlen(t) = 0
</code>```

OwnerDisplayName: Александр Брус

ContentLicense: CC BY-SA 3.0

Title: C++ char* array

Body:
When I create something like

char* t = new char[44];
t = strcpy(s,t);

then strlen(t); return some wrong results. how I can change this?

Body:
You have to initialize the variable t

Do something like this:

char *t = new char[44];
memset(t, 0, 44);

// strlen(t) = 0


问:
Process multi-level nested escaped JSON strings inside JSON with fluentd
I'm new to fluentd and I would like to parse a multi-level nested escaped JSON strings inside JSON.

My messages look like:

```<code>{"log":"HELLO WORLD\n","stream":"stdout","time":"2019-05-23T15:40:54.298531098Z"}

{"log":"{\"appName\":\"adapter\",\"time\":\"2019-05-23T15:40:54.299\",\"message\":\"{\\\"level\\\":\\\"info\\\",\\\"message\\\":\\\"Awaiting Messages from queue...\\\"}\"}\n","stream":"stdout","time":"2019-05-23T15:40:54.2996761Z"}
</code>```

The first message get parsed correctly but the second one got ignored and I guess it's because of an error in parsing format

Here is my source:

```<code>    <source>
      @id fluentd-containers.log
      @type tail
      path /var/log/containers/*.log
      pos_file /var/log/containers.log.pos
      tag raw.kubernetes.*
      read_from_head true
      <parse>
        @type multi_format
        <pattern>
          format json
          time_key time
          time_format %Y-%m-%dT%H:%M:%S.%NZ
        </pattern>
        <pattern>
          format /^(?<time>.+) (?<stream>stdout|stderr) [^ ]* (?<log>.*)$/
          time_format %Y-%m-%dT%H:%M:%S.%N%:z
        </pattern>
      </parse>
    </source>
</code>```

Here is what I tried:

```<code>    <filter **>
      @type parser
      key_name log
      reserve_data true
      remove_key_name_field true
      hash_value_field parsed_log
      <parse>
        @type json
      </parse>
    </filter>
</code>```

i actually just want to parse this log message:

```<code>{
"log":"{\"appName\":\"dedge-adapter\",\"time\":\"2019-05-24T02:39:12.242\",\"message\":\"{\\\"level\\\":\\\"warn\\\",\\\"status\\\":401,\\\"method\\\":\\\"GET\\\",\\\"path\\\":\\\"/api/v1/bookings\\\",\\\"requestId\\\":\\\"782a470b-9d62-43d3-9865-1b67397717d4\\\",\\\"ip\\\":\\\"90.79.204.18\\\",\\\"latency\\\":0.097897,\\\"user-agent\\\":\\\"PostmanRuntime/7.11.0\\\",\\\"message\\\":\\\"Request\\\"}\"}\n",
"stream":"stdout",
"time":"2019-05-24T02:39:12.242383376Z"
}
</code>```

答:
Do you have multiple format log field?
If so, you can use https://github.com/repeatedly/fluent-plugin-multi-format-parser

```<code><source>
  @type dummy
  tag dummy
  dummy [
    {"log":"HELLO WORLD\n","stream":"stdout","time":"2019-05-23T15:40:54.298531098Z"},
    {"log":"{\"appName\":\"adapter\",\"time\":\"2019-05-23T15:40:54.299\",\"message\":\"{\\\"level\\\":\\\"info\\\",\\\"message\\\":\\\"Awaiting Messages from queue...\\\"}\"}\n","stream":"stdout","time":"2019-05-23T15:40:54.2996761Z"}
  ]
</source>

<filter dummy>
  @type parser
  key_name log
  reserve_data true
  remove_key_name_field true
  <parse>
    @type multi_format
    <pattern>
      format json
    </pattern>
    <pattern>
      format none
    </pattern>
  </parse>
</filter>

<filter dummy>
  @type parser
  key_name message
  reserve_data true
  remove_key_name_field true
  <parse>
    @type multi_format
    <pattern>
      format json
    </pattern>
    <pattern>
      format none
    </pattern>
  </parse>
</filter>

<match dummy>
  @type stdout
</match>
</code>```

Output:

```<code>2019-06-03 11:41:13.022468253 +0900 dummy: {"stream":"stdout","time":"2019-05-23T15:40:54.298531098Z","message":"HELLO WORLD\n"}
2019-06-03 11:41:14.024253824 +0900 dummy: {"stream":"stdout","time":"2019-05-23T15:40:54.2996761Z","appName":"adapter","level":"info","message":"Awaiting Messages from queue..."}
</code>```

Body:
I'm new to fluentd and I would like to parse a multi-level nested escaped JSON strings inside JSON.

My messages look like:

{"log":"HELLO WORLD\n","stream":"stdout","time":"2019-05-23T15:40:54.298531098Z"}

{"log":"{\"appName\":\"adapter\",\"time\":\"2019-05-23T15:40:54.299\",\"message\":\"{\\\"level\\\":\\\"info\\\",\\\"message\\\":\\\"Awaiting Messages from queue...\\\"}\"}\n","stream":"stdout","time":"2019-05-23T15:40:54.2996761Z"}

The first message get parsed correctly but the second one got ignored and I guess it's because of an error in parsing format

Here is my source:

    <source>
      @id fluentd-containers.log
      @type tail
      path /var/log/containers/*.log
      pos_file /var/log/containers.log.pos
      tag raw.kubernetes.*
      read_from_head true
      <parse>
        @type multi_format
        <pattern>
          format json
          time_key time
          time_format %Y-%m-%dT%H:%M:%S.%NZ
        </pattern>
        <pattern>
          format /^(?<time>.+) (?<stream>stdout|stderr) [^ ]* (?<log>.*)$/
          time_format %Y-%m-%dT%H:%M:%S.%N%:z
        </pattern>
      </parse>
    </source>

Here is what I tried:

    <filter **>
      @type parser
      key_name log
      reserve_data true
      remove_key_name_field true
      hash_value_field parsed_log
      <parse>
        @type json
      </parse>
    </filter>

i actually just want to parse this log message:

{
"log":"{\"appName\":\"dedge-adapter\",\"time\":\"2019-05-24T02:39:12.242\",\"message\":\"{\\\"level\\\":\\\"warn\\\",\\\"status\\\":401,\\\"method\\\":\\\"GET\\\",\\\"path\\\":\\\"/api/v1/bookings\\\",\\\"requestId\\\":\\\"782a470b-9d62-43d3-9865-1b67397717d4\\\",\\\"ip\\\":\\\"90.79.204.18\\\",\\\"latency\\\":0.097897,\\\"user-agent\\\":\\\"PostmanRuntime/7.11.0\\\",\\\"message\\\":\\\"Request\\\"}\"}\n",
"stream":"stdout",
"time":"2019-05-24T02:39:12.242383376Z"
}

Body:
Do you have multiple format log field?
If so, you can use https://github.com/repeatedly/fluent-plugin-multi-format-parser

<source>
  @type dummy
  tag dummy
  dummy [
    {"log":"HELLO WORLD\n","stream":"stdout","time":"2019-05-23T15:40:54.298531098Z"},
    {"log":"{\"appName\":\"adapter\",\"time\":\"2019-05-23T15:40:54.299\",\"message\":\"{\\\"level\\\":\\\"info\\\",\\\"message\\\":\\\"Awaiting Messages from queue...\\\"}\"}\n","stream":"stdout","time":"2019-05-23T15:40:54.2996761Z"}
  ]
</source>

<filter dummy>
  @type parser
  key_name log
  reserve_data true
  remove_key_name_field true
  <parse>
    @type multi_format
    <pattern>
      format json
    </pattern>
    <pattern>
      format none
    </pattern>
  </parse>
</filter>

<filter dummy>
  @type parser
  key_name message
  reserve_data true
  remove_key_name_field true
  <parse>
    @type multi_format
    <pattern>
      format json
    </pattern>
    <pattern>
      format none
    </pattern>
  </parse>
</filter>

<match dummy>
  @type stdout
</match>

Output:

2019-06-03 11:41:13.022468253 +0900 dummy: {"stream":"stdout","time":"2019-05-23T15:40:54.298531098Z","message":"HELLO WORLD\n"}
2019-06-03 11:41:14.024253824 +0900 dummy: {"stream":"stdout","time":"2019-05-23T15:40:54.2996761Z","appName":"adapter","level":"info","message":"Awaiting Messages from queue..."}


问:
How do i set the state from one API call and use the data for URL in next API call?
I need the data from API call 1 to add to the URL of API call 2. The data from API 2 will go into the URL for API 3. I am setting the state on each Axios request and it is not working. Returning undefined</p>

```<code>componentDidMount() {
  // Get the IP adress of user
  axios
    .get('https://api.ipify.org?format=json')
    .then(res => {
      this.setState({
        ip: res.data.ip
      });
      console.log(`IP : ${this.state.ip}`);
    })
    .catch(err => console.log(err));

  // GET the coordinates of a location based on IP adress
  axios
    .get(
      'https://geo.ipify.org/api/v1?apiKey=YOUR_API_KEY&ipAddress=24.8.227.87'
    )
    .then(res => {
      this.setState({
        latitude: res.data.location.lat,
        longitude: res.data.location.lng
      });
      console.log(
        `Latitude: ${this.state.latitude}. Longitude: ${this.state.longitude}`
      );
    })
    .catch(err => console.log(err));

  // Make the API call on page load
  axios({
      method: 'get',
      url: `https://developers.zomato.com/api/v2.1/geocode?lat=39.6924553&lon=-105.0256318`,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Accept: 'application/json',
        'user-key': 'USER_KEY'
      }
    })
    .then(res => {
      const restaurantsNearMe = res.data.nearby_restaurants;

      this.setState({
        restaurants: restaurantsNearMe
      });

      // Pick out a random retaurant from what the API returns
      var randomRestaurant =
        restaurantsNearMe[
          Math.floor(Math.random() * restaurantsNearMe.length)
        ];

      // Select only the data that you want
      var finalResult = {
        name: randomRestaurant.restaurant.name,
        id: randomRestaurant.restaurant.id,
        rating: randomRestaurant.restaurant.user_rating.aggregate_rating,
        ratingColor: randomRestaurant.restaurant.user_rating.rating_color,
        address: randomRestaurant.restaurant.location.address,
        delivery: randomRestaurant.restaurant.is_delivering_now,
        typeOfFood: randomRestaurant.restaurant.cuisines
      };

      this.setState({
        restaurant: finalResult
      });
      console.log(this.state.restaurant);
    })
    .catch(err => console.log(err));
}
</code>```

答:
You need a callback in setState, and in that callback you need to call your second API and so on. Check this.

This is what you want,

```<code>axios
    .get('https://api.ipify.org?format=json')
    .then(res => {
        this.setState({
            ip: res.data.ip
        }, () => {
            // GET the coordinates of a location based on IP adress
            axios
                .get(
                    'https://geo.ipify.org/api/v1?apiKey=YOUR_API_KEY&ipAddress=24.8.227.87'
                )
                .then(res => {
                    this.setState({
                        latitude: res.data.location.lat,
                        longitude: res.data.location.lng
                    }, () => {
                        // Make the API call on page load
                        axios({
                                method: 'get',
                                url: `https://developers.zomato.com/api/v2.1/geocode?lat=39.6924553&lon=-105.0256318`,
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded',
                                    Accept: 'application/json',
                                    'user-key': 'USER_KEY'
                                }
                            })
                            .then(res => {
                                const restaurantsNearMe = res.data.nearby_restaurants;

                                this.setState({
                                    restaurants: restaurantsNearMe
                                });

                                // Pick out a random retaurant from what the API returns
                                var randomRestaurant =
                                    restaurantsNearMe[
                                        Math.floor(Math.random() * restaurantsNearMe.length)
                                    ];

                                // Select only the data that you want
                                var finalResult = {
                                    name: randomRestaurant.restaurant.name,
                                    id: randomRestaurant.restaurant.id,
                                    rating: randomRestaurant.restaurant.user_rating.aggregate_rating,
                                    ratingColor: randomRestaurant.restaurant.user_rating.rating_color,
                                    address: randomRestaurant.restaurant.location.address,
                                    delivery: randomRestaurant.restaurant.is_delivering_now,
                                    typeOfFood: randomRestaurant.restaurant.cuisines
                                };

                                this.setState({
                                    restaurant: finalResult
                                });
                                console.log(this.state.restaurant);
                            })
                            .catch(err => console.log(err));
                    });
                    console.log(
                        `Latitude: ${this.state.latitude}. Longitude: ${this.state.longitude}`
                    );
                })
                .catch(err => console.log(err));

        });
        console.log(`IP : ${this.state.ip}`);
    })
    .catch(err => console.log(err));
</code>```

Body:
I need the data from API call 1 to add to the URL of API call 2. The data from API 2 will go into the URL for API 3. I am setting the state on each Axios request and it is not working. Returning undefined

componentDidMount() {
  // Get the IP adress of user
  axios
    .get('https://api.ipify.org?format=json')
    .then(res => {
      this.setState({
        ip: res.data.ip
      });
      console.log(`IP : ${this.state.ip}`);
    })
    .catch(err => console.log(err));

  // GET the coordinates of a location based on IP adress
  axios
    .get(
      'https://geo.ipify.org/api/v1?apiKey=YOUR_API_KEY&ipAddress=24.8.227.87'
    )
    .then(res => {
      this.setState({
        latitude: res.data.location.lat,
        longitude: res.data.location.lng
      });
      console.log(
        `Latitude: ${this.state.latitude}. Longitude: ${this.state.longitude}`
      );
    })
    .catch(err => console.log(err));

  // Make the API call on page load
  axios({
      method: 'get',
      url: `https://developers.zomato.com/api/v2.1/geocode?lat=39.6924553&lon=-105.0256318`,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Accept: 'application/json',
        'user-key': 'USER_KEY'
      }
    })
    .then(res => {
      const restaurantsNearMe = res.data.nearby_restaurants;

      this.setState({
        restaurants: restaurantsNearMe
      });

      // Pick out a random retaurant from what the API returns
      var randomRestaurant =
        restaurantsNearMe[
          Math.floor(Math.random() * restaurantsNearMe.length)
        ];

      // Select only the data that you want
      var finalResult = {
        name: randomRestaurant.restaurant.name,
        id: randomRestaurant.restaurant.id,
        rating: randomRestaurant.restaurant.user_rating.aggregate_rating,
        ratingColor: randomRestaurant.restaurant.user_rating.rating_color,
        address: randomRestaurant.restaurant.location.address,
        delivery: randomRestaurant.restaurant.is_delivering_now,
        typeOfFood: randomRestaurant.restaurant.cuisines
      };

      this.setState({
        restaurant: finalResult
      });
      console.log(this.state.restaurant);
    })
    .catch(err => console.log(err));
}

Body:
You need a callback in setState, and in that callback you need to call your second API and so on. Check this.

This is what you want,

axios
    .get('https://api.ipify.org?format=json')
    .then(res => {
        this.setState({
            ip: res.data.ip
        }, () => {
            // GET the coordinates of a location based on IP adress
            axios
                .get(
                    'https://geo.ipify.org/api/v1?apiKey=YOUR_API_KEY&ipAddress=24.8.227.87'
                )
                .then(res => {
                    this.setState({
                        latitude: res.data.location.lat,
                        longitude: res.data.location.lng
                    }, () => {
                        // Make the API call on page load
                        axios({
                                method: 'get',
                                url: `https://developers.zomato.com/api/v2.1/geocode?lat=39.6924553&lon=-105.0256318`,
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded',
                                    Accept: 'application/json',
                                    'user-key': 'USER_KEY'
                                }
                            })
                            .then(res => {
                                const restaurantsNearMe = res.data.nearby_restaurants;

                                this.setState({
                                    restaurants: restaurantsNearMe
                                });

                                // Pick out a random retaurant from what the API returns
                                var randomRestaurant =
                                    restaurantsNearMe[
                                        Math.floor(Math.random() * restaurantsNearMe.length)
                                    ];

                                // Select only the data that you want
                                var finalResult = {
                                    name: randomRestaurant.restaurant.name,
                                    id: randomRestaurant.restaurant.id,
                                    rating: randomRestaurant.restaurant.user_rating.aggregate_rating,
                                    ratingColor: randomRestaurant.restaurant.user_rating.rating_color,
                                    address: randomRestaurant.restaurant.location.address,
                                    delivery: randomRestaurant.restaurant.is_delivering_now,
                                    typeOfFood: randomRestaurant.restaurant.cuisines
                                };

                                this.setState({
                                    restaurant: finalResult
                                });
                                console.log(this.state.restaurant);
                            })
                            .catch(err => console.log(err));
                    });
                    console.log(
                        `Latitude: ${this.state.latitude}. Longitude: ${this.state.longitude}`
                    );
                })
                .catch(err => console.log(err));

        });
        console.log(`IP : ${this.state.ip}`);
    })
    .catch(err => console.log(err));


问:
mongoose populate after another populate
I have 3 mongo collections.

resource

access

user

the user has a relationship with access and access has a relationship with resource. I want when populate a user all join be done and I see the full resource that user has access them.

I tried this code but was n't expected response

```<code>     Users.findById(req.params.userId)
     .populate({path:'accessID',model:'accesses'})
     .populate({path:'accessID.accessLists',model:'resources'})
</code>```

and this

```<code> Users.findById(req.params.userId)
     .populate({path:'accessID',model:'accesses'})
     .then
(
        (user)=>
        {
         Users.populate(user,{path})
        }
)

</code>```

here is my defections

Resource:

```<code>  var ResourceSchema =new Schema
       ({
        resource:String
        method:
        {   type:String,
            enum:["GET","PUT","POST","DELETE"]
        }
       })
</code>```

Access:

```<code>     var AccessSchema =new Schema
     ({
      name:String
      access_List:
     [
       { type: Schema.Types.ObjectId,  ref:'resources'}
     ]

    })
</code>```

User:

```<code>     var  UserSchema = new Schema
      ({
       name:String,
       email:String,
       accessID:
       { type: Schema.Types.ObjectId, required: true, ref: 'accesses' }
      )}
</code>```

my output like this

```<code>{"accessID":
 {
   "_id": "5cef82d1d2f7e14d3013ac8c",
           "accessLists":
                [
               "5cee8e093defe92b88c1626b",
               "5cee8e093defe92b88c1626c",
               "5cee8e093defe92b88c1626d",
                 ],
           "name": "Admin",
   },
"name": "ali"
"email": "ali17@yahoo.com"
      }
</code>```

but I want my output like this:

```<code> {
  "name": "ali",
   "email": "ali17@yahoo.com"
   "accessID":
    {
       "_id": "5cef82d1d2f7e14d3013ac8c",
         "accessLists":
       [
           {
                "_id": "5cee8e093defe92b88c1626b",
                "resource": "groups",
                "method": "POST",
            },
            {
                "_id": "5cee8e093defe92b88c1626c",
                "resource": "groups",
                "method": "DELETE",
            },
            {
                "_id": "5cee8e093defe92b88c1626d",
                "resource": "groups",
                "method": "GET",
            }
       ]
            "name": "Admin",
          }

         }
</code>```

答:
```<code>    User.findById(req.params.userId)
        .populate({path:'accessID',model:'accesses'})
        .populate({ path: 'accessID', populate: { path: 'access_List',model:'resources' }})
        .exec(function (err, response) {
     })
</code>```

I have tried and its working.
More Help: Example

also, I have tried with aggregation :

```<code>db.users.aggregate([
   {$match : { _id : ObjectId("5cf00388eae5400e9439b2df")}},
   {
        $lookup: {
            from:"access",
            localField:"accessID",
            foreignField: "_id",
            as:"accessID"
        }
    },
    { "$unwind": '$accessID'},
    { "$unwind": '$accessID.access_List'},
    {
        $lookup: {
            from:"resources",
            localField:"accessID.access_List",
            foreignField: "_id",
            as:"access_List"
        }
    },
    {
        $group : {
            _id : {
                "_id" : '$_id', "name" : '$name', "email" : '$email',
                 "accessID" : {"_id" : '$accessID._id', "name": '$accessID.name' }
            },
            access_List : { $push : { "$arrayElemAt": [ "$access_List", 0 ] } }
        }
    },
    { $project : {
          _id : '$_id._id',
          name : '$_id.name',
          email : '$_id.email',
          accessID : {
              _id : '$_id.accessID._id',
              name:  '$_id.accessID.name',
              access_List : '$access_List'
          }

       }
    }
    ]).pretty()
</code>```

Body:
I have 3 mongo collections.

resource

access

user

the user has a relationship with access and access has a relationship with resource. I want when populate a user all join be done and I see the full resource that user has access them.

I tried this code but was n't expected response

     Users.findById(req.params.userId)
     .populate({path:'accessID',model:'accesses'})
     .populate({path:'accessID.accessLists',model:'resources'})

and this

 Users.findById(req.params.userId)
     .populate({path:'accessID',model:'accesses'})
     .then
(
        (user)=>
        {
         Users.populate(user,{path})
        }
)

here is my defections

Resource:

  var ResourceSchema =new Schema
       ({
        resource:String
        method:
        {   type:String,
            enum:["GET","PUT","POST","DELETE"]
        }
       })

Access:

     var AccessSchema =new Schema
     ({
      name:String
      access_List:
     [
       { type: Schema.Types.ObjectId,  ref:'resources'}
     ]

    })

User:

     var  UserSchema = new Schema
      ({
       name:String,
       email:String,
       accessID:
       { type: Schema.Types.ObjectId, required: true, ref: 'accesses' }
      )}

my output like this

{"accessID":
 {
   "_id": "5cef82d1d2f7e14d3013ac8c",
           "accessLists":
                [
               "5cee8e093defe92b88c1626b",
               "5cee8e093defe92b88c1626c",
               "5cee8e093defe92b88c1626d",
                 ],
           "name": "Admin",
   },
"name": "ali"
"email": "ali17@yahoo.com"
      }

but I want my output like this:

 {
  "name": "ali",
   "email": "ali17@yahoo.com"
   "accessID":
    {
       "_id": "5cef82d1d2f7e14d3013ac8c",
         "accessLists":
       [
           {
                "_id": "5cee8e093defe92b88c1626b",
                "resource": "groups",
                "method": "POST",
            },
            {
                "_id": "5cee8e093defe92b88c1626c",
                "resource": "groups",
                "method": "DELETE",
            },
            {
                "_id": "5cee8e093defe92b88c1626d",
                "resource": "groups",
                "method": "GET",
            }
       ]
            "name": "Admin",
          }

         }

Body:
    User.findById(req.params.userId)
        .populate({path:'accessID',model:'accesses'})
        .populate({ path: 'accessID', populate: { path: 'access_List',model:'resources' }})
        .exec(function (err, response) {
     })

I have tried and its working.
More Help: Example

also, I have tried with aggregation :

db.users.aggregate([
   {$match : { _id : ObjectId("5cf00388eae5400e9439b2df")}},
   {
        $lookup: {
            from:"access",
            localField:"accessID",
            foreignField: "_id",
            as:"accessID"
        }
    },
    { "$unwind": '$accessID'},
    { "$unwind": '$accessID.access_List'},
    {
        $lookup: {
            from:"resources",
            localField:"accessID.access_List",
            foreignField: "_id",
            as:"access_List"
        }
    },
    {
        $group : {
            _id : {
                "_id" : '$_id', "name" : '$name', "email" : '$email',
                 "accessID" : {"_id" : '$accessID._id', "name": '$accessID.name' }
            },
            access_List : { $push : { "$arrayElemAt": [ "$access_List", 0 ] } }
        }
    },
    { $project : {
          _id : '$_id._id',
          name : '$_id.name',
          email : '$_id.email',
          accessID : {
              _id : '$_id.accessID._id',
              name:  '$_id.accessID.name',
              access_List : '$access_List'
          }

       }
    }
    ]).pretty()


问:
Running Xcode 10 I get Codesigning error when building for my iPhone
So I am a Primary Teacher with no coding experience but I would like to develop a simple app to help teach phonics in my class.

However, I  have been trying to get builds to run on my device (iPhone 6s plus iOS 12.2). The simple app I made up said build succeeded on simulator but not the device. :< I can't fix that :<

```
Copy Swift standard libraries into /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app

Showing All Messages
CopySwiftLibs /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app (in target: GonativeIO)
    cd /Users/macbook/Desktop/ios\ 2
    export CODESIGN_ALLOCATE=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate
    export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
    export SDKROOT=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk
    builtin-swiftStdLibTool --copy --verbose --sign 83FA19DF98CE2F83DBD4CABB58C1ADEE9F9E52CA --scan-executable /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/GonativeIO --scan-folder /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks --scan-folder /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/PlugIns --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/Social.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/Accounts.framework --scan-folder /Users/macbook/Desktop/ios\ 2/FBSDKShareKit.framework --scan-folder /Users/macbook/Desktop/ios\ 2/Bolts.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/SystemConfiguration.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/Security.framework --scan-folder /Users/macbook/Desktop/ios\ 2/FBSDKLoginKit.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/QuartzCore.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/CoreLocation.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/CFNetwork.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/AudioToolbox.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/MessageUI.framework --scan-folder /Users/macbook/Desktop/ios\ 2/FBSDKCoreKit.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/CoreText.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/MediaAccessibility.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/CoreGraphics.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/UIKit.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/Foundation.framework --scan-folder /Users/macbook/Desktop/ios\ 2/OneSignal.framework --platform iphoneos --toolchain /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain --destination /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks --strip-bitcode --resource-destination /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app --resource-library libswiftRemoteMirror.dylib --strip-bitcode-tool /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/bitcode_strip --emit-dependency-info /Users/macbook/Desktop/Build/Intermediates.noindex/GoNativeIOS.build/Debug-iphoneos/GonativeIO.build/SwiftStdLibToolInputDependencies.dep

Requested Swift ABI version based on scanned binaries: unstable(7)
libswiftos.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftos.dylib
libswiftDarwin.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftDarwin.dylib
libswiftCoreGraphics.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftCoreGraphics.dylib
libswiftObjectiveC.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftObjectiveC.dylib
libswiftUIKit.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftUIKit.dylib
libswiftMetal.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftMetal.dylib
libswiftSwiftOnoneSupport.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftSwiftOnoneSupport.dylib
libswiftFoundation.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftFoundation.dylib
libswiftDispatch.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftDispatch.dylib
libswiftCoreFoundation.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftCoreFoundation.dylib
libswiftCore.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftCore.dylib
libswiftCoreImage.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftCoreImage.dylib
libswiftQuartzCore.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftQuartzCore.dylib
libswiftRemoteMirror.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/libswiftRemoteMirror.dylib
Probing signature of /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftos.dylib
/usr/bin/codesign -r- --display /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftos.dylib
/Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftos.dylib: code object is not signed at all

Codesigning /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftos.dylib
/usr/bin/codesign --force --sign 83FA19DF98CE2F83DBD4CABB58C1ADEE9F9E52CA --verbose /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftos.dylib
/Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftos.dylib: errSecInternalComponent

error: Failed with exit code 1
```

答:
running on simulator doesn't require code signing so you were able to run your app on that. Running on a device needs certificates. As suggested in the comment, kindly go through the steps enumerated in the following link:
https://help.apple.com/xcode/mac/current/#/dev60b6fbbc7</p>

Body:
So I am a Primary Teacher with no coding experience but I would like to develop a simple app to help teach phonics in my class.

However, I  have been trying to get builds to run on my device (iPhone 6s plus iOS 12.2). The simple app I made up said build succeeded on simulator but not the device. :< I can't fix that :<

Copy Swift standard libraries into /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app

Showing All Messages
CopySwiftLibs /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app (in target: GonativeIO)
    cd /Users/macbook/Desktop/ios\ 2
    export CODESIGN_ALLOCATE=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate
    export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
    export SDKROOT=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk
    builtin-swiftStdLibTool --copy --verbose --sign 83FA19DF98CE2F83DBD4CABB58C1ADEE9F9E52CA --scan-executable /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/GonativeIO --scan-folder /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks --scan-folder /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/PlugIns --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/Social.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/Accounts.framework --scan-folder /Users/macbook/Desktop/ios\ 2/FBSDKShareKit.framework --scan-folder /Users/macbook/Desktop/ios\ 2/Bolts.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/SystemConfiguration.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/Security.framework --scan-folder /Users/macbook/Desktop/ios\ 2/FBSDKLoginKit.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/QuartzCore.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/CoreLocation.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/CFNetwork.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/AudioToolbox.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/MessageUI.framework --scan-folder /Users/macbook/Desktop/ios\ 2/FBSDKCoreKit.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/CoreText.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/MediaAccessibility.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/CoreGraphics.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/UIKit.framework --scan-folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/Foundation.framework --scan-folder /Users/macbook/Desktop/ios\ 2/OneSignal.framework --platform iphoneos --toolchain /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain --destination /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks --strip-bitcode --resource-destination /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app --resource-library libswiftRemoteMirror.dylib --strip-bitcode-tool /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/bitcode_strip --emit-dependency-info /Users/macbook/Desktop/Build/Intermediates.noindex/GoNativeIOS.build/Debug-iphoneos/GonativeIO.build/SwiftStdLibToolInputDependencies.dep

Requested Swift ABI version based on scanned binaries: unstable(7)
libswiftos.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftos.dylib
libswiftDarwin.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftDarwin.dylib
libswiftCoreGraphics.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftCoreGraphics.dylib
libswiftObjectiveC.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftObjectiveC.dylib
libswiftUIKit.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftUIKit.dylib
libswiftMetal.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftMetal.dylib
libswiftSwiftOnoneSupport.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftSwiftOnoneSupport.dylib
libswiftFoundation.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftFoundation.dylib
libswiftDispatch.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftDispatch.dylib
libswiftCoreFoundation.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftCoreFoundation.dylib
libswiftCore.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftCore.dylib
libswiftCoreImage.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftCoreImage.dylib
libswiftQuartzCore.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftQuartzCore.dylib
libswiftRemoteMirror.dylib is up to date at /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/libswiftRemoteMirror.dylib
Probing signature of /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftos.dylib
/usr/bin/codesign -r- --display /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftos.dylib
/Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftos.dylib: code object is not signed at all

Codesigning /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftos.dylib
/usr/bin/codesign --force --sign 83FA19DF98CE2F83DBD4CABB58C1ADEE9F9E52CA --verbose /Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftos.dylib
/Users/macbook/Desktop/Build/Products/Debug-iphoneos/GonativeIO.app/Frameworks/libswiftos.dylib: errSecInternalComponent

error: Failed with exit code 1


答:
The issue you're facing is because IndexOf matches a single character, or sequence of characters (a search string) within the greater string. Therefore "I am your friend" contains the sequence "you". To match words only, you have to consider things at a word level.

For example, you could use Regular Expressions' to match around the word boundaries:

```<code>private static int IndexOfWord(string val, int startAt, string search)
{
    // escape the match expression in case it contains any characters meaningful
    // to regular expressions, and then create an expression with the \b boundary
    // characters
    var escapedMatch = string.Format(@"\b{0}\b", Regex.Escape(search));

    // create a case-sensitive regular expression object using the pattern
    var exp = new Regex(escapedMatch, RegexOptions.IgnoreCase);

    // perform the match from the start position
    var match = exp.Match(val, startAt);

    // if it's successful, return the match index
    if (match.Success)
    {
        return match.Index;
    }

    // if it's unsuccessful, return -1
    return -1;
}

// overload without startAt, for when you just want to start from the beginning
private static int IndexOfWord(string val, string search)
{
    return IndexOfWord(val, 0, search);
}
</code>```

In your example you would try to match \byou\b, which because of the boundary requirements won't match your.

Try it online

See more about word boundaries in Regular Expressions here.

Title: String.IndexOf() returns unexpected index of string

Body:
The issue you're facing is because IndexOf matches a single character, or sequence of characters (a search string) within the greater string. Therefore "I am your friend" contains the sequence "you". To match words only, you have to consider things at a word level.

For example, you could use Regular Expressions' to match around the word boundaries:

private static int IndexOfWord(string val, int startAt, string search)
{
    // escape the match expression in case it contains any characters meaningful
    // to regular expressions, and then create an expression with the \b boundary
    // characters
    var escapedMatch = string.Format(@"\b{0}\b", Regex.Escape(search));

    // create a case-sensitive regular expression object using the pattern
    var exp = new Regex(escapedMatch, RegexOptions.IgnoreCase);

    // perform the match from the start position
    var match = exp.Match(val, startAt);

    // if it's successful, return the match index
    if (match.Success)
    {
        return match.Index;
    }

    // if it's unsuccessful, return -1
    return -1;
}

// overload without startAt, for when you just want to start from the beginning
private static int IndexOfWord(string val, string search)
{
    return IndexOfWord(val, 0, search);
}

In your example you would try to match \byou\b, which because of the boundary requirements won't match your.

Try it online

See more about word boundaries in Regular Expressions here.


问:
.NET CORE API: Is it possible to conditionally validate a model depending on the http verb used to submit it?

I'm very new to the FluentValidation and I'd like to validate my model in different ways depending on which verb was used to submit it.

Given a very simple class, I'd like to ignore the ID property on a POST but ensure it's been provided on a PUT. Is this something the FluentValidation can do?

 public class CategoryModel
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}
```

I'm guessing I have to get the HttpContext over to the validators so I can determine the http method used, but I don't want to re-invent the wheel if there's already a built-in way.

Thanks!!

答:
I think I've come up with a solution by passing the context to my validator. However, if something looks wrong or out of place, please let me know.

public class CategoryModel
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }

public class CategoryModelValidator : AbstractValidator<CategoryModel>
    {
        public CategoryModelValidator(IHttpContextAccessor context)
        {
            if (context.HttpContext.Request.Method == HttpMethods.Post)
                RuleFor(x => x.ID).Empty();

            if (context.HttpContext.Request.Method == HttpMethods.Put)
                RuleFor(x => x.ID).NotEmpty();

            RuleFor(x => x.Name).Length(1, 30);
        }
    }
```

Passing the context was easier than I thought. All I had to do was register it in my ConfigureServices method with services.AddHttpContextAccessor() and DI takes care of the rest.

To be honest, this is a pretty handy validation tool

Body:
I'm very new to the FluentValidation and I'd like to validate my model in different ways depending on which verb was used to submit it.

Given a very simple class, I'd like to ignore the ID property on a POST but ensure it's been provided on a PUT. Is this something the FluentValidation can do?

 public class CategoryModel
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

I'm guessing I have to get the HttpContext over to the validators so I can determine the http method used, but I don't want to re-invent the wheel if there's already a built-in way.

Thanks!!

Body:
I think I've come up with a solution by passing the context to my validator. However, if something looks wrong or out of place, please let me know.

public class CategoryModel
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }

public class CategoryModelValidator : AbstractValidator<CategoryModel>
    {
        public CategoryModelValidator(IHttpContextAccessor context)
        {
            if (context.HttpContext.Request.Method == HttpMethods.Post)
                RuleFor(x => x.ID).Empty();

            if (context.HttpContext.Request.Method == HttpMethods.Put)
                RuleFor(x => x.ID).NotEmpty();

            RuleFor(x => x.Name).Length(1, 30);
        }
    }

Passing the context was easier than I thought. All I had to do was register it in my ConfigureServices method with services.AddHttpContextAccessor() and DI takes care of the rest.

To be honest, this is a pretty handy validation tool


答:
Please use this code I hope it's helpful for you.</p>

```<code> <link id="pagestyle" rel="stylesheet" type="text/css" href="main.css">
<script>
  function swapStyleSheet(sheet) {
    if($(sheet).prop("checked") == true){
       document.getElementById('pagestyle').setAttribute('href', 'main2.css');
    }else{
        document.getElementById('pagestyle').setAttribute('href', 'main.css');
    }

  }
</script>

<!-- Rectangular switch -->
<label class="switch">
  <input type="checkbox" onchange="swapStyleSheet(this)">
    <span class="slider"></span>
</label>
</code>```

Title: How to change BACK with onchange with a switch in HTML

Body:
I am writing a website, and want to create a dark/light mode. I have a switch that switches when clicked, and it successfully changes to my second css stylesheet. How should I go about switching BACK to the original stylesheet?

HTML-

<link id="pagestyle" rel="stylesheet" type="text/css" href="assets/css/main.css">

  <input type="checkbox" onchange="swapStyleSheet()"">

Using this switch style

Body:
Please use this code I hope it's helpful for you.

 <link id="pagestyle" rel="stylesheet" type="text/css" href="main.css">
<script>
  function swapStyleSheet(sheet) {
    if($(sheet).prop("checked") == true){
       document.getElementById('pagestyle').setAttribute('href', 'main2.css');
    }else{
        document.getElementById('pagestyle').setAttribute('href', 'main.css');
    }

  }
</script>

<!-- Rectangular switch -->
<label class="switch">
  <input type="checkbox" onchange="swapStyleSheet(this)">
    <span class="slider"></span>
</label>


问:
How do I perform a simple one-statement SQL search across tables?
Suppose that two tables exist: users and groups.

How does one provide "simple search" in which a user enters text and results contain both users and groups whose names contain the text?

The result of the search must distinguish between the two types.

答:
Using LIKE will cause a number of problems as it will require a table scan every single time when the LIKE comparator starts with a %. This forces SQL to check every single row and work it's way, byte by byte, through the string you are using for comparison. While this may be fine when you start, it quickly causes scaling issues.

A better way to handle this is using Full Text Search. While this would be a more complex option, it will provide you with better results for very large databases. Then you can use a functioning version of the example Bobby Jack gave you to UNION ALL your two result sets together and display the results.

OwnerDisplayName: Bobby Jack

OwnerDisplayName: Josef

ContentLicense: CC BY-SA 2.5


问:
I want format phone number column while selecting from oracle
I am trying to add +1 while trying to get data from a phone number column. example data(1234567890)</p>

```<code>select phone_number from table1;

result
1234567880

desired result
+11234567880
</code>```

答:
If your original data has fixed length 10, then you might consider using lpad with padded_length is 12 and pad_string is +1:

select lpad(phone_number,12,'+1') from table1

Body:
I am trying to add +1 while trying to get data from a phone number column. example data(1234567890)

select phone_number from table1;

result
1234567880

desired result
+11234567880


问:
Commit changes from gitignore
On my branch under changes tracked there appears to be a .gitignore file with two changes that are now in there. How do I dissolve this file and put it with all other changes</p>

答: Solution is to stash the .gitignore file which will display the changes in file status</p>

Title: Commit changes from gitignore


问:
How to interrupt Console.ReadLine
Is it possible to stop the Console.ReadLine() programmatically?

I have a console application: the much of the logic runs on a different thread and in the main thread I accept input using Console.ReadLine(). I'd like to stop reading from console when the separated thread stop running.

How can I achieve this?

答:
This will process a Ctrl+C in a seperate thread while your app is waiting for a Console.Readline():</p>

```<code>Console.CancelKeyPress += (_, e) =>
{
    e.Cancel = true;
    Environment.Exit(0);
};
</code>```

Title: How to interrupt Console.ReadLine

Body:
This will process a Ctrl+C in a seperate thread while your app is waiting for a Console.Readline():

Console.CancelKeyPress += (_, e) =>
{
    e.Cancel = true;
    Environment.Exit(0);
};


问:
How to create unique constraints on AgensGraph
I want to use "id" property as primary key on label.

```<code>agens=# create vlabel v;
CREATE VLABEL
agens=# create (:v{id:1});
GRAPH WRITE (INSERT VERTEX 1, INSERT EDGE 0)
agens=# create (:v{id:1});
GRAPH WRITE (INSERT VERTEX 1, INSERT EDGE 0)
</code>```

But, I don't know grammar for create constraint.

How to create unique constraints on AgensGraph.

答:
Use unique property index on AgensGraph.</p>

```<code>agens=# create (:v{id:1});
GRAPH WRITE (INSERT VERTEX 1, INSERT EDGE 0)
agens=# create unique property index on v(id);
CREATE PROPERTY INDEX
agens=# create (:v{id:1});
ERROR:  duplicate key value violates unique constraint "v_id_idx"
DETAIL:  Key ((properties.'id'::text))=(1) already exists.
</code>```

Body:
I want to use "id" property as primary key on label.

agens=# create vlabel v;
CREATE VLABEL
agens=# create (:v{id:1});
GRAPH WRITE (INSERT VERTEX 1, INSERT EDGE 0)
agens=# create (:v{id:1});
GRAPH WRITE (INSERT VERTEX 1, INSERT EDGE 0)

But, I don't know grammar for create constraint.

How to create unique constraints on AgensGraph.

Body:
Use unique property index on AgensGraph.

agens=# create (:v{id:1});
GRAPH WRITE (INSERT VERTEX 1, INSERT EDGE 0)
agens=# create unique property index on v(id);
CREATE PROPERTY INDEX
agens=# create (:v{id:1});
ERROR:  duplicate key value violates unique constraint "v_id_idx"
DETAIL:  Key ((properties.'id'::text))=(1) already exists.


问:
I need corresponding values to appear automatically in Google Sheets
I have 2 Google Sheets. Now in excel 1 The name column in sheet 1 is A and the address column in Sheet 1 is B. Now I have another sheet which already has these data, name and addresses etc. Now, what I want to do is when I write the name(A) in sheet 1, I want the column B(address) in the same sheet to automatically lookup the sheet 2 for the corresponding address to name (A) and show the address in that cell.

Please help.

答:
this is what you need: =ARRAYFORMULA(IF(LEN(A2:A); VLOOKUP(A2:A; 'Tab B'!A2:B; 2; 0); ))

which means that IF ID from Tab B is found in Tab A, formula will return 2 (second) column from range A:B of Tab B in sorted order based on IDs in A column of Tab A - hence that 0

here is demo spreadsheet: https://docs.google.com/spreadsheets/d/


问:
Send parameter value via React routing
I'm trying to use Link from react-router-dom to send a parameter to another page.

I have this path:

```<code><Route path={"/IDSM/IDSMAdmin/EditUser/:username"} component={EditUser}/>
</code>```

Here's the link that gets there:

```<code><Link to={"/IDSM/IDSMAdmin/EditUser/${item}"}>{item}</Link>
</code>```

But that doesn't send the value of {item} to the other page. Instead it just sends the literal value "${item}".

```<code>{ username: "${{item}}" }
</code>```

How can I send the contents of {item} itself?

答:
Use back-tick character instead of double quotes to send the params</p>

```<code><Link to={`/IDSM/IDSMAdmin/EditUser/${item}`}>text here</Link>
</code>```

Title: Send parameter value via React routing

Body:
I'm trying to use Link from react-router-dom to send a parameter to another page.

I have this path:

<Route path={"/IDSM/IDSMAdmin/EditUser/:username"} component={EditUser}/>

Here's the link that gets there:

<Link to={"/IDSM/IDSMAdmin/EditUser/${item}"}>{item}</Link>

But that doesn't send the value of {item} to the other page. Instead it just sends the literal value "${item}".

{ username: "${{item}}" }

How can I send the contents of {item} itself?

Body:
Use back-tick character instead of double quotes to send the params

<Link to={`/IDSM/IDSMAdmin/EditUser/${item}`}>text here</Link>


问:
Change class for last two rows in a while loop
I have a while loop that displays result from a MySQL query. I know how to change the output for the last row or an odd row but how can I change the output for the last two results?

For example I have a list of results in a 2x2 matrix with border-bottom: 1px on each result but I would like to display the bottom two without the border?

答:
Yeah just do it like this:

```<code>$result = //execute your query
$num_rows = mysql_num_rows($result;
$num_rows_different = 2;

$loop_counter = 0;
while ($loop_counter < $num_rows) {
   if ($loop_counter < $num_rows - $num_rows_different) {
      // with border
   } else {
      // no border
   }
   $loop_counter++;
}
</code>```

I wouldn't use the CSS3 method due to its poor support...

Body:
Yeah just do it like this:

$result = //execute your query
$num_rows = mysql_num_rows($result;
$num_rows_different = 2;

$loop_counter = 0;
while ($loop_counter < $num_rows) {
   if ($loop_counter < $num_rows - $num_rows_different) {
      // with border
   } else {
      // no border
   }
   $loop_counter++;
}

I wouldn't use the CSS3 method due to its poor support...


问:
Name node fails after restarting the hadoop HA cluster nodes after power off
I have setup HA hadoop cluster with 2 name nodes and journal nodes with automatic fail-over control . it starts fines when starting after namenode format. But it fails when restarting the cluster. I also tried to up the cluster in the order.

start all journal nodes

start active name node

start standby node (using bootstrap)and start name node

start zkserver on all nodes

start all data nodes.

format zkfc on active node ,then start

format zkfc on standby node ,then start.

it works fine until stage 5 and all nodes are up(both name nodes are up and standby).When i started zkfc , name node fails and getting an error journal node not formated.

(before this step , i started the setup with successfully by formatting the active name node, in the second time i start , i removed name node format in step 2):

how do i starting the setup after shutdown and restart?

```<code><configuration>
<property>
<name>dfs.namenode.name.dir</name>
<value>file:///usr/local/hadoop/data/nameNode</value>
<final>true</final>
</property>

<property>
<name>dfs.datanode.data.dir</name>
<value>file:///usr/local/hadoop/data/dataNode</value>
<final>true</final>
</property>

<property>
<name>dfs.replication</name>
<value>2</value>
</property>

<property>
<name>dfs.permissions</name>
<value>false</value>
</property>

<property>
<name>dfs.nameservices</name>
<value>ha_cluster</value>
</property>

<property>
 <name>dfs.ha.namenodes.ha_cluster</name>
 <value>sajan,sajan2</value>
 </property>

 <property>
 <name>dfs.namenode.rpc-address.ha_cluster.sajan</name>
 <value>192.168.5.249:9000</value>
 </property>

 <property>
 <name>dfs.namenode.rpc-address.ha_cluster.sajan2</name>
 <value>192.168.5.248:9000</value>
 </property>

 <property>
 <name>dfs.namenode.http-address.ha_cluster.sajan</name>
 <value>192.168.5.249:50070</value>
 </property>

 <property>
 <name>dfs.namenode.http-address.ha_cluster.sajan2</name>
 <value>192.168.5.248:50070</value>
 </property>

 <property>
 <name>dfs.namenode.shared.edits.dir</name>
 <value>qjournal://192.168.5.249:8485;192.168.5.248:8485;192.168.5.250:8485/ha_cluster</value>
 </property>
 <property>
 <name>dfs.client.failover.proxy.provider.ha_cluster</name>
 <value>org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider</value>
 </property>
 <property>
 <name>dfs.ha.automatic-failover.enabled</name>
 <value>true</value>
 </property>
 <property>
 <name>ha.zookeeper.quorum</name>
 <value>192.168.5.249:2181,192.168.5.248:2181,192.168.5.250:2181,192.168.5.251:2181,192.168.5.252:2181,192.168.5.253:2181</value>
 </property>
 <property>
 <name>dfs.ha.fencing.methods</name>
 <value>sshfence</value>
 </property>
 <property>
 <name>dfs.ha.fencing.ssh.private-key-files</name>
 <value>/home/hadoop/.ssh/id_rsa</value>
 </property>

</configuration>
</code>```

答:
If you want to stop the service use the below order. I lost my 2 working days to figure this out.

stop all name nodes.

stop-all journal nodes.

stop-all data nodes.

stop fail over service.

stop zkserver

Body:
I have setup HA hadoop cluster with 2 name nodes and journal nodes with automatic fail-over control . it starts fines when starting after namenode format. But it fails when restarting the cluster. I also tried to up the cluster in the order.

start all journal nodes

start active name node

start standby node (using bootstrap)and start name node

start zkserver on all nodes

start all data nodes.

format zkfc on active node ,then start

format zkfc on standby node ,then start.

it works fine until stage 5 and all nodes are up(both name nodes are up and standby).When i started zkfc , name node fails and getting an error journal node not formated.

(before this step , i started the setup with successfully by formatting the active name node, in the second time i start , i removed name node format in step 2):

how do i starting the setup after shutdown and restart?

<configuration>
<property>
<name>dfs.namenode.name.dir</name>
<value>file:///usr/local/hadoop/data/nameNode</value>
<final>true</final>
</property>

<property>
<name>dfs.datanode.data.dir</name>
<value>file:///usr/local/hadoop/data/dataNode</value>
<final>true</final>
</property>

<property>
<name>dfs.replication</name>
<value>2</value>
</property>

<property>
<name>dfs.permissions</name>
<value>false</value>
</property>

<property>
<name>dfs.nameservices</name>
<value>ha_cluster</value>
</property>

<property>
 <name>dfs.ha.namenodes.ha_cluster</name>
 <value>sajan,sajan2</value>
 </property>

 <property>
 <name>dfs.namenode.rpc-address.ha_cluster.sajan</name>
 <value>192.168.5.249:9000</value>
 </property>

 <property>
 <name>dfs.namenode.rpc-address.ha_cluster.sajan2</name>
 <value>192.168.5.248:9000</value>
 </property>

 <property>
 <name>dfs.namenode.http-address.ha_cluster.sajan</name>
 <value>192.168.5.249:50070</value>
 </property>

 <property>
 <name>dfs.namenode.http-address.ha_cluster.sajan2</name>
 <value>192.168.5.248:50070</value>
 </property>

 <property>
 <name>dfs.namenode.shared.edits.dir</name>
 <value>qjournal://192.168.5.249:8485;192.168.5.248:8485;192.168.5.250:8485/ha_cluster</value>
 </property>
 <property>
 <name>dfs.client.failover.proxy.provider.ha_cluster</name>
 <value>org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider</value>
 </property>
 <property>
 <name>dfs.ha.automatic-failover.enabled</name>
 <value>true</value>
 </property>
 <property>
 <name>ha.zookeeper.quorum</name>
 <value>192.168.5.249:2181,192.168.5.248:2181,192.168.5.250:2181,192.168.5.251:2181,192.168.5.252:2181,192.168.5.253:2181</value>
 </property>
 <property>
 <name>dfs.ha.fencing.methods</name>
 <value>sshfence</value>
 </property>
 <property>
 <name>dfs.ha.fencing.ssh.private-key-files</name>
 <value>/home/hadoop/.ssh/id_rsa</value>
 </property>

</configuration>


问:
"TypeError: data.map is not a function" on accessing newsapi using nextjs/react
I am trying to access newsapi using nextjs/react but "TypeError: data.map is not a function".

I have tried the following some solutions provided on stackoverflow but did not work for my case.

Here is my code:

```<code>import Layout from '../components/MyLayout.js'
import Link from 'next/link'
import fetch from 'isomorphic-unfetch'

const Index = (props) => (
  <Layout>
    <h1>Batman TV sources</h1>
    <ul>
      {props.sources.map(source => (
        <li key={source.id}>
          <Link as={`/p/${source.id}`} href={`/post?id=${source.id}`}>
            <a>{source.name}</a>
          </Link>
        </li>
      ))}
    </ul>
  </Layout>
)

Index.getInitialProps = async function() {
  const res = await fetch('https://api.tvmaze.com/search/sources?q=batman')
  //const res = await fetch('https://randomuser.me/api/?results=10')
  //const res = await fetch ('https://newsapi.org/v2/top-headlines?country=us')
  const data = await res.json()

  //console.log(`source data fetched. Count: ${data.length}`)

  return {
    sources: data.map(entry => entry.source)
  }
}

export default Index
</code>```

and here SHORTED api data looks like:
{"status":"ok","totalResults":38,"articles":[{"source":{"id":"fox-news","name":"Fox News"},"author":"Frank Miles","title":....}]}

I know this is an object but not an array and map() is not valid for object. But how can I get around this based on my code above?

The expected result should be new headlines be displayed but always got "TypeError: data.map is not a function". I tried the solutions suggested here but did not work. I am kind of new to this.

答:
Since your data is an Object you can't use map on it as Object don't have map method, you're trying to map source property which is inside articles array

change this

```<code>data.map(entry => entry.source)
</code>```

to this

```<code>data.articles.map(entry => entry.source)
</code>```

Body:
I am trying to access newsapi using nextjs/react but "TypeError: data.map is not a function".

I have tried the following some solutions provided on stackoverflow but did not work for my case.

Here is my code:

import Layout from '../components/MyLayout.js'
import Link from 'next/link'
import fetch from 'isomorphic-unfetch'

const Index = (props) => (
  <Layout>

Batman TV sources

      {props.sources.map(source => (

          <Link as={`/p/${source.id}`} href={`/post?id=${source.id}`}>
            {source.name}
          </Link>

      ))}

  </Layout>
)

Index.getInitialProps = async function() {
  const res = await fetch('https://api.tvmaze.com/search/sources?q=batman')
  //const res = await fetch('https://randomuser.me/api/?results=10')
  //const res = await fetch ('https://newsapi.org/v2/top-headlines?country=us')
  const data = await res.json()

  //console.log(`source data fetched. Count: ${data.length}`)

  return {
    sources: data.map(entry => entry.source)
  }
}

export default Index

and here SHORTED api data looks like:
{"status":"ok","totalResults":38,"articles":[{"source":{"id":"fox-news","name":"Fox News"},"author":"Frank Miles","title":....}]}

I know this is an object but not an array and map() is not valid for object. But how can I get around this based on my code above?

The expected result should be new headlines be displayed but always got "TypeError: data.map is not a function". I tried the solutions suggested here but did not work. I am kind of new to this.

Body:
Since your data is an Object you can't use map on it as Object don't have map method, you're trying to map source property which is inside articles array

change this

data.map(entry => entry.source)

to this

data.articles.map(entry => entry.source)


问:
I am unable to getStatusesByTag of the enqueueUniquePeriodicWork through WorkManager
I am using WorkManager via implementation "android.arch.work:work-runtime:1.0.1" to start a PeriodicWorkRequest to call a Rest API to pull some data at interval PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS which is 15 minutes, my code is:

```<code>    PeriodicWorkRequest.Builder builder = new
            PeriodicWorkRequest.Builder(MyWorker.class,
            PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS, TimeUnit.MILLISECONDS)
            .addTag(TAG_WORKER)
            .setInputData(createInputData(config));
    WorkManager.getInstance().enqueueUniquePeriodicWork(TAG_WORKER,
            ExistingPeriodicWorkPolicy.KEEP, builder.build());
</code>```

I want to know the status or the PeriodicWorkRequest enqueued by WorkManager by its TAG, through the code:

```<code>WorkManager.getInstance().getStatusesByTag(TAG_WORKER);
</code>```

But I am unable to resolve the method getStatusesByTag(TAG_WORKER), please help if anyone did the workaround to get the Status of Request been enqueued by TAG.

Thanks in advance!

答:
You are using unique work. To observe unique work you should be using
getWorkInfosForUniqueWorkLiveData API.

Edit: Re-read your code snippet and realized that you are also adding a tag. You can also use the getWorkInfosByTagLiveData API mentioned in the answer below.

Body:
I am using WorkManager via implementation "android.arch.work:work-runtime:1.0.1" to start a PeriodicWorkRequest to call a Rest API to pull some data at interval PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS which is 15 minutes, my code is:

    PeriodicWorkRequest.Builder builder = new
            PeriodicWorkRequest.Builder(MyWorker.class,
            PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS, TimeUnit.MILLISECONDS)
            .addTag(TAG_WORKER)
            .setInputData(createInputData(config));
    WorkManager.getInstance().enqueueUniquePeriodicWork(TAG_WORKER,
            ExistingPeriodicWorkPolicy.KEEP, builder.build());

I want to know the status or the PeriodicWorkRequest enqueued by WorkManager by its TAG, through the code:

WorkManager.getInstance().getStatusesByTag(TAG_WORKER);

But I am unable to resolve the method getStatusesByTag(TAG_WORKER), please help if anyone did the workaround to get the Status of Request been enqueued by TAG.

Thanks in advance!


问:
How to nest two data models in a data binding in sapui5
I want to do something like the following in sapui5, where two lists are nested, but the description is not showed, no matter what I change.

Can anyone help? Is it possible at all?

And what's more, I actually just want to add some text-controls or labels in the inner list (and I need something like a list with path or items to bind it), is there another possibility to do this instead of StandardListItem, so that it fits better to the upper part?

```<code>    <List headerText="Events" items="{path: 'model1>/'}" >
       <items>
        <CustomListItem type="Navigation">
             <HBox>
                <VBox>
                    <Label text="{model1>message}"/>
                    <Text text="{model1>date}"></Text>
                    <Text text="{model1>time}"></Text>

                    <List id="MasterAttributeList" items="{ path: 'model2>/' }">
                            <items>
 critical part -->            <StandardListItem title="{model1>description}"
                                           description="{model2>{= ${model1>key}}}"/>
                            </items>
                       </List>
                </VBox>
                 </HBox>
             </CustomListItem>
        </items>
    </List>
</code>```

Best regards!

答:
You cant bind they way you did, as it is a aggregation binding. As per your XML view it is a nested list, it means that you need to have nested data to bind.

For example: Nested Data

```<code>{
  'items': [
    {
        'message': "ss",
        'date': "2020-12-12",
        'time': "12:00",
        'items1': [
            { 'description': "description", 'key': "2141" },
            { 'description': "description", 'key': "2141" },
            { 'description': "description", 'key': "2141" }
        ]

    },
    {
        'message': "ss",
        'date': "2020-12-12",
        'time': "5:00",
        'items1': [
            { 'description': "description", 'key': "2141" },
            { 'description': "description", 'key': "2141" },
            { 'description': "description", 'key': "2141" }
        ]
    },
    {
        'message': "fff",
        'date': "2020-12-12",
        'time': "8:00",
        'items1': [
            { 'description': "description", 'key': "2141" },
            { 'description': "description", 'key': "2141" },
            { 'description': "description", 'key': "2141" }
        ]
    }
  ]
}
</code>```

The above data works fine for the nested list and also need to mention the templateShareable: true property as well

```<code><List headerText="Events" items="{path: '/items'}" >
    <items>
       <CustomListItem type="Navigation">
         <HBox>
            <VBox>
                <Label text="{message}"/>
                <Text text="{date}"></Text>
                <Text text="{time}"></Text>
                <List items="{path:'items1', templateShareable: true}">
                    <items>
                        <StandardListItem title="{description}" description="{key}"/>
                    </items>
                </List>
            </VBox>
        </HBox>
    </CustomListItem>
  </items>
</List>
</code>```

Note: Use formatting as per your requirement.

Body:
I want to do something like the following in sapui5, where two lists are nested, but the description is not showed, no matter what I change.

Can anyone help? Is it possible at all?

And what's more, I actually just want to add some text-controls or labels in the inner list (and I need something like a list with path or items to bind it), is there another possibility to do this instead of StandardListItem, so that it fits better to the upper part?

    <List headerText="Events" items="{path: 'model1>/'}" >
       <items>
        <CustomListItem type="Navigation">
             <HBox>
                <VBox>
                    message}"/>
                    <Text text="{model1>date}"></Text>
                    <Text text="{model1>time}"></Text>

                    <List id="MasterAttributeList" items="{ path: 'model2>/' }">
                            <items>
 critical part -->            <StandardListItem title="{model1>description}"
                                           description="{model2>{= ${model1>key}}}"/>
                            </items>
                       </List>
                </VBox>
                 </HBox>
             </CustomListItem>
        </items>
    </List>

Best regards!

Body:
You cant bind they way you did, as it is a aggregation binding. As per your XML view it is a nested list, it means that you need to have nested data to bind.

For example: Nested Data

{
  'items': [
    {
        'message': "ss",
        'date': "2020-12-12",
        'time': "12:00",
        'items1': [
            { 'description': "description", 'key': "2141" },
            { 'description': "description", 'key': "2141" },
            { 'description': "description", 'key': "2141" }
        ]

    },
    {
        'message': "ss",
        'date': "2020-12-12",
        'time': "5:00",
        'items1': [
            { 'description': "description", 'key': "2141" },
            { 'description': "description", 'key': "2141" },
            { 'description': "description", 'key': "2141" }
        ]
    },
    {
        'message': "fff",
        'date': "2020-12-12",
        'time': "8:00",
        'items1': [
            { 'description': "description", 'key': "2141" },
            { 'description': "description", 'key': "2141" },
            { 'description': "description", 'key': "2141" }
        ]
    }
  ]
}

The above data works fine for the nested list and also need to mention the templateShareable: true property as well

<List headerText="Events" items="{path: '/items'}" >
    <items>
       <CustomListItem type="Navigation">
         <HBox>
            <VBox>
                <Label text="{message}"/>
                <Text text="{date}"></Text>
                <Text text="{time}"></Text>
                <List items="{path:'items1', templateShareable: true}">
                    <items>
                        <StandardListItem title="{description}" description="{key}"/>
                    </items>
                </List>
            </VBox>
        </HBox>
    </CustomListItem>
  </items>
</List>

Note: Use formatting as per your requirement.


问:
Flutter: How to check what is the previous route in navigator?
I can go to route 'C' from both routes 'A' and 'B'. When I press back button on 'C' I want to make different api calls if I go back to 'A' or 'B'.</p>

答: The solution is RouteAware - it has didPopNext method.</p>


问:
Preview Excel file in browser - Blob data
I am trying to get blob and  preview the file in browser, it works fine for pdf files. How can i preview the excel files, when trying to preview excel it is downloading the file (looking for a java script, HTML solution)</p>

答:
You can use xlsx npm package to read Excel files.
I have created stackblitz https://angular-kpvq2i.stackblitz.io

You can find more details on https://www.npmjs.com/package/xlsx


问:
Is having a while loop inside a for loop considered a nested while loop?
Can having a while loop inside a for loop be considered a nested while loop?

How can I do this same problem using do while?

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

#define NUMS 3

int main() {
    // insert code here...
    int highVal;
    int lowVal;
    int i;
    printf("---=== IPC Temperature Analyzer ===---\n");

    for (i=1;i<=NUMS;i++){
        printf("Enter the high value for day %d: ",i);
        scanf("%d",&highVal);
        printf("Enter the low value for day %d: ",i);
        scanf("%d",&lowVal);

        while((highVal < lowVal)||(highVal >= 41 || lowVal <= -41)){

            printf("Incorrect values,temperature must be in the range -40 to 40,high must be greater than low\n");
            i--;
            highVal=1;
            lowVal=0;
        }
    }

    return 0;
}
</code>```

I am getting the results I need to be getting but the assignment calls for using a nested while loop (or do while) as well as for loop to prompt the user.

答:
Can having a while loop inside a for loop be considered a nested while loop?

No, it'd just be a nested loop, the same as this would be a nested loop:

```<code>foo:
    z = baz();
    x++;
bar:
    y++;
    if(x < 100) goto bar;
    if(y < 100) goto foo;
</code>```

Note that you can convert a for() into a while by separating out the pieces. For example, this:

```<code>    for (i=initial; i<=MAX; i++) {
        do_something();
    }
</code>```

..is equivalent to this:

```<code>    i=initial;
    while (i<=MAX) {
        do_something();
        i++;
    }
</code>```

In a similar way you can convert while() into if and goto fairly easily (and therefore can convert for() into if and goto too). For example, the previous for() and while() examples are equivalent to this:

```<code>    i=initial;
start:
    if( !(i<=MAX) ) goto end;
    do_something();
    i++;
    goto start;
end:
</code>```

Body:
Can having a while loop inside a for loop be considered a nested while loop?

How can I do this same problem using do while?

#include <stdio.h>

#define NUMS 3

int main() {
    // insert code here...
    int highVal;
    int lowVal;
    int i;
    printf("---=== IPC Temperature Analyzer ===---\n");

    for (i=1;i<=NUMS;i++){
        printf("Enter the high value for day %d: ",i);
        scanf("%d",&highVal);
        printf("Enter the low value for day %d: ",i);
        scanf("%d",&lowVal);

        while((highVal < lowVal)||(highVal >= 41 || lowVal <= -41)){

            printf("Incorrect values,temperature must be in the range -40 to 40,high must be greater than low\n");
            i--;
            highVal=1;
            lowVal=0;
        }
    }

    return 0;
}

I am getting the results I need to be getting but the assignment calls for using a nested while loop (or do while) as well as for loop to prompt the user.

Body:
Can having a while loop inside a for loop be considered a nested while loop?

No, it'd just be a nested loop, the same as this would be a nested loop:

foo:
    z = baz();
    x++;
bar:
    y++;
    if(x < 100) goto bar;
    if(y < 100) goto foo;

Note that you can convert a for() into a while by separating out the pieces. For example, this:

    for (i=initial; i<=MAX; i++) {
        do_something();
    }

..is equivalent to this:

    i=initial;
    while (i<=MAX) {
        do_something();
        i++;
    }

In a similar way you can convert while() into if and goto fairly easily (and therefore can convert for() into if and goto too). For example, the previous for() and while() examples are equivalent to this:

    i=initial;
start:
    if( !(i<=MAX) ) goto end;
    do_something();
    i++;
    goto start;
end:


问:
Does symfony have a built-in method for comparing tainted values to the original?
I am using symfony 1.4 with Doctrine.  I have built a form which uses a table that has the Versionable behaviour.  As expected, Versionable creates a new version of the row every time the form is submitted and saved.  My problem is that I would like to prevent it doing so if the actual values submitted are not any different from the original values put into the form via the edit action.

I know that I can do this with javascript relatively easily.  I'm just curious as to whether symfony or Doctrine have this functionality already, and how it is used if so.  It just seems like something that symfony would have a method for, which could be checked right before $form->save() is called.  Am I dreaming or perhaps missing something obvious?

答:
The comment for the save() method of the Doctrine_Record is

```<code>/**
 * applies the changes made to this object into database
 * this method is smart enough to know if any changes are made
 * and whether to use INSERT or UPDATE statement
 *
 * this method also saves the related components
 *
 * @param Doctrine_Connection $conn     optional connection parameter
 * @throws Exception                    if record is not valid and validation is active
 * @return void
 */
</code>```

so first, you should check whether it does not already work.
If not, Doctrine_Record has a isModified() method you could use. If the bind() method of the form object modifies the object in the form which should at first contain the default values, then this method should return true.

Body:
The comment for the save() method of the Doctrine_Record is

/**
 * applies the changes made to this object into database
 * this method is smart enough to know if any changes are made
 * and whether to use INSERT or UPDATE statement
 *
 * this method also saves the related components
 *
 * @param Doctrine_Connection $conn     optional connection parameter
 * @throws Exception                    if record is not valid and validation is active
 * @return void
 */

so first, you should check whether it does not already work.
If not, Doctrine_Record has a isModified() method you could use. If the bind() method of the form object modifies the object in the form which should at first contain the default values, then this method should return true.