问:
How do you write an array of numbers to a csv file?
```<code>let mut file = Writer::from_path(output_path)?;
file.write_record([5.34534536546, 34556.456456467567567, 345.56465456])?;
</code>```

Produces the following error:

```<code>error[E0277]: the trait bound `{float}: AsRef<[u8]>` is not satisfied
   --> src/main.rs:313:27
    |
313 |         file.write_record([5.34534536546, 34556.456456467567567, 345.56465456])?;
    |              ------------ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `AsRef<[u8]>` is not implemented for `{float}`
    |              |
    |              required by a bound introduced by this call
    |
    = help: the following implementations were found:
              <&T as AsRef<U>>
              <&mut T as AsRef<U>>
              <Arc<T> as AsRef<T>>
              <Box<T, A> as AsRef<T>>
            and 44 others
note: required by a bound in `Writer::<W>::write_record`
   --> /home/mlueder/.cargo/registry/src/github.com-1ecc6299db9ec823/csv-1.1.6/src/writer.rs:896:12
    |
896 |         T: AsRef<[u8]>,
    |            ^^^^^^^^^^^ required by this bound in `Writer::<W>::write_record`
</code>```

Is there any way to use the csv crate with numbers instead of structs or characters?

答:
Only strings or raw bytes can be written to a file; if you try to give it something else, it isn't sure how to handle the data (as @SilvioMayolo mentioned). You can map your float array to one with strings, and then you will be able to write the string array to the file.

let float_arr = [5.34534536546, 34556.456456467567567, 345.56465456];
let string_arr = float_arr.map(|e| e.to_string();
```

This can obviously be combined to one line without using the extra variable, but it is a little easier to see the extra step that we need to take if it is split apart.

Body:
let mut file = Writer::from_path(output_path)?;
file.write_record([5.34534536546, 34556.456456467567567, 345.56465456])?;

Produces the following error:

error[E0277]: the trait bound `{float}: AsRef<[u8]>` is not satisfied
   --> src/main.rs:313:27
    |
313 |         file.write_record([5.34534536546, 34556.456456467567567, 345.56465456])?;
    |              ------------ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `AsRef<[u8]>` is not implemented for `{float}`
    |              |
    |              required by a bound introduced by this call
    |
    = help: the following implementations were found:
              <&T as AsRef>
              <&mut T as AsRef>
              <Arc<T> as AsRef<T>>
              <Box<T, A> as AsRef<T>>
            and 44 others
note: required by a bound in `Writer::<W>::write_record`
   --> /home/mlueder/.cargo/registry/src/github.com-1ecc6299db9ec823/csv-1.1.6/src/writer.rs:896:12
    |
896 |         T: AsRef<[u8]>,
    |            ^^^^^^^^^^^ required by this bound in `Writer::<W>::write_record`

Is there any way to use the csv crate with numbers instead of structs or characters?

Body:
Only strings or raw bytes can be written to a file; if you try to give it something else, it isn't sure how to handle the data (as @SilvioMayolo mentioned). You can map your float array to one with strings, and then you will be able to write the string array to the file.

let float_arr = [5.34534536546, 34556.456456467567567, 345.56465456];
let string_arr = float_arr.map(|e| e.to_string();

This can obviously be combined to one line without using the extra variable, but it is a little easier to see the extra step that we need to take if it is split apart.


来源: stackexchange

问:
Create common codable for slightly different json responses - Swift
How to create a common codable struct in swift for slightly different json responses.For example response A and B has almost same attributes and B has some extra attribute called Designation.Is it possible to create common codable struct for this scenario?

```<code>//Response A
{
  "name" : "Jhon",
  "age" : 23,
  "mobile" : "+11012341234",
  .
  .
  .
}

//Response B
{
  "name" : "Jhon",
  "age" : 23,
  "mobile" : "+11012341234",
  .
  .
  .
  "designation": "Manager"
}
</code>```

答:
You can use optionals like so:</p>
```<code>struct Response: Decodable {

   var name: String
   var age: Int
   var mobile: String
   var designation: String?

   // If you need to decode, it would look like this:
   init(from decoder: Decoder) throws {

      let container = try decoder.container(keyedBy: CodingKeys.self)

      name = try container.decode(String.self, forKey: .name)
      age = try container.decode(Int.self, forKey: .age)
      mobile = try container.decode(String.self, forKey: .mobile)

      // Decode designation if provided
      if container.contains(.designation){
         designation = try container.decode(String.self, forKey: .designation)
      }
   }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How to create a common codable struct in swift for slightly different json responses.For example response A and B has almost same attributes and B has some extra attribute called Designation.Is it possible to create common codable struct for this scenario?

//Response A
{
  "name" : "Jhon",
  "age" : 23,
  "mobile" : "+11012341234",
  .
  .
  .
}

//Response B
{
  "name" : "Jhon",
  "age" : 23,
  "mobile" : "+11012341234",
  .
  .
  .
  "designation": "Manager"
}

Body:
You can use optionals like so:

struct Response: Decodable {

   var name: String
   var age: Int
   var mobile: String
   var designation: String?

   // If you need to decode, it would look like this:
   init(from decoder: Decoder) throws {

      let container = try decoder.container(keyedBy: CodingKeys.self)

      name = try container.decode(String.self, forKey: .name)
      age = try container.decode(Int.self, forKey: .age)
      mobile = try container.decode(String.self, forKey: .mobile)

      // Decode designation if provided
      if container.contains(.designation){
         designation = try container.decode(String.self, forKey: .designation)
      }
   }
}


问:
How to do Upsert in Vlang
Currently, the ORM for V only supports select, update, and insert. I would like to do a more complicated upsert like this:

INSERT INTO Settings (Key, Value)
VALUES (?0, ?1)
ON CONFLICT(Key)
DO UPDATE
SET Key = ?0,
    Value = ?1;`
```
<p>But it looks like from the docs there is no exposure for doing an update like this. So, I would need to clean the inserted/updated values myself.</p>
<p>Is there a way to do direct SQL with variables directly? Am I missing something?</p>
<p>Another option I would have would be:</p>
```setting := Settings {
    key: key
    value: value
}
sql r.db {
    insert setting into Settings
}
sql r.db {
    update Settings set value = value where key == key
}
```

Although the above works it isn't very elegant and requires two calls to the DB. Is there a way to do direct queries with arguments?

答:
The vlang Sqlite library (not the Orm) has a method that can execute raw SQL against the db and return raw row data.

You could create your upsert query using the information in this stackoverflow and execute it as a string against the DB.

Something like this maybe (you'll have to test it against your particular database until it works):

r.db.exec("UPDATE Settings SET value = 'value' WHERE id = 2;
INSERT INTO Settings(key, value) SELECT 2, 'value' WHERE changes() = 0;")
```

Do not use this in production. Unfortunately, the exec function does not santize inputs or pass in parameterized values. This means that you will be vulnerable to sql injection by default.

Title: How to do Upsert in Vlang

Body:
Currently, the ORM for V only supports select, update, and insert. I would like to do a more complicated upsert like this:

INSERT INTO Settings (Key, Value)
VALUES (?0, ?1)
ON CONFLICT(Key)
DO UPDATE
SET Key = ?0,
    Value = ?1;`

But it looks like from the docs there is no exposure for doing an update like this. So, I would need to clean the inserted/updated values myself.

Is there a way to do direct SQL with variables directly? Am I missing something?

Another option I would have would be:

setting := Settings {
    key: key
    value: value
}
sql r.db {
    insert setting into Settings
}
sql r.db {
    update Settings set value = value where key == key
}

Although the above works it isn't very elegant and requires two calls to the DB. Is there a way to do direct queries with arguments?

Body:
The vlang Sqlite library (not the Orm) has a method that can execute raw SQL against the db and return raw row data.

You could create your upsert query using the information in this stackoverflow and execute it as a string against the DB.

Something like this maybe (you'll have to test it against your particular database until it works):

r.db.exec("UPDATE Settings SET value = 'value' WHERE id = 2;
INSERT INTO Settings(key, value) SELECT 2, 'value' WHERE changes() = 0;")

Do not use this in production. Unfortunately, the exec function does not santize inputs or pass in parameterized values. This means that you will be vulnerable to sql injection by default.


问:
json_normalize JSON file with multiple levels of lists containing dictionary (sample included)
(Originally from previous question but re-framed for the more general question)

This is a sample json file I'm working with with 2 records:

```<code>[{"Time":"2016-01-10",
"ID"
:13567,
"Content":{
    "Event":"UPDATE",
    "Id":{"EventID":"ABCDEFG"},
    "Story":[{
        "@ContentCat":"News",
        "Body":"Related Meeting Memo: Engagement with target firm for potential M&A.  Please be on call this weekend for news updates.",
        "BodyTextType":"PLAIN_TEXT",
        "DerivedId":{"Entity":[{"Id":"Amy","Score":70}, {"Id":"Jon","Score":70}]},
        "DerivedTopics":{"Topics":[
                            {"Id":"Meeting","Score":70},
                            {"Id":"Performance","Score":70},
                            {"Id":"Engagement","Score":100},
                            {"Id":"Salary","Score":70},
                            {"Id":"Career","Score":100}]
                        },
        "HotLevel":0,
        "LanguageString":"ENGLISH",
        "Metadata":{"ClassNum":50,
                    "Headline":"Attn: Weekend",
                    "WireId":2035,
                    "WireName":"IIS"},
        "Version":"Original"}
                ]},
"yyyymmdd":"20160110",
"month":201601},
{"Time":"2016-01-12",
"ID":13568,
"Content":{
    "Event":"DEAL",
    "Id":{"EventID":"ABCDEFG2"},
    "Story":[{
        "@ContentCat":"Details",
        "Body":"Test email contents",
        "BodyTextType":"PLAIN_TEXT",
        "DerivedId":{"Entity":[{"Id":"Bob","Score":100}, {"Id":"Jon","Score":70}, {"Id":"Jack","Score":60}]},
        "DerivedTopics":{"Topics":[
                            {"Id":"Meeting","Score":70},
                            {"Id":"Engagement","Score":100},
                            {"Id":"Salary","Score":70},
                            {"Id":"Career","Score":100}]
                        },
        "HotLevel":0,
        "LanguageString":"ENGLISH",
        "Metadata":{"ClassNum":70,
                    "Headline":"Attn: Weekend",
                    "WireId":2037,
                    "WireName":"IIS"},
        "Version":"Original"}
                ]},
"yyyymmdd":"20160112",
"month":201602}]
</code>```

I'm trying to get to a dataframe at the level of the entity IDs (extracting Amy and Jon from record 1 and Bob, Jon, Jack from record 2).  How do I do this?
To clarify, the levels are (Content > Story > DerivedID > Entity > Id)

答:
df = pd.json_normalize(data, ['Content', 'Story', 'DerivedId', 'Entity'])
print(df)
```
<p>remember, the final root must be a list in your json</p>
<h2>Results:</h2>
<pre class="lang-py prettyprint-override"><code>     Id  Score
0   Amy     70
1   Jon     70
2   Bob    100
3   Jon     70
4  Jack     60
</code>```

if you want just id

df[['Id']]
```

Body:
(Originally from previous question but re-framed for the more general question)

This is a sample json file I'm working with with 2 records:

[{"Time":"2016-01-10",
"ID"
:13567,
"Content":{
    "Event":"UPDATE",
    "Id":{"EventID":"ABCDEFG"},
    "Story":[{
        "@ContentCat":"News",
        "Body":"Related Meeting Memo: Engagement with target firm for potential M&A.  Please be on call this weekend for news updates.",
        "BodyTextType":"PLAIN_TEXT",
        "DerivedId":{"Entity":[{"Id":"Amy","Score":70}, {"Id":"Jon","Score":70}]},
        "DerivedTopics":{"Topics":[
                            {"Id":"Meeting","Score":70},
                            {"Id":"Performance","Score":70},
                            {"Id":"Engagement","Score":100},
                            {"Id":"Salary","Score":70},
                            {"Id":"Career","Score":100}]
                        },
        "HotLevel":0,
        "LanguageString":"ENGLISH",
        "Metadata":{"ClassNum":50,
                    "Headline":"Attn: Weekend",
                    "WireId":2035,
                    "WireName":"IIS"},
        "Version":"Original"}
                ]},
"yyyymmdd":"20160110",
"month":201601},
{"Time":"2016-01-12",
"ID":13568,
"Content":{
    "Event":"DEAL",
    "Id":{"EventID":"ABCDEFG2"},
    "Story":[{
        "@ContentCat":"Details",
        "Body":"Test email contents",
        "BodyTextType":"PLAIN_TEXT",
        "DerivedId":{"Entity":[{"Id":"Bob","Score":100}, {"Id":"Jon","Score":70}, {"Id":"Jack","Score":60}]},
        "DerivedTopics":{"Topics":[
                            {"Id":"Meeting","Score":70},
                            {"Id":"Engagement","Score":100},
                            {"Id":"Salary","Score":70},
                            {"Id":"Career","Score":100}]
                        },
        "HotLevel":0,
        "LanguageString":"ENGLISH",
        "Metadata":{"ClassNum":70,
                    "Headline":"Attn: Weekend",
                    "WireId":2037,
                    "WireName":"IIS"},
        "Version":"Original"}
                ]},
"yyyymmdd":"20160112",
"month":201602}]

I'm trying to get to a dataframe at the level of the entity IDs (extracting Amy and Jon from record 1 and Bob, Jon, Jack from record 2).  How do I do this?
To clarify, the levels are (Content > Story > DerivedID > Entity > Id)

Body:
df = pd.json_normalize(data, ['Content', 'Story', 'DerivedId', 'Entity'])
print(df)

remember, the final root must be a list in your json

Results:

     Id  Score
0   Amy     70
1   Jon     70
2   Bob    100
3   Jon     70
4  Jack     60

if you want just id

df[['Id']]


问:
Are WPF and Silverlight command implementations useless for the M-V-VM (M-V-P) pattern?
Please excuse my ignorance, I only started coding in Silverlight recently.

I tried implementing the command pattern in Silverlight and hit a wall.
They say commands are great, because you can write them into xaml, so you can keep your code-behind clean, also you have loose coupling between your view and your viewmodel because there is no direct reference to the viewmodel in the view.

You can not keep your code-behind clean, because you can bind only one command to a control, and you have to decide which event will fire your command when you bind it. If a control has 30 events, you have to choose one for commanding. The other 29 will execute the other commands from event handlers from the code behind.

Loose coupling can be achieved more simply by dependency injection, commands add a useless layer of indirection that gives nothing extra, they only make it a bit harder to maintain your code. It is easier to maintain your code, when you are programming against an interface and see exactly what method gets called, then when you have to keep jumping between your command definitions and your viewmodel.

Did I miss anything, or commands are really not meant to be used for view and viewmodel interaction?

Please see the following question. This is why I don't get all the hype with commands:

How should I handle multiple events per control w/command pattern using MVVM in Silverlight?

答:
SL 2.0 is not so powerful as WPF, you will have to write some code behind :-(.

Not sure if you have read this article about MVVM and SL, talks about commands limitations on SL:

http://msdn.microsoft.com/en-us/magazine/dd458800.aspx

OwnerDisplayName: Sandor Davidhazi

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Braulio


问:
speechSynthesis.speak() doesn`t output any sound
I am trying to create a website that scrapes a news website and reads it.
For some reason, whenever I am trying to read the actual info of the article, it reads part of it and stops after a few seconds.

important to point out :

I am using chromium.

The text I'm inserting doesn't reach speechSynthesis.speak()
text limit.

My function :

```<code>export async function textToSpeech(text) {
  new Promise((resolve) => {
    let msg = new SpeechSynthesisUtterance();
    msg.voice = voices[6];
    msg.lang = "en";
    msg.text = text;
    speechSynthesis.speak(msg);
    msg.addEventListener("end", () => {
      resolve();
    });
  });
}
</code>```

calling the function :

```<code>    ReadNews(data) {
    textToSpeech(data.Title)
      .then(textToSpeech(data.Info))
      .then(textToSpeech("Would You like me to continue?"))
      .then(
        ContinueCON.addEventListener("click", () => {
          textToSpeech(data.Content);
        })
      );
};
</code>```

The first 3 instances (data.title, data.info, and the default message) are all spoken as expected. But on the 4th instance, stops after a few seconds.

Several things I have tried:
I used window.speechSynthesis.speaking right after the sound stopped working, and it printed true(which is very bizarre)

1st Edit (Yet to be solved)

```<code>Changed the code by the comments below
export function textToSpeech(text) {
  return new Promise((resolve) => {
    let msg = new SpeechSynthesisUtterance();
    msg.voice = voices[6];
    msg.lang = "en";
    msg.text = text;
    speechSynthesis.cancel(msg);
    speechSynthesis.speak(msg);
    msg.addEventListener("end", () => {
      resolve();
    });
  });
}
</code>```

Async was unnecessary and also "clean" the "Speak" queue (by using cancel)

```<code>ReadNews(data) {
    textToSpeech(data.Title)
      .then(() => textToSpeech(data.Info))
      .then(() => textToSpeech("Would You like me to continue?"))
      .then(() =>
        ContinueCON.addEventListener("click", () => {
          textToSpeech(data.Content);
        })
      );
  },
};
</code>```

I invoked the return value immediately instead of waiting for a resolve and then running the next line of text.
Problem is yet to be solved.

答:
I see a couple issues with your code, which are causing the speech to all get queued up right away, without waiting. But speechSynthesis is supposed to handle that automatically, so it's not clear to me how they would cause what you're seeing. Still, i'll point them out in case they're causing your problem in a subtle way that i can't identify.

The first issue is that your textToSpeech function doesn't return the promise it creates. A promise is implicitly returned since it's an async function, but that promise will not wait for the speech to finish. The fix for this is to add a return in (and you can also remove async if you wish, since you're not awaiting anything)

```<code>export function textToSpeech(text) {
  return new Promise((resolve) => {
    let msg = new SpeechSynthesisUtterance();
    msg.voice = voices[6];
    msg.lang = "en";
    msg.text = text;
    speechSynthesis.speak(msg);
    msg.addEventListener("end", () => {
      resolve();
    });
  });
}
</code>```

Secondly, ReadNews is not waiting for the promises to finish. .then(textToSpeech(data.Info)) means "immediately call textToSpeech, passing in data.Info, and then whatever it returns pass that into .then". Instead, you want to pass a function into .then, so that the function will be called once the previous promise has resolved:

```<code>ReadNews(data) {
  textToSpeech(data.Title)
    .then(() => textToSpeech(data.Info))
    .then(() => textToSpeech("Would You like me to continue?"))
    .then(
      () => ContinueCON.addEventListener("click", () => {
        textToSpeech(data.Content);
      })
    );
}
</code>```

Or with async/await:

```<code>async ReadNews(data) {
  await textToSpeech(data.Title);
  await textToSpeech(data.Info);
  await textToSpeech("Would you like me to continue?");
  ContinueCON.addEventListener("click", () => {
    textToSpeech(data.Content);
  })
}
</code>```

Body:
I am trying to create a website that scrapes a news website and reads it.
For some reason, whenever I am trying to read the actual info of the article, it reads part of it and stops after a few seconds.

important to point out :

I am using chromium.

The text I'm inserting doesn't reach speechSynthesis.speak()
text limit.

My function :

export async function textToSpeech(text) {
  new Promise((resolve) => {
    let msg = new SpeechSynthesisUtterance();
    msg.voice = voices[6];
    msg.lang = "en";
    msg.text = text;
    speechSynthesis.speak(msg);
    msg.addEventListener("end", () => {
      resolve();
    });
  });
}

calling the function :

    ReadNews(data) {
    textToSpeech(data.Title)
      .then(textToSpeech(data.Info))
      .then(textToSpeech("Would You like me to continue?"))
      .then(
        ContinueCON.addEventListener("click", () => {
          textToSpeech(data.Content);
        })
      );
};

The first 3 instances (data.title, data.info, and the default message) are all spoken as expected. But on the 4th instance, stops after a few seconds.

Several things I have tried:
I used window.speechSynthesis.speaking right after the sound stopped working, and it printed true(which is very bizarre)

1st Edit (Yet to be solved)

Changed the code by the comments below
export function textToSpeech(text) {
  return new Promise((resolve) => {
    let msg = new SpeechSynthesisUtterance();
    msg.voice = voices[6];
    msg.lang = "en";
    msg.text = text;
    speechSynthesis.cancel(msg);
    speechSynthesis.speak(msg);
    msg.addEventListener("end", () => {
      resolve();
    });
  });
}

Async was unnecessary and also "clean" the "Speak" queue (by using cancel)

ReadNews(data) {
    textToSpeech(data.Title)
      .then(() => textToSpeech(data.Info))
      .then(() => textToSpeech("Would You like me to continue?"))
      .then(() =>
        ContinueCON.addEventListener("click", () => {
          textToSpeech(data.Content);
        })
      );
  },
};

I invoked the return value immediately instead of waiting for a resolve and then running the next line of text.
Problem is yet to be solved.

Body:
I see a couple issues with your code, which are causing the speech to all get queued up right away, without waiting. But speechSynthesis is supposed to handle that automatically, so it's not clear to me how they would cause what you're seeing. Still, i'll point them out in case they're causing your problem in a subtle way that i can't identify.

The first issue is that your textToSpeech function doesn't return the promise it creates. A promise is implicitly returned since it's an async function, but that promise will not wait for the speech to finish. The fix for this is to add a return in (and you can also remove async if you wish, since you're not awaiting anything)

export function textToSpeech(text) {
  return new Promise((resolve) => {
    let msg = new SpeechSynthesisUtterance();
    msg.voice = voices[6];
    msg.lang = "en";
    msg.text = text;
    speechSynthesis.speak(msg);
    msg.addEventListener("end", () => {
      resolve();
    });
  });
}

Secondly, ReadNews is not waiting for the promises to finish. .then(textToSpeech(data.Info)) means "immediately call textToSpeech, passing in data.Info, and then whatever it returns pass that into .then". Instead, you want to pass a function into .then, so that the function will be called once the previous promise has resolved:

ReadNews(data) {
  textToSpeech(data.Title)
    .then(() => textToSpeech(data.Info))
    .then(() => textToSpeech("Would You like me to continue?"))
    .then(
      () => ContinueCON.addEventListener("click", () => {
        textToSpeech(data.Content);
      })
    );
}

Or with async/await:

async ReadNews(data) {
  await textToSpeech(data.Title);
  await textToSpeech(data.Info);
  await textToSpeech("Would you like me to continue?");
  ContinueCON.addEventListener("click", () => {
    textToSpeech(data.Content);
  })
}


问:
how to make my content area to the right of my menu?
Hello im trying to put my content area to the right of my vertical nav bar using bootstrap 4. in my current code the content area is under the menu. any suggestions on how to fix it so its next to the menu on the right side.
Thank you</p>
```<code> <div class="container-fluid">
 <div class="col-3">

 <nav class="navbar navbar-expand-sm bg-dark navbar-dark">
 <button class="navbar-toggler" type="button" data-toggle="collapse" data-
 target="#collapsibleNavbar" aria-expanded="true">
 <span class="navbar-toggler-icon"></span>
 </button>
 <div class="navbar-collapse collapse show" id="collapsibleNavbar" style>
 <ul class="navbar.flex-column">
 <li class="nav-item">
 <a class="nav-link" href="index.html">Index</a>
 </li>

 </ul>
 </div>
 </nav>
 </div>
 </div>

 <div class="container-fluid">
 <div class="col-9">

 <p>Main Content area</p>

 </div>
 </div>
</code>```

答: Copy the col-9 div and place it after the col-3 div ends. Add d-flex flex-row classes with container-fluid class.

Body:
Hello im trying to put my content area to the right of my vertical nav bar using bootstrap 4. in my current code the content area is under the menu. any suggestions on how to fix it so its next to the menu on the right side.
Thank you

 <button class="navbar-toggler" type="button" data-toggle="collapse" data-
 target="#collapsibleNavbar" aria-expanded="true">

 </button>

 Index

Main Content area


问:
Any reason Azure App Service Outbound IP showing IPV6 when integrated with vNET?
I am using Azure App Service with P1V3 App Services Plan so that I can make use of Private Endpoint and vNET integration. vNET integration is configured on a subnet with NAT Gateway attached.

When my application calls outbound, my goal is to control the outbound IP and my expectation is, it should show the NAT ip as outbound ip. But, it does not! Here is my sample code-

App (.Net Core 3.1) is deployed in app service and I see IPV6 as outbound ip? Any idea why I am not seeing IPV4 (NAT ip)? You can see the result by accessing this url- https://whois.aspnet4you.com/api/values/getclientipv2

This is the network configuration at the moment-

Subnet looks like-

Outgoing ip showing here-

答:
I want to give credit to Sakaldeep Yadav for his blog post- https://www.linkedin.com/pulse/integrate-azure-web-app-nat-gateway-vnet-get-static-outbound-yadav/

Here is what I did to solve the issue-
Add vNET Integration to app service as you do normally.

Removed all the services from Endpoint Service section at the Subnet. This was the culprit! If you add services to endpoint service specially Microsoft.Web, traffic is routed through Azure backbone and as RithwikBojja-MT explained you get to see ipv6 as outbound address.

This is how your subnet should look like- you don't manually add subnet delegation, it is added when you add the subnet to app service vNet integration. Now I can see NAT ip as outbound ip. Try it- https://whois.aspnet4you.com/api/values/getclientipv2


问:
Run task every minute in Flutter
I'm very beginner in mobile development.
I want to create an android app with flutter which send a GET request to my server every minutes even if the app is in background or screen is off. I did it with the Cron plugin but when the app is no more in foreground, the data are not sent to my server.
Can you please help me to know which plugin need I to use ?
I tried with android_workmanager_plus but periodically wasn't seem to work :/

this is how it's implemented for the moment

```<code>TextButton(
                onPressed: () {
                  var cron =  Cron();
                  cron.schedule(Schedule.parse('*/1 * * * *'), () async {
                  BlocProvider.of<TestCubit>(context).validate();
                  });
                },
</code>```

and this is my method in my cubit file

```<code>validate() async{

    var battery = Battery();
    var batlevel = await battery.batteryLevel;
    state.status = Colors.blue;
    emit(state);
    try{
      final batt = await repo.getBattery(batlevel.toString());
      print(batt);
      //print(state.path);

    }catch(e){
      print(e);
    }
    state.status = Colors.green;
    emit(state);
  }
}
</code>```

Thanks for your future help :)

答:
You can use dart:async in your code with Timer.periodic

ex: for run task every 60 seconds

timer = Timer.periodic(
      const Duration(
        seconds: 60, //You can change second to milisecond etc
      ),
      (t) => getData(),
    );
```

you can add it in function or in initstate, Docs

Nb: don't forget to add
import 'dart:async'; and late Timer timer;

Title: Run task every minute in Flutter

Body:
I'm very beginner in mobile development.
I want to create an android app with flutter which send a GET request to my server every minutes even if the app is in background or screen is off. I did it with the Cron plugin but when the app is no more in foreground, the data are not sent to my server.
Can you please help me to know which plugin need I to use ?
I tried with android_workmanager_plus but periodically wasn't seem to work :/

this is how it's implemented for the moment

TextButton(
                onPressed: () {
                  var cron =  Cron();
                  cron.schedule(Schedule.parse('*/1 * * * *'), () async {
                  BlocProvider.of<TestCubit>(context).validate();
                  });
                },

and this is my method in my cubit file

validate() async{

    var battery = Battery();
    var batlevel = await battery.batteryLevel;
    state.status = Colors.blue;
    emit(state);
    try{
      final batt = await repo.getBattery(batlevel.toString());
      print(batt);
      //print(state.path);

    }catch(e){
      print(e);
    }
    state.status = Colors.green;
    emit(state);
  }
}

Thanks for your future help :)

Body:
You can use dart:async in your code with Timer.periodic

ex: for run task every 60 seconds

timer = Timer.periodic(
      const Duration(
        seconds: 60, //You can change second to milisecond etc
      ),
      (t) => getData(),
    );

you can add it in function or in initstate, Docs

Nb: don't forget to add
import 'dart:async'; and late Timer timer;


问:
Google Sheet Formula to extract from | separated hiearchy
I have a hierarchy list separated by |.  The hierarchy is listed as L1|L2|L3|L4|L5 ect.

I'm trying to create a formula to extract the L2 and L3 of the hierarchy.  The best method I've found for now is using the Text to Columns feature in Google Sheets but a formula would be ideal.  Giving some examples below.

答:
delete everything in A:B range and use:

```<code>=INDEX(ARRAY_CONSTRAIN(IFNA(SPLIT(REPT(REGEXEXTRACT(C2:C,
 "\|(.+)")&"|", 2), "|")), 9^9, 2))
</code>```

Body:
delete everything in A:B range and use:

=INDEX(ARRAY_CONSTRAIN(IFNA(SPLIT(REPT(REGEXEXTRACT(C2:C,
 "\|(.+)")&"|", 2), "|")), 9^9, 2))


问:
What part (success/error) of jquery's ajax receives a redirect status code?
I'm having a redirect sent by my server but jquery's ajax error: callback seems to get xhr.status=200 and status="parseerror"

Anywork around?? I don't want to overload other codes since I use the for the things that they were intended for? Is this just not possible with jquery?

The callback is like this:
error: function(xhr, status){...}

答:
When you redirect from the server you can send a response header along with it. And then look for that respone header in the ajax error/success callback. I hope that will help you

```<code> var status =   xhr.getResponseHeader("redirectResponseHeader");//Specify the same name in the server side code
</code>```

Now using status you can decide what to do.

ContentLicense: CC BY-SA 3.0

Body:
When you redirect from the server you can send a response header along with it. And then look for that respone header in the ajax error/success callback. I hope that will help you

 var status =   xhr.getResponseHeader("redirectResponseHeader");//Specify the same name in the server side code

Now using status you can decide what to do.


问:
Gunicorn with unix socket not working gives 502 bad gateway
I'm following the http://www.obeythetestinggoat.com/book/chapter_08.html book, and it says to add a unix socket to run nginx server with gunicorn, which i did.
This is my nginx file

```<code>server {
listen 80;
server_name mydjsuperlist-staging.tk;

location /static {
alias /home/elspeth/sites/mydjsuperlist-staging.tk/static;
}

location / {
proxy_set_header Host $host;
    proxy_pass http://unix:/tmp/mydjsuperlist-staging.tk.socket;
}
}
</code>```

Nginx reloads without any failure and checked it with nginx -t

When i run:

```<code>gunicorn --bind unix:/tmp/mydjsuperlist-staging.tk.socket superlists.wsgi:application
</code>```

It succesfully creates mydjsuperlist-staging.tk.socket file in tmp folder and i get this on my terminal

```<code>2016-09-01 18:56:01 [15449] [INFO] Starting gunicorn 18.0
2016-09-01 18:56:01 [15449] [INFO] Listening at: unix:/tmp/mydjsuperlist-staging.tk.socket (15449)
2016-09-01 18:56:01 [15449] [INFO] Using worker: sync
2016-09-01 18:56:01 [15452] [INFO] Booting worker with pid: 15452
</code>```

Everything seems fine, but when i go to my site mydjsuperlist-staging.tk it gives a (502) bad gateway error.
When i was using a port my site was running perfectly. What am i doing wrong over here ?

答:
Try to add your user to nginx group like:</p>
```<code>sudo usermod -a -G user nginx
</code>```

Body:
I'm following the http://www.obeythetestinggoat.com/book/chapter_08.html book, and it says to add a unix socket to run nginx server with gunicorn, which i did.
This is my nginx file

server {
listen 80;
server_name mydjsuperlist-staging.tk;

location /static {
alias /home/elspeth/sites/mydjsuperlist-staging.tk/static;
}

location / {
proxy_set_header Host $host;
    proxy_pass http://unix:/tmp/mydjsuperlist-staging.tk.socket;
}
}

Nginx reloads without any failure and checked it with nginx -t

When i run:

gunicorn --bind unix:/tmp/mydjsuperlist-staging.tk.socket superlists.wsgi:application

It succesfully creates mydjsuperlist-staging.tk.socket file in tmp folder and i get this on my terminal

2016-09-01 18:56:01 [15449] [INFO] Starting gunicorn 18.0
2016-09-01 18:56:01 [15449] [INFO] Listening at: unix:/tmp/mydjsuperlist-staging.tk.socket (15449)
2016-09-01 18:56:01 [15449] [INFO] Using worker: sync
2016-09-01 18:56:01 [15452] [INFO] Booting worker with pid: 15452

Everything seems fine, but when i go to my site mydjsuperlist-staging.tk it gives a (502) bad gateway error.
When i was using a port my site was running perfectly. What am i doing wrong over here ?

Body:
Try to add your user to nginx group like:

sudo usermod -a -G user nginx


问:
How to turn a single row to multiple row in mysql?
ex:

the column 'genre' has a row of data:

```<code>+----------------------------+
|            genres          |
+----------------------------+
|   action, adventure, drama |       |
|                            |
+----------------------------+
</code>```

my desired output will be a column that holds the following data:

```<code>+------------+
|    genre   |
+------------+
| action     |
| adventure  |
| drama      |
+------------+
</code>```

how do I do it in mysql?

答:
You can try to create a split function as below to get your expectation part of values by comma.

Schema (MySQL v5.7)

```<code>DELIMITER $$
DROP FUNCTION IF EXISTS `SPLIT_STR` $$
CREATE FUNCTION `SPLIT_STR`(
  x VARCHAR(255),
  delim VARCHAR(12),
  pos INT
) RETURNS varchar(255) CHARSET latin1
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
       LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
       delim, '') $$

DELIMITER ;
</code>```

then use UNION ALL to combine those result as below

Query #1

```<code>SELECT SPLIT_STR(genres, ',', 1) genre  FROM T
UNION ALL
SELECT SPLIT_STR(genres, ',', 2) FROM T
UNION ALL
SELECT SPLIT_STR(genres, ',', 3) FROM T;
</code>```

genre

action

adventure

drama

View on DB Fiddle

NOTE

I would suggest you re-design your table scheme because it was bad for store value by comma and you need to convert as rows.

Body:
ex:

the column 'genre' has a row of data:

+----------------------------+
|            genres          |
+----------------------------+
|   action, adventure, drama |       |
|                            |
+----------------------------+

my desired output will be a column that holds the following data:

+------------+
|    genre   |
+------------+
| action     |
| adventure  |
| drama      |
+------------+

how do I do it in mysql?

Body:
You can try to create a split function as below to get your expectation part of values by comma.

Schema (MySQL v5.7)

DELIMITER $$
DROP FUNCTION IF EXISTS `SPLIT_STR` $$
CREATE FUNCTION `SPLIT_STR`(
  x VARCHAR(255),
  delim VARCHAR(12),
  pos INT
) RETURNS varchar(255) CHARSET latin1
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
       LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
       delim, '') $$

DELIMITER ;

then use UNION ALL to combine those result as below

Query #1

SELECT SPLIT_STR(genres, ',', 1) genre  FROM T
UNION ALL
SELECT SPLIT_STR(genres, ',', 2) FROM T
UNION ALL
SELECT SPLIT_STR(genres, ',', 3) FROM T;

genre

action

adventure

drama

View on DB Fiddle

NOTE

I would suggest you re-design your table scheme because it was bad for store value by comma and you need to convert as rows.


问:
Different results came from different editor in terms of .this keyword
Everyone.
I am learning javascript. I ran this code: (below)

```<code>function x(){
  return this;
}

console.log(x() === global);
</code>```

in Atom editor, then got a result which was "false". (please see my added picture)
However, I turned to another online editor to run the same code then got the result "true" ! (please see my added picture)

My question one is : Is it Atom's problem leading to different results ?

My question one two : I heard that "===" is named strict equality, which means it will be "false" if left operand is different with right operand. But, in the code I just have posted, in this line "(x() === global)", the result is "true" while the left operand and the right operand are certainly different, so what is wrong with it, is it that I am still not learning about some fundamental concepts?

Waiting for your answer Hopefully!

答:
in "sloppy mode" this keyword in a function refers to the global object. while in strict mode its value is undefined.
I'm not sure about your editor's settings but I would say both are correct depending on the settings.
It could be that atom sets strict mode by default while the other editor doesn't.

More on what is strict mode and what does it effect and why it is used for in MDN documentation

Body:
Everyone.
I am learning javascript. I ran this code: (below)

function x(){
  return this;
}

console.log(x() === global);

in Atom editor, then got a result which was "false". (please see my added picture)
However, I turned to another online editor to run the same code then got the result "true" ! (please see my added picture)

My question one is : Is it Atom's problem leading to different results ?

My question one two : I heard that "===" is named strict equality, which means it will be "false" if left operand is different with right operand. But, in the code I just have posted, in this line "(x() === global)", the result is "true" while the left operand and the right operand are certainly different, so what is wrong with it, is it that I am still not learning about some fundamental concepts?

Waiting for your answer Hopefully!


问:
How to create an in-place sorting algorithm with faster than O (nlogn) time complexity?
I was recently asked to create an in-place sorting algorithm in an interview. The follow up was to code it up to make it faster than O(n logn), discuss the time complexity of every loop.

I understand that insertion sort, bubble sort, heap sort, quicksort, and shell sort are all in-place, however which of these can be modified to have better time complexity?

答:
A comparison based sort cannot be faster than O(nlogn). Since all the algorithms you mentioned are comparison based, none of them can have better time complexity.
There are algorithms like bucket sort and radix sort that can achieve O(n) in some cases, namely if the input is uniformly distributed.</p>


问:
Unreal Engine 5 Puzzle Example Block Spacing has no effect
I've recently begun toying with Unreal Engine (UE5 Early Access) and I started with the Puzzle Example Template. In the PuzzleBlockGrid blueprint, there is a variable called BlockSpacing that is used to calculate the (X,Y) coordinates a block before spawning it.

This is the blueprint.

I collapsed the logic for calculating the position to tidy up the graph a bit. I've highlighted the path to the variable in question.

Changing the value of Block Spacing has no effect on the placement of the blocks. I have verified this by printing the calculated values to the screen (not shown in pictures). I have tried changing Block Spacing to a wide range of values (10^10, 1, 0, 10^-10, -100: Default was 400). No matter the value entered, the calculated values are always the same. The only way I could get a different result is to bypass the Block Spacing and Multiply nodes; in which case, all positions are calculated to be (0,0).

Am I missing something?

Just FYI the calculated coordinates that I get are:

答: I realized that this is happening because Block Spacing is public and the value was set in the level map's viewport editor details pain, which overrides the initial value set in the blueprint.


问:
R: Finding code with authors' comments, if any
Is there any reasonably simple, straightforward function along the line of getAnywhere() which returns the source code of a function with any comments, such that if I see no comments I can be confident that there are none, whether the code is in R,  c, c++, Fortran, or something else? For example, stats:::plot.acf does not seem to have any comments in it. Can I conclude from this that there are no comments on its text?

I understand that there is a flowchart-like search process where if you know that source is written in R, then that source including comments is available from a specific github repository via some search method appropriate tp gethub. Also if you have determined that code is in some specified other language it is available via a more elaborate search process that involves finding the correct file and then doing text search within it, different for base and contributed packages. I am under the impression that at least until recently there was no shortcut to learning and working your way through that implicit flowchart search method if you wanted to learn whether there is a version of the code which contains comments. Moreover, I believe that that versions of the code which do or don't contain comments were nowhere identified as such, except by the comments themselves or by prior knowledge.

However, R is a pretty rapidly evolving ecosystem and I don't think it is entirely unreasonable to hope that simpler tools for determining whether there is a version of the source that includes comments, and finding it if there is, might now exist. Do they?

答:
Whether the source code of an R function is preserved internally (via its srcref attribute) depends on the value of option keep.source when the function is defined. By source code, I mean the code as entered by the user, with comments, possibly inconsistent indentation, possibly inconsistent spacing around operators, etc.

options(keep.source = FALSE)
f <- function(x) {
    ## A comment
        x +
  1}

getSrcref(f)
## NULL # (invisibly)

deparse(f, control = "all")
## [1] "function (x) "
## [2] "{"
## [3] "    x + 1"
## [4] "}"
```
<pre class="lang-r prettyprint-override"><code>options(keep.source = TRUE)
g <- function(x) {
    ## A comment
        x +
  1}

getSrcref(g)
## function(x) {
##     ## A comment
##         x +
##   1}

deparse(g, control = "all")
## [1] "function(x) {"
## [2] "    ## A comment"
## [3] "        x +"
## [4] "  1}"
</code>```

Whether functions in a contributed package retain their source code depends on options passed to R CMD INSTALL when the package was built from sources (by you or by CRAN). The default is to discard source code, but you can avoid that by installing from sources and setting the --with-keep.source flag:

install.packages(pkgs, type = "source", INSTALL_opts = "--with-keep.source")
```
<p>Functions in base packages (<code>base</code>, <code>stats</code>, etc.) won't have their source code unless you build R itself from sources with environment variable <code>R_KEEP_PKG_SOURCE</code> set to <code>yes</code>—at least, that is what I infer from <code>?options</code>. To learn about building R, see the corresponding manual.</p>
<p>Given a function <em>with source references</em>, you can programmatically extract comments from the source code. A quick and dirty approach is pattern matching:</p>
<pre class="lang-r prettyprint-override"><code>zzz <- deparse(g, control = "all")
grep("#", zzz, value = TRUE)
## [1] "    ## A comment"
</code>```

There can be false positives, though, because the pattern # also matches strings and non-syntactic names containing the hash character, which aren't comments at all.

grep("#", "\"## Not a comment\"", value = TRUE)
## [1] "\"## Not a comment\""
```
<p>A much more robust way to extract comments is to examine the parse data for tokens of type <code>COMMENT</code>:</p>
<pre class="lang-r prettyprint-override"><code>getParseData(parse(text = zzz), includeText = NA)
##    line1 col1 line2 col2 id parent          token terminal         text
## 23     1    1     4    4 23      0           expr    FALSE
## 1      1    1     1    8  1     23       FUNCTION     TRUE     function
## 2      1    9     1    9  2     23            '('     TRUE            (
## 3      1   10     1   10  3     23 SYMBOL_FORMALS     TRUE            x
## 4      1   11     1   11  4     23            ')'     TRUE            )
## 20     1   13     4    4 20     23           expr    FALSE
## 6      1   13     1   13  6     20            '{'     TRUE            {
## 8      2    5     2   16  8     20        COMMENT     TRUE ## A comment
## 17     3    9     4    3 17     20           expr    FALSE
## 10     3    9     3    9 10     12         SYMBOL     TRUE            x
## 12     3    9     3    9 12     17           expr    FALSE
## 11     3   11     3   11 11     17            '+'     TRUE            +
## 14     4    3     4    3 14     15      NUM_CONST     TRUE            1
## 15     4    3     4    3 15     17           expr    FALSE
## 16     4    4     4    4 16     20            '}'     TRUE            }
</code>```

Clearly, getParseData returns much more information than you need. Here is a utility that you can use instead, which takes as an argument a function with source references and returns a character vector listing the comments, if any:

getComments <- function(func) {
    func <- match.fun(func)
    if (is.null(getSrcref(func))) {
        stop("'func' has no source references")
    }
    data <- getParseData(func, includeText = NA)
    if (is.null(data)) {
        op <- options(keep.source = TRUE, keep.parse.data = TRUE)
        on.exit(options(op))
        expr <- parse(text = deparse(func, control = "all"))
        data <- getParseData(expr, includeText = NA)
    }
    data$text[data$token == "COMMENT"]
}
```
<pre class="lang-r prettyprint-override"><code>getComments(g)
## [1] "## A comment"

h <- function(x) {
    ## I will comment
            ##     anywhere
    ######## and with as many hashes
    x + 1 # as I want!
}

getComments(h)
## [1] "## I will comment"
## [2] "##     anywhere"
## [3] "######## and with as many hashes"
## [4] "# as I want!"

## You will need Rtools on Windows and Command Line Tools on macOS
## to install from sources packages containing C/C++/Fortran code.
## 'lme4' is one such package ... feel free to choose a different one.
install.packages("lme4", type = "source", INSTALL_opts = "--with-keep.source")
getComments(lme4::lmer)
##  [1] "## , ...)"
##  [2] "## see functions in modular.R for the body .."
##  [3] "## back-compatibility kluge"
##  [4] "## if (!is.null(list(...)[[\"family\"]])) {"
##  [5] "##    warning(\"calling lmer with 'family' is deprecated; please use glmer() instead\")"
##  [6] "##    mc[[1]] <- quote(lme4::glmer)"
##  [7] "##    if(missCtrl) mc$control <- glmerControl()"
##  [8] "##    return(eval(mc, parent.frame(1L)))"
##  [9] "## }"
## [10] "## update for  back-compatibility kluge"
## [11] "## https://github.com/lme4/lme4/issues/50"
## [12] "## parse data and formula"
## [13] "## create deviance function for covariance parameters (theta)"
## [14] "## optimize deviance function over covariance parameters"
## [15] "## prepare output"
</code>```

AFAIK, there is no convenient mechanism for checking whether C code called by an R function contained comments before it was compiled...

Relevant documentation is a bit scattered, as always. I have found these help pages useful: ?parse, ?deparse, ?.deparseOpts, ?srcref (and links therein), ?options, and ?getParseData.

Body:
Whether the source code of an R function is preserved internally (via its srcref attribute) depends on the value of option keep.source when the function is defined. By source code, I mean the code as entered by the user, with comments, possibly inconsistent indentation, possibly inconsistent spacing around operators, etc.

options(keep.source = FALSE)
f <- function(x) {
    ## A comment
        x +
  1}

getSrcref(f)
## NULL # (invisibly)

deparse(f, control = "all")
## [1] "function (x) "
## [2] "{"
## [3] "    x + 1"
## [4] "}"

options(keep.source = TRUE)
g <- function(x) {
    ## A comment
        x +
  1}

getSrcref(g)
## function(x) {
##     ## A comment
##         x +
##   1}

deparse(g, control = "all")
## [1] "function(x) {"
## [2] "    ## A comment"
## [3] "        x +"
## [4] "  1}"

Whether functions in a contributed package retain their source code depends on options passed to R CMD INSTALL when the package was built from sources (by you or by CRAN). The default is to discard source code, but you can avoid that by installing from sources and setting the --with-keep.source flag:

install.packages(pkgs, type = "source", INSTALL_opts = "--with-keep.source")

Functions in base packages (base, stats, etc.) won't have their source code unless you build R itself from sources with environment variable R_KEEP_PKG_SOURCE set to yes—at least, that is what I infer from ?options. To learn about building R, see the corresponding manual.

Given a function with source references, you can programmatically extract comments from the source code. A quick and dirty approach is pattern matching:

zzz <- deparse(g, control = "all")
grep("#", zzz, value = TRUE)
## [1] "    ## A comment"

There can be false positives, though, because the pattern # also matches strings and non-syntactic names containing the hash character, which aren't comments at all.

grep("#", "\"## Not a comment\"", value = TRUE)
## [1] "\"## Not a comment\""

A much more robust way to extract comments is to examine the parse data for tokens of type COMMENT:

getParseData(parse(text = zzz), includeText = NA)
##    line1 col1 line2 col2 id parent          token terminal         text
## 23     1    1     4    4 23      0           expr    FALSE
## 1      1    1     1    8  1     23       FUNCTION     TRUE     function
## 2      1    9     1    9  2     23            '('     TRUE            (
## 3      1   10     1   10  3     23 SYMBOL_FORMALS     TRUE            x
## 4      1   11     1   11  4     23            ')'     TRUE            )
## 20     1   13     4    4 20     23           expr    FALSE
## 6      1   13     1   13  6     20            '{'     TRUE            {
## 8      2    5     2   16  8     20        COMMENT     TRUE ## A comment
## 17     3    9     4    3 17     20           expr    FALSE
## 10     3    9     3    9 10     12         SYMBOL     TRUE            x
## 12     3    9     3    9 12     17           expr    FALSE
## 11     3   11     3   11 11     17            '+'     TRUE            +
## 14     4    3     4    3 14     15      NUM_CONST     TRUE            1
## 15     4    3     4    3 15     17           expr    FALSE
## 16     4    4     4    4 16     20            '}'     TRUE            }

Clearly, getParseData returns much more information than you need. Here is a utility that you can use instead, which takes as an argument a function with source references and returns a character vector listing the comments, if any:

getComments <- function(func) {
    func <- match.fun(func)
    if (is.null(getSrcref(func))) {
        stop("'func' has no source references")
    }
    data <- getParseData(func, includeText = NA)
    if (is.null(data)) {
        op <- options(keep.source = TRUE, keep.parse.data = TRUE)
        on.exit(options(op))
        expr <- parse(text = deparse(func, control = "all"))
        data <- getParseData(expr, includeText = NA)
    }
    data$text[data$token == "COMMENT"]
}

getComments(g)
## [1] "## A comment"

h <- function(x) {
    ## I will comment
            ##     anywhere
    ######## and with as many hashes
    x + 1 # as I want!
}

getComments(h)
## [1] "## I will comment"
## [2] "##     anywhere"
## [3] "######## and with as many hashes"
## [4] "# as I want!"

## You will need Rtools on Windows and Command Line Tools on macOS
## to install from sources packages containing C/C++/Fortran code.
## 'lme4' is one such package ... feel free to choose a different one.
install.packages("lme4", type = "source", INSTALL_opts = "--with-keep.source")
getComments(lme4::lmer)
##  [1] "## , ...)"
##  [2] "## see functions in modular.R for the body .."
##  [3] "## back-compatibility kluge"
##  [4] "## if (!is.null(list(...)[[\"family\"]])) {"
##  [5] "##    warning(\"calling lmer with 'family' is deprecated; please use glmer() instead\")"
##  [6] "##    mc[[1]] <- quote(lme4::glmer)"
##  [7] "##    if(missCtrl) mc$control <- glmerControl()"
##  [8] "##    return(eval(mc, parent.frame(1L)))"
##  [9] "## }"
## [10] "## update for  back-compatibility kluge"
## [11] "## https://github.com/lme4/lme4/issues/50"
## [12] "## parse data and formula"
## [13] "## create deviance function for covariance parameters (theta)"
## [14] "## optimize deviance function over covariance parameters"
## [15] "## prepare output"

AFAIK, there is no convenient mechanism for checking whether C code called by an R function contained comments before it was compiled...

Relevant documentation is a bit scattered, as always. I have found these help pages useful: ?parse, ?deparse, ?.deparseOpts, ?srcref (and links therein), ?options, and ?getParseData.


问:
Navigate to another screen - 'navigation.navigate' is not a function
I am trying to navigate from Screen1 to Screen2. Screen1 is being rendered in my Home screen. So far I have tried using this.props.navigation.navigate as well as what you see currently implemented.

I have created a snack expo here that recreates the exact error as well as posted some code below.

Thank you for any insight at all, I appreciate it more than you know.

EDIT:: this needs to be ran on IOS and I am using react-native-navigation

App.js

```<code> /*passing props to home is from my overall project, I left it in incase it impacted the answer*/
<Stack.Navigator initialRouteName="Home">
      <Stack.Screen name="HomeScreen" options={{ headerShown: false }}>
        {(props) => (
          <Home {...props}/>
        )}
      </Stack.Screen>
       <Stack.Screen
        name="Screen1"
        component={Screen1}
        options={{ headerShown: false }}
      />
      <Stack.Screen
        name="Screen2"
        component={Screen2}
        options={{ headerShown: false }}
      />
  </Stack.Navigator>
);
}

export default function App() {

  return (
<NavigationContainer>
  <MyTabs/>
</NavigationContainer>
);
</code>```

Screen1

```<code>export default class Screen1 extends React.Component {
  renderList = (props, navigation) => {
    return List.map((item, i) => {
      return (
        <View
        key={List.name}
          style={{
            width: windowWidth,
            height: scale(100),
            paddingLeft: scale(10)
          }}>
          <TouchableOpacity
            onPress={() => this.props.navigation.navigate('Screen2')}
            activeOpacity={0.7}>
                <Text style={{fontSize: 20}}>{item.name}</Text>
          </TouchableOpacity>
        </View>
      );
    });
  };

  render() {
  return (
      <View style={{top: scale(50)}}>

          <ScrollView style={{ height: windowHeight }}>
            <this.renderList />
          </ScrollView>

      </View>
    );
  }
}

</code>```

答:
In Screen 1

```<code>renderList = (props) => {
return List.map((item, i) => {
  return (
    <View
    key={List.name}
      style={{
        width: windowWidth,
        height: scale(100),
        paddingLeft: scale(10)
      }}>
      <TouchableOpacity
        onPress={() => this.props.navigation.navigate('Screen2')}
        activeOpacity={0.7}>
            <Text style={{fontSize: 20}}>{item.name}</Text>
      </TouchableOpacity>
    </View>
  );
});
</code>```

in Home

```<code>const Home = (props) => {

return (
<View>
    <Screen1 {...props}/>
</View>

);
</code>```

}

And in App

```<code><Tab.Navigator initialRouteName="Home">
  <Tab.Screen name="Home" options={{ headerShown: false }} component={Home}/>

   <Tab.Screen
    name="Screen1"
    component={Screen1}
    options={{ headerShown: false }}
  />

  <Tab.Screen
    name="Screen2"
    component={Screen2}
    options={{ headerShown: false }}
  />
</code>```

</Tab.Navigator>

And for me working perfectly (I take some capture but I'm not authorized yet, new user...)

Say me

Body:
I am trying to navigate from Screen1 to Screen2. Screen1 is being rendered in my Home screen. So far I have tried using this.props.navigation.navigate as well as what you see currently implemented.

I have created a snack expo here that recreates the exact error as well as posted some code below.

Thank you for any insight at all, I appreciate it more than you know.

EDIT:: this needs to be ran on IOS and I am using react-native-navigation

App.js

 /*passing props to home is from my overall project, I left it in incase it impacted the answer*/
<Stack.Navigator initialRouteName="Home">
      <Stack.Screen name="HomeScreen" options={{ headerShown: false }}>
        {(props) => (
          <Home {...props}/>
        )}
      </Stack.Screen>
       <Stack.Screen
        name="Screen1"
        component={Screen1}
        options={{ headerShown: false }}
      />
      <Stack.Screen
        name="Screen2"
        component={Screen2}
        options={{ headerShown: false }}
      />
  </Stack.Navigator>
);
}

export default function App() {

  return (
<NavigationContainer>
  <MyTabs/>
</NavigationContainer>
);

Screen1

export default class Screen1 extends React.Component {
  renderList = (props, navigation) => {
    return List.map((item, i) => {
      return (
        <View
        key={List.name}
          style={{
            width: windowWidth,
            height: scale(100),
            paddingLeft: scale(10)
          }}>
          <TouchableOpacity
            onPress={() => this.props.navigation.navigate('Screen2')}
            activeOpacity={0.7}>
                <Text style={{fontSize: 20}}>{item.name}</Text>
          </TouchableOpacity>
        </View>
      );
    });
  };

  render() {
  return (
      <View style={{top: scale(50)}}>

          <ScrollView style={{ height: windowHeight }}>
            <this.renderList />
          </ScrollView>

      </View>
    );
  }
}

Body:
In Screen 1

renderList = (props) => {
return List.map((item, i) => {
  return (
    <View
    key={List.name}
      style={{
        width: windowWidth,
        height: scale(100),
        paddingLeft: scale(10)
      }}>
      <TouchableOpacity
        onPress={() => this.props.navigation.navigate('Screen2')}
        activeOpacity={0.7}>
            <Text style={{fontSize: 20}}>{item.name}</Text>
      </TouchableOpacity>
    </View>
  );
});

in Home

const Home = (props) => {

return (
<View>
    <Screen1 {...props}/>
</View>

);

}

And in App

<Tab.Navigator initialRouteName="Home">
  <Tab.Screen name="Home" options={{ headerShown: false }} component={Home}/>

   <Tab.Screen
    name="Screen1"
    component={Screen1}
    options={{ headerShown: false }}
  />

  <Tab.Screen
    name="Screen2"
    component={Screen2}
    options={{ headerShown: false }}
  />

</Tab.Navigator>

And for me working perfectly (I take some capture but I'm not authorized yet, new user...)

Say me


问:
Possible Bug - Asp.net Routing Localization strange problem with Thread
I have two Pages A and B. Both should display a Text using the appropriate Global Resource depending on the Culture setting in Web.Conf.

On Page A I'm able to visualize the text accordingly to the Culture setting (so in this case French).

Page A  has also a Link which use GetUrl to create an Url (Routing) to Page B

```<code><asp:HyperLink
           runat="server"
           Text='<%# Eval("Title") %>'
           NavigateUrl='<%# GetRouteUrl("TopicHub", new {TitleUrl = Eval("TitleUrl")}) %>'>
</asp:HyperLink>
</code>```

At the moment of visit Page B I'm not able to see the Literal in French anymore and Text in English is applied (Default value).
The strange thing is if I open Page B directly in the Browser the Literal displays in French.

So I debugged the Global.asax.cs and I found out the at the moment of Clicking the Link created with GetRouteUrl the var Thread.CurrentThread.CurrentCulture and CurrentUICulture are in English and not in French as for my Web.Config.

MY Questions are:

What could be the problem here? Maybe a bug?

Any idea how to fix it?

I'm running out of ideas so as last thought would be to force in Global.asax.cs the Thread.CurrentThread.CurrentCulture using the value in Web.Conf.

Please let me know your thoughts on this. Thanks!

Page A:

```<code><asp:Literal ID="uxLatestGuides"
             runat="server"
             Text="<%$ Resources:Global, LatestGuides %>" />
</code>```

Page B:

```<code><asp:Literal ID="uxLatestGuides"
             runat="server"
             Text="<%$ Resources:Global, LatestGuides %>" />
</code>```

Global.asax.cs

```<code>protected void Application_BeginRequest(object sender, EventArgs e)
{
  var check1 = Thread.CurrentThread.CurrentCulture;
  var check2 = Thread.CurrentThread.CurrentUICulture;
}
</code>```

Web.Config

```<code><?xml version="1.0"?>
    <configuration>
        <system.web>
            <pages enableViewState="false" theme="Cms-FE-00" >
            </pages>
            <globalization culture="fr" uiCulture="fr"/>
        </system.web>
    </configuration>
</code>```

答:
I was able to find the solution to this problem.

Analyzing the Global.asax.cs Routes I notice the virtual URL topic/{TitleUrl} that will map to the physical Url ~/Cms/FrontEndCms/CategoryList.aspx

```<code> routes.MapPageRoute("TopicHub", "topic/{TitleUrl}", "~/Cms/FrontEndCms/CategoryList.aspx");
</code>```

In my specif case I had the Web.Config file in ~/Cms/FrontEndCms/ so when a link would be created on the a Routed URL page like mysite.com/topic/my-page the Web.Config would not be in the right place but in another Folder so my Culture setting would not apply.

The solution was to move Web.Config to the ROOT for my website so it will apply on all Routes. Hopes can help some one else.

Body:
I have two Pages A and B. Both should display a Text using the appropriate Global Resource depending on the Culture setting in Web.Conf.

On Page A I'm able to visualize the text accordingly to the Culture setting (so in this case French).

Page A  has also a Link which use GetUrl to create an Url (Routing) to Page B

<asp:HyperLink
           runat="server"
           Text='<%# Eval("Title") %>'
           NavigateUrl='<%# GetRouteUrl("TopicHub", new {TitleUrl = Eval("TitleUrl")}) %>'>
</asp:HyperLink>

At the moment of visit Page B I'm not able to see the Literal in French anymore and Text in English is applied (Default value).
The strange thing is if I open Page B directly in the Browser the Literal displays in French.

So I debugged the Global.asax.cs and I found out the at the moment of Clicking the Link created with GetRouteUrl the var Thread.CurrentThread.CurrentCulture and CurrentUICulture are in English and not in French as for my Web.Config.

MY Questions are:

What could be the problem here? Maybe a bug?

Any idea how to fix it?

I'm running out of ideas so as last thought would be to force in Global.asax.cs the Thread.CurrentThread.CurrentCulture using the value in Web.Conf.

Please let me know your thoughts on this. Thanks!

Page A:

<asp:Literal ID="uxLatestGuides"
             runat="server"
             Text="<%$ Resources:Global, LatestGuides %>" />

Page B:

<asp:Literal ID="uxLatestGuides"
             runat="server"
             Text="<%$ Resources:Global, LatestGuides %>" />

Global.asax.cs

protected void Application_BeginRequest(object sender, EventArgs e)
{
  var check1 = Thread.CurrentThread.CurrentCulture;
  var check2 = Thread.CurrentThread.CurrentUICulture;
}

Web.Config

<?xml version="1.0"?>
    <configuration>
        <system.web>
            <pages enableViewState="false" theme="Cms-FE-00" >
            </pages>
            <globalization culture="fr" uiCulture="fr"/>
        </system.web>
    </configuration>

Body:
I was able to find the solution to this problem.

Analyzing the Global.asax.cs Routes I notice the virtual URL topic/{TitleUrl} that will map to the physical Url ~/Cms/FrontEndCms/CategoryList.aspx

 routes.MapPageRoute("TopicHub", "topic/{TitleUrl}", "~/Cms/FrontEndCms/CategoryList.aspx");

In my specif case I had the Web.Config file in ~/Cms/FrontEndCms/ so when a link would be created on the a Routed URL page like mysite.com/topic/my-page the Web.Config would not be in the right place but in another Folder so my Culture setting would not apply.

The solution was to move Web.Config to the ROOT for my website so it will apply on all Routes. Hopes can help some one else.


问:
how to make testText to text text in typescript
this is my first question so if I make mistakes I'm really sorry

I have a variable called foo and it contains the string "helloWorld"
is there any way to make it to "hello world" like how unity does with the variables in the script

Im using typescript btw

and Thanks

答:
A simple regex replace should do the trick for you:

"fooBarBaz".replace(/[A-Z]/g, (m) => " " + m.toLowerCase());
// "foo bar baz"
```


问:
how can i access the path and see the message of an error returned using JOI validation
i'm trying to use joi validation method and i can't access the path or message returned from the object
i tried to follow some videos to know more yet no effects the whole problem is that i can't access the joi object though it's consoled correctly</p>
```<code>    state ={
    username : "",
    password : "",
    errors :{}
};

schema =Joi.object().keys({
    username: Joi.string().required(),
    password:Joi.string().required()
})

validate = ()=>{
    const errors = {};
            const res = Joi.validate(this.state,this.schema,{abortEarly:false});
    console.log(res);
    if (res.error===null ){
        this.setState({errors:{}});
        return null;
    }
    // this is where i get the error and can't access it
    for (const error of res.error.details){
        errors[error.path] = error.message;
    }
    this.setState({errors});

}
handleSubmit=(e)=>{
    e.preventDefault();
    const errors = this.validate();
    if(errors){return}
    else{
        //call backend
        console.log("Passed");
    }
}
</code>```

答:
Hopefully you have already figured it out now However, just in case,  if you are using the lastest version of Joi, then if you look at the document, you will find the validate method now is being called on the schema, not the Joi object itself, which means you can do it like
Schema. validate() instead of Joi.validate().  Alright, happy coding :)</p>

Body:
i'm trying to use joi validation method and i can't access the path or message returned from the object
i tried to follow some videos to know more yet no effects the whole problem is that i can't access the joi object though it's consoled correctly

    state ={
    username : "",
    password : "",
    errors :{}
};

schema =Joi.object().keys({
    username: Joi.string().required(),
    password:Joi.string().required()
})

validate = ()=>{
    const errors = {};
            const res = Joi.validate(this.state,this.schema,{abortEarly:false});
    console.log(res);
    if (res.error===null ){
        this.setState({errors:{}});
        return null;
    }
    // this is where i get the error and can't access it
    for (const error of res.error.details){
        errors[error.path] = error.message;
    }
    this.setState({errors});

}
handleSubmit=(e)=>{
    e.preventDefault();
    const errors = this.validate();
    if(errors){return}
    else{
        //call backend
        console.log("Passed");
    }
}


问:
How to enter more than 1 value in an array in C/AL Microsoft NAV?
I want to enter more than one value in an array in C/AL without having to use many lines.
It will only set the values in a array like this:

```<code>numbers[1] := 5;
numbers[2] := 20;
numbers[3] := 12;
numbers[4] := 9;
</code>```

But I want to know if there is any Java-like way to introduce them like this:

```<code>int[] numbers = {5, 20, 12, 9};
</code>```

答:
Nope. You can't do things like that in neither c/al nor al.

There are tons of syntax sugar that won't work in Nav like in other mature languages. So if you new one, just run.

Body:
I want to enter more than one value in an array in C/AL without having to use many lines.
It will only set the values in a array like this:

numbers[1] := 5;
numbers[2] := 20;
numbers[3] := 12;
numbers[4] := 9;

But I want to know if there is any Java-like way to introduce them like this:

int[] numbers = {5, 20, 12, 9};


问:
How to declare const char* in .cpp file
There are many questions about declaring const string in .h files, this is not my case.

I need string (for serialization purposes if it is important) to use in

My current solution is

// file.cpp
static constexpr const char* const str = "some string key";

void MyClass::serialize()
{
    // using str
}

void MyClass::deserialize()
{
    // using str
}
```

Does it have any problems? (i.e. memory leaks, redefinitions, UB, side effects)?

P.S. is using #define KEY "key" could be better here (speed/memory/consistency)?

答:
Since you mentioned C++17, the best way to do this is with:

constexpr std::string_view str = "some string key";
```

str will be substituted by the compiler to the places where it is used at compile time.

Memory-wise you got rid of storing the str in run-time since it is only available at compile time.

Speed-wise this is also marginally better because less indirections to get the data in runtime.

Consistency-wise it is also even better since constexpr is solely used for expressions that are immutable and available at compile time. Also string_view is solely used for immutable strings so you are using the exact data type needed for you.

Title: How to declare const char* in .cpp file

Body:
There are many questions about declaring const string in .h files, this is not my case.

I need string (for serialization purposes if it is important) to use in

My current solution is

// file.cpp
static constexpr const char* const str = "some string key";

void MyClass::serialize()
{
    // using str
}

void MyClass::deserialize()
{
    // using str
}

Does it have any problems? (i.e. memory leaks, redefinitions, UB, side effects)?

P.S. is using #define KEY "key" could be better here (speed/memory/consistency)?

Body:
Since you mentioned C++17, the best way to do this is with:

constexpr std::string_view str = "some string key";

str will be substituted by the compiler to the places where it is used at compile time.

Memory-wise you got rid of storing the str in run-time since it is only available at compile time.

Speed-wise this is also marginally better because less indirections to get the data in runtime.

Consistency-wise it is also even better since constexpr is solely used for expressions that are immutable and available at compile time. Also string_view is solely used for immutable strings so you are using the exact data type needed for you.


问:
Onelogin SAML implementation with other IDP that accepts SAML
Does the sample Onelogin SAML implementation, work with any other IDP that accepts SAML?</p>

答:
I am answering your question - is there a generic way we can SAML enable an application.... As you stated you are on .Net platform then one of the ways you could saml enable is by using a saml library provided by a third party. e.g. google search gives ComponentPro who provide a saml library for .net platform. Disclaimer- I have not used their product, just providing a reference.
In summary, your application will effectively become a Service Provider once it integrates with the saml library. Now your Service Provider (the .net application) can communicate with the remote IDP, Identity Provider using saml protocol. This will enable you to deploy your app (.Net app) in a IdP app repository as you stated in your question.
If you have any further questions let us know.</p>