问:
What guarantees that different unrelated objects in two unrelated threads don't have an (unavoidable) race condition?
When different threads only use unrelated objects and literally do not share anything they cannot have a race condition, right? Obviously.

Actually all threads share something: the address space. There is no guarantee that a memory location that was used by one thread isn't going to be allocated at some other time to another thread. This can be true of memory for dynamically allocated objects or even for automatic objects: there is no prescription that the memory space for the "stacks" (the local objects of functions) of multiple threads is pre-allocated (even lazily), disjoint and represented as the usual linear "stack"; it could be anything with stack (FILO) behavior. So the memory location used to store an automatic object can be reused later by another automatic object in another thread.

That in itself seems pretty innocuous and uninteresting as how room is made for automatic objects is only important when room is missing (very large automatic arrays or deep recursion).

What about synchronisation? Unrelated disjoint threads obviously cannot use any C++ synchronisation primitive to ensure correct synchronisation as by definition there is nothing (to) synchronize (on), so no happens before relation is going to be created between threads.

What if the implementation reuses the memory range of the stack of foo() (including the location of i) after destruction of local variables and exit of foo() in thread 1 to store variables for bar() in thread 2?

```<code>void foo() { // in thread 1
   int i;
   i = 1;
}

void bar() { // in thread 2
   int i;
   i = 2;
}
</code>```

There is no happens before between i = 1 and i = 2.

Would that cause a data race and undefined behavior?

In other words, do all multithread programs have a potential for having undefined behavior based on implementation choices the user has no control over, that are unforeseeable and with races he can't do anything about?

答:
The C++ memory model doesn't behave like you might intuitively expect. For example, it has memory locations, but quoting the N4713 draft section 6.6.1, paragraph 3:

A memory location is either an object of scalar type or a maximal sequence of adjacent bit-fields all having
  nonzero width. [ Note: Various features of the language, such as references and virtual functions, might involve
  additional memory locations that are not accessible to programs but are managed by the implementation.
  — end note ] Two or more threads of execution (6.8.2) can access separate memory locations without interfering
  with each other.

So by the C++ memory model, two distinct objects in different threads are never considered to have the same memory location, even if at the physical machine level, one is allocated in the same RAM after the other is deallocated.

By the C++ memory model, the situation you ask about is not a data race. The implementation must take whatever steps are necessary to ensure this is safe, regardless of the hardware's memory model.

Body:
When different threads only use unrelated objects and literally do not share anything they cannot have a race condition, right? Obviously.

Actually all threads share something: the address space. There is no guarantee that a memory location that was used by one thread isn't going to be allocated at some other time to another thread. This can be true of memory for dynamically allocated objects or even for automatic objects: there is no prescription that the memory space for the "stacks" (the local objects of functions) of multiple threads is pre-allocated (even lazily), disjoint and represented as the usual linear "stack"; it could be anything with stack (FILO) behavior. So the memory location used to store an automatic object can be reused later by another automatic object in another thread.

That in itself seems pretty innocuous and uninteresting as how room is made for automatic objects is only important when room is missing (very large automatic arrays or deep recursion).

What about synchronisation? Unrelated disjoint threads obviously cannot use any C++ synchronisation primitive to ensure correct synchronisation as by definition there is nothing (to) synchronize (on), so no happens before relation is going to be created between threads.

What if the implementation reuses the memory range of the stack of foo() (including the location of i) after destruction of local variables and exit of foo() in thread 1 to store variables for bar() in thread 2?

void foo() { // in thread 1
   int i;
   i = 1;
}

void bar() { // in thread 2
   int i;
   i = 2;
}

There is no happens before between i = 1 and i = 2.

Would that cause a data race and undefined behavior?

In other words, do all multithread programs have a potential for having undefined behavior based on implementation choices the user has no control over, that are unforeseeable and with races he can't do anything about?


来源: stackexchange

问:
Powershell to look at log and send email notification
New to scripting. I need help creating a powershell script which will look at a log file and search for a keyword e.g. fail/unsuccessful, and the keyword is present, send an email of the last 50 lines.

I've got parts of the script working, but I am having trouble putting it together.

Looking at log and printing out the line

```<code>$PATH="C:\tmp\test.log"
Get-Content $PATH -Tail 50 | Where-Object { $_.Contains("fail") }
</code>```

Email to SMTP server sorted and working

```<code>$From = "test@foobar.com"
$To = "test2@foobar.com"

$Subject = "Failed notification"
$Body = "This is what I want to say"
$SMTPServer = "smtp.foobar.com"
$SMTPPort = "25"
Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -port $SMTPPort
</code>```

I know I need an IF statement to compare the content and set if true, send email.

Can someone help me?

答:
While you're learning it's probably easier to be explicit if you need to remind yourself what something will return.

```<code>[string] $PATH="C:\tmp\test.log"
[string[]] $failedRows = Get-Content $PATH -Tail 50 | Where-Object { $_.Contains("fail") }
# Email to SMTP server sorted and working

[string] $From = "test@foobar.com"
[string] $To = "test2@foobar.com"
[string] $Subject = "Failed notification"
[string] $Body = "This is what I want to say"
[string] $SMTPServer = "smtp.foobar.com"
[string] $SMTPPort = "25"
if( $failedRows -and $failedRows.Length -gt 0) {
    Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -port $SMTPPort
}
</code>```

Remember powershell is weakly typed. An editor like vscode with the powershell extension will help as well as you can see suggestions on how to improve your code.

```<code>$PATH="C:\tmp\test.log"
$failedRows = Get-Content $PATH -Tail 50 | Where-Object { $_.Contains("fail") }
# Email to SMTP server sorted and working

$From = "test@foobar.com"
$To = "test2@foobar.com"
$Subject = "Failed notification"
$Body = "This is what I want to say"
$SMTPServer = "smtp.foobar.com"
$SMTPPort = "25"
if( $failedRows -and $failedRows.Length -gt 0) {
    Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -port $SMTPPort
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
New to scripting. I need help creating a powershell script which will look at a log file and search for a keyword e.g. fail/unsuccessful, and the keyword is present, send an email of the last 50 lines.

I've got parts of the script working, but I am having trouble putting it together.

Looking at log and printing out the line

$PATH="C:\tmp\test.log"
Get-Content $PATH -Tail 50 | Where-Object { $_.Contains("fail") }

Email to SMTP server sorted and working

$From = "test@foobar.com"
$To = "test2@foobar.com"

$Subject = "Failed notification"
$Body = "This is what I want to say"
$SMTPServer = "smtp.foobar.com"
$SMTPPort = "25"
Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -port $SMTPPort

I know I need an IF statement to compare the content and set if true, send email.

Can someone help me?

Body:
While you're learning it's probably easier to be explicit if you need to remind yourself what something will return.

[string] $PATH="C:\tmp\test.log"
[string[]] $failedRows = Get-Content $PATH -Tail 50 | Where-Object { $_.Contains("fail") }
# Email to SMTP server sorted and working

[string] $From = "test@foobar.com"
[string] $To = "test2@foobar.com"
[string] $Subject = "Failed notification"
[string] $Body = "This is what I want to say"
[string] $SMTPServer = "smtp.foobar.com"
[string] $SMTPPort = "25"
if( $failedRows -and $failedRows.Length -gt 0) {
    Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -port $SMTPPort
}

Remember powershell is weakly typed. An editor like vscode with the powershell extension will help as well as you can see suggestions on how to improve your code.

$PATH="C:\tmp\test.log"
$failedRows = Get-Content $PATH -Tail 50 | Where-Object { $_.Contains("fail") }
# Email to SMTP server sorted and working

$From = "test@foobar.com"
$To = "test2@foobar.com"
$Subject = "Failed notification"
$Body = "This is what I want to say"
$SMTPServer = "smtp.foobar.com"
$SMTPPort = "25"
if( $failedRows -and $failedRows.Length -gt 0) {
    Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -port $SMTPPort
}


问:
Authenticate with ECE ElasticSearch Sink from Apache Fink (Scala code)
Compiler error when using example provided in Flink documentation. The Flink documentation provides sample Scala code to set the REST client factory parameters when talking to Elasticsearch, https://ci.apache.org/projects/flink/flink-docs-stable/dev/connectors/elasticsearch.html.
When trying out this code i get a compiler error in IntelliJ which says "Cannot resolve symbol restClientBuilder".

I found the following SO which is EXACTLY my problem except that it is in Java and i am doing this in Scala.
Apache Flink (v1.6.0) authenticate Elasticsearch Sink (v6.4)

I tried copy pasting the solution code provided in the above SO into IntelliJ, the auto-converted code also has compiler errors.

```<code>      // provide a RestClientFactory for custom configuration on the internally created REST client
      // i only show the setMaxRetryTimeoutMillis for illustration purposes, the actual code will use HTTP cutom callback
      esSinkBuilder.setRestClientFactory(
        restClientBuilder -> {
          restClientBuilder.setMaxRetryTimeoutMillis(10)
        }
      )
</code>```

Then i tried (auto generated Java to Scala code by IntelliJ)

```<code>// provide a RestClientFactory for custom configuration on the internally created REST client// provide a RestClientFactory for custom configuration on the internally created REST client
      import org.apache.http.auth.AuthScope
      import org.apache.http.auth.UsernamePasswordCredentials
      import org.apache.http.client.CredentialsProvider
      import org.apache.http.impl.client.BasicCredentialsProvider
      import org.apache.http.impl.nio.client.HttpAsyncClientBuilder
      import org.elasticsearch.client.RestClientBuilder
      // provide a RestClientFactory for custom configuration on the internally created REST client// provide a RestClientFactory for custom configuration on the internally created REST client

      esSinkBuilder.setRestClientFactory((restClientBuilder) => {
        def foo(restClientBuilder) = restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
          override def customizeHttpClient(httpClientBuilder: HttpAsyncClientBuilder): HttpAsyncClientBuilder = { // elasticsearch username and password
            val credentialsProvider = new BasicCredentialsProvider
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(es_user, es_password))
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
          }
        })

        foo(restClientBuilder)
      })
</code>```

The original code snippet produces the error "cannot resolve RestClientFactory" and then Java to Scala shows several other errors.

So basically i need to find a Scala version of the solution described in Apache Flink (v1.6.0) authenticate Elasticsearch Sink (v6.4)

Update 1: I was able to make some progress with some help from IntelliJ. The following code compiles and runs but there is another problem.

```<code>esSinkBuilder.setRestClientFactory(
          new RestClientFactory {
            override def configureRestClientBuilder(restClientBuilder: RestClientBuilder): Unit = {
              restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                override def customizeHttpClient(httpClientBuilder: HttpAsyncClientBuilder): HttpAsyncClientBuilder = {
                  // elasticsearch username and password
                  val credentialsProvider = new BasicCredentialsProvider
                  credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(es_user, es_password))
                  httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
                  httpClientBuilder.setSSLContext(trustfulSslContext)
                }
              })
            }
          }
</code>```

The problem is that i am not sure if i should be doing a new of the RestClientFactory object. What happens is that the application connects to the elasticsearch cluster but then discovers that the SSL CERT is not valid, so i had to put the trustfullSslContext (as described here https://gist.github.com/iRevive/4a3c7cb96374da5da80d4538f3da17cb), this got me past the SSL issue but now the ES REST Client does a ping test and the ping fails, it throws an exception and the app shutsdown. I am suspecting that the ping fails because of the SSL error and maybe it is not using the trustfulSslContext i setup as part of new RestClientFactory and this makes me suspect that i should not have done the new, there should be a simple way to update the existing RestclientFactory object and basically this is all happening because of my lack of Scala knowledge.

答:
Happy to report that this is resolved. The code i posted in Update 1 is correct. The ping to ECE was not working for two reasons:

The certificate needs to include the complete chain including the root CA, the intermediate CA and the cert for the ECE. This helped get rid of the whole trustfulSslContext stuff.

The ECE was sitting behind an ha-proxy and the proxy did the mapping for the hostname in the HTTP request to the actual deployment cluster name in ECE. this mapping logic did not take into account that the Java REST High Level client uses the org.apache.httphost class which creates the hostname as hostname:port_number even when the port number is 443. Since it did not find the mapping because of the 443 therefore the ECE returned a 404 error instead of 200 ok (only way to find this was to look at unencrypted packets at the ha-proxy). Once the mapping logic in ha-proxy was fixed, the mapping was found and the pings are now successfull.

Body:
Compiler error when using example provided in Flink documentation. The Flink documentation provides sample Scala code to set the REST client factory parameters when talking to Elasticsearch, https://ci.apache.org/projects/flink/flink-docs-stable/dev/connectors/elasticsearch.html.
When trying out this code i get a compiler error in IntelliJ which says "Cannot resolve symbol restClientBuilder".

I found the following SO which is EXACTLY my problem except that it is in Java and i am doing this in Scala.
Apache Flink (v1.6.0) authenticate Elasticsearch Sink (v6.4)

I tried copy pasting the solution code provided in the above SO into IntelliJ, the auto-converted code also has compiler errors.

      // provide a RestClientFactory for custom configuration on the internally created REST client
      // i only show the setMaxRetryTimeoutMillis for illustration purposes, the actual code will use HTTP cutom callback
      esSinkBuilder.setRestClientFactory(
        restClientBuilder -> {
          restClientBuilder.setMaxRetryTimeoutMillis(10)
        }
      )

Then i tried (auto generated Java to Scala code by IntelliJ)

// provide a RestClientFactory for custom configuration on the internally created REST client// provide a RestClientFactory for custom configuration on the internally created REST client
      import org.apache.http.auth.AuthScope
      import org.apache.http.auth.UsernamePasswordCredentials
      import org.apache.http.client.CredentialsProvider
      import org.apache.http.impl.client.BasicCredentialsProvider
      import org.apache.http.impl.nio.client.HttpAsyncClientBuilder
      import org.elasticsearch.client.RestClientBuilder
      // provide a RestClientFactory for custom configuration on the internally created REST client// provide a RestClientFactory for custom configuration on the internally created REST client

      esSinkBuilder.setRestClientFactory((restClientBuilder) => {
        def foo(restClientBuilder) = restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
          override def customizeHttpClient(httpClientBuilder: HttpAsyncClientBuilder): HttpAsyncClientBuilder = { // elasticsearch username and password
            val credentialsProvider = new BasicCredentialsProvider
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(es_user, es_password))
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
          }
        })

        foo(restClientBuilder)
      })

The original code snippet produces the error "cannot resolve RestClientFactory" and then Java to Scala shows several other errors.

So basically i need to find a Scala version of the solution described in Apache Flink (v1.6.0) authenticate Elasticsearch Sink (v6.4)

Update 1: I was able to make some progress with some help from IntelliJ. The following code compiles and runs but there is another problem.

esSinkBuilder.setRestClientFactory(
          new RestClientFactory {
            override def configureRestClientBuilder(restClientBuilder: RestClientBuilder): Unit = {
              restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                override def customizeHttpClient(httpClientBuilder: HttpAsyncClientBuilder): HttpAsyncClientBuilder = {
                  // elasticsearch username and password
                  val credentialsProvider = new BasicCredentialsProvider
                  credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(es_user, es_password))
                  httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
                  httpClientBuilder.setSSLContext(trustfulSslContext)
                }
              })
            }
          }

The problem is that i am not sure if i should be doing a new of the RestClientFactory object. What happens is that the application connects to the elasticsearch cluster but then discovers that the SSL CERT is not valid, so i had to put the trustfullSslContext (as described here https://gist.github.com/iRevive/4a3c7cb96374da5da80d4538f3da17cb), this got me past the SSL issue but now the ES REST Client does a ping test and the ping fails, it throws an exception and the app shutsdown. I am suspecting that the ping fails because of the SSL error and maybe it is not using the trustfulSslContext i setup as part of new RestClientFactory and this makes me suspect that i should not have done the new, there should be a simple way to update the existing RestclientFactory object and basically this is all happening because of my lack of Scala knowledge.


问:
Getting Tab Component To Consume UIID
I have tried everything possible to style my Tab component but its not getting reflected. I want my selected Tab to have a white background and red foreground. Even though I have edited Style using Theme designer. Its still doesnt work. I read the docs and I am aware Tab component is now like a toggle. I did the suggestion to setTabUIID(null) but still cant get it to work. How can this be done.</p>

答: You don't need the setTabUIID(null); just make sure to style both selected and unselected styles. Also override the Border to Empty if you don't define a border.

Title: Getting Tab Component To Consume UIID


问:
Simple HelloWorld app on cloudrun (or knative) seems too slow
I deployed a sample HelloWorld app on Google Cloud Run, which is basically k-native, and every call to the API takes 1.4 seconds at best, in an end-to-end manner. Is it supposed to be so?

The sample app is at https://cloud.google.com/run/docs/quickstarts/build-and-deploy

I deployed the very same app on my localhost as a docker container and it takes about 22ms, end-to-end.

The same app on my GKE cluster takes about 150 ms, end-to-end.

import os

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    target = os.environ.get('TARGET', 'World')
    return 'Hello {}!\n'.format(target)

if __name__ == "__main__":
    app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080)))
```

I am a little experience in FaaS and I expect API calls would get faster as I invoked them in a row. (as in cold start vs. warm start)

But no matter how many times I execute the command it doesn't go below 1.4 seconds.

I think the network distance isn't the dominant factor here. The round-trip time via ping to the API endpoint is only 50ms away, more or less

So my questions are as follows:

Is it potentially an unintended bug? Is it a technical difficulty which will be resolved eventually? Or maybe nothing's wrong, it's just the SLA of k-native?

If nothing's wrong with Google Cloud Run and/or k-native, what is the dominant time-consuming factor here for my API call? I'd love to learn the mechanism.

Additional Details:

Where I am located at: Seoul/Asia

The region for my Cloud Run app: us-central1

type of Internet connection I am testing under: Business, Wired

app's container image size: 343.3MB

the bucket location that Container Registry is using: gcr.io

WebPageTest from Seoul/Asia (warmup time):

Content Type: text/html

Request Start: 0.44 s

DNS Lookup: 249 ms

Initial Connection: 59 ms

SSL Negotiation: 106 ms

Time to First Byte: 961 ms

Content Download: 2 ms

WebPageTest from Chicago/US (warmup time):

Content Type: text/html

Request Start: 0.171 s

DNS Lookup: 41 ms

Initial Connection: 29 ms

SSL Negotiation: 57 ms

Time to First Byte: 61 ms

Content Download: 3 ms

ANSWER by Steren, the Cloud Run product manager

We have detected high latency when calling Cloud Run services from
  some particular regions in the world. Sadly, Seoul seems to be one of
  them.

答:
[Update: This person has a networking problem in his area. I tested his endpoint from Seattle with no problems. Details in the comments below.]

I have worked with Cloud Run constantly for the past several months. I have deployed several production applications and dozens of test services. I am in Seattle, Cloud Run is in us-central1. I have never noticed a delay. Actually, I am impressed with how fast a container starts up.

For one of my services, I am seeing cold start time to first byte of 485ms. Next invocation 266ms, 360ms. My container is checking SSL certificates (2) on the Internet. The response time is very good.

For another service which is a PHP website, time to first byte on cold start is 312ms, then 94ms, 112ms.

What could be factors that are different for you?

How large is your container image? Check Container Registry for the size. My containers are under 100 MB. The larger the container the longer the cold start time.

Where is the bucket located that Container Registry is using? You want the bucket to be in us-central1 or at least US. This will change soon with when new Cloud Run regions are announced.

What type of Internet connection are you testing under? Home based or Business. Wireless or Ethernet connection? Where in the world are you testing from? Launch a temporary Compute Engine instance, repeat your tests to Cloud Run and compare. This will remove your ISP from the equation.

Increase the memory allocated to the container. Does this affect performance? Python/Flask does not require much memory, my containers are typically 128 MB and 256 MB. Container images are loaded into memory, so if you have a bloated container, you might now have enough memory left reducing performance.

What does Stackdriver logs show you? You can see container starts, requests, and container terminations.

Body:
I deployed a sample HelloWorld app on Google Cloud Run, which is basically k-native, and every call to the API takes 1.4 seconds at best, in an end-to-end manner. Is it supposed to be so?

The sample app is at https://cloud.google.com/run/docs/quickstarts/build-and-deploy

I deployed the very same app on my localhost as a docker container and it takes about 22ms, end-to-end.

The same app on my GKE cluster takes about 150 ms, end-to-end.

import os

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    target = os.environ.get('TARGET', 'World')
    return 'Hello {}!\n'.format(target)

if __name__ == "__main__":
    app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080)))

I am a little experience in FaaS and I expect API calls would get faster as I invoked them in a row. (as in cold start vs. warm start)

But no matter how many times I execute the command it doesn't go below 1.4 seconds.

I think the network distance isn't the dominant factor here. The round-trip time via ping to the API endpoint is only 50ms away, more or less

So my questions are as follows:

Is it potentially an unintended bug? Is it a technical difficulty which will be resolved eventually? Or maybe nothing's wrong, it's just the SLA of k-native?

If nothing's wrong with Google Cloud Run and/or k-native, what is the dominant time-consuming factor here for my API call? I'd love to learn the mechanism.

Additional Details:

Where I am located at: Seoul/Asia

The region for my Cloud Run app: us-central1

type of Internet connection I am testing under: Business, Wired

app's container image size: 343.3MB

the bucket location that Container Registry is using: gcr.io

WebPageTest from Seoul/Asia (warmup time):

Content Type: text/html

Request Start: 0.44 s

DNS Lookup: 249 ms

Initial Connection: 59 ms

SSL Negotiation: 106 ms

Time to First Byte: 961 ms

Content Download: 2 ms

WebPageTest from Chicago/US (warmup time):

Content Type: text/html

Request Start: 0.171 s

DNS Lookup: 41 ms

Initial Connection: 29 ms

SSL Negotiation: 57 ms

Time to First Byte: 61 ms

Content Download: 3 ms

ANSWER by Steren, the Cloud Run product manager

We have detected high latency when calling Cloud Run services from
  some particular regions in the world. Sadly, Seoul seems to be one of
  them.


问:
How to wrap text within multiline react native textInput
I am trying to implement a multiline text input in react native, but when user types the text doesn't get wrapped but gets written horizontally on the same line,

the code for my text input is as follows

```<code><View style={[styles.container, props.containerStyles]}>
  <TextInput
    style={styles.placeholderStyle}
    placeholder={"Placeholder text"}
    value={this.state.reviewBody}
    onChangeText={body => this.setState({ reviewBody: body })}
    numberOfLines={5}
    textAlignVertical={"top"}
    textBreakStrategy={"highQuality"}
    underlineColorAndroid={"transparent"}
    autoCorrect
  />
</View>
</code>```

and the styles are,

```<code>const styles = StyleSheet.create({
  container: {
    flex: 1,
    borderWidth: 2,
    borderColor: "#f4f4f4",
    width: WIDTH - 40,
    maxWidth: WIDTH - 40,
    minWidth: WIDTH - 40,
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 5,
    marginTop: 10,
    flexWrap: "wrap",
  },
  placeholderStyle: {
    fontSize: 11,
    padding: 0,
    flex: 1,
    width: WIDTH - 40,
    maxWidth: WIDTH - 40,
    minWidth: WIDTH - 40,
    flexWrap: "wrap",
    overflow: "scroll"
  },
</code>```

答:
In TextInput component, use props multiline={true}, this should solve your issue. Also if you want to control the text alignment behavior, you can use textAlignVertical props.
Find more details in this link - https://facebook.github.io/react-native/docs/textinput#multiline

Body:
I am trying to implement a multiline text input in react native, but when user types the text doesn't get wrapped but gets written horizontally on the same line,

the code for my text input is as follows

<View style={[styles.container, props.containerStyles]}>
  <TextInput
    style={styles.placeholderStyle}
    placeholder={"Placeholder text"}
    value={this.state.reviewBody}
    onChangeText={body => this.setState({ reviewBody: body })}
    numberOfLines={5}
    textAlignVertical={"top"}
    textBreakStrategy={"highQuality"}
    underlineColorAndroid={"transparent"}
    autoCorrect
  />
</View>

and the styles are,

const styles = StyleSheet.create({
  container: {
    flex: 1,
    borderWidth: 2,
    borderColor: "#f4f4f4",
    width: WIDTH - 40,
    maxWidth: WIDTH - 40,
    minWidth: WIDTH - 40,
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 5,
    marginTop: 10,
    flexWrap: "wrap",
  },
  placeholderStyle: {
    fontSize: 11,
    padding: 0,
    flex: 1,
    width: WIDTH - 40,
    maxWidth: WIDTH - 40,
    minWidth: WIDTH - 40,
    flexWrap: "wrap",
    overflow: "scroll"
  },


问:
can I split some text on python?
I want to split text on python and take some part, for example:

let the blue sky meet the blue sea

I want this for the result:

blue sky

this is my code

text = "let the blue sky meet the blue sea"
bluee = text.split("the", 1)[1]
print bluee
```

and the result from the code is
blue sky meet the blue sea

答:
This would strip away the beggining of the text and then the last of the text.
raw_input() or input() could be used to have the user determine what part of the code to be stripped out

```<code>text = "let the blue sky meet the blue sea"
bluee = text.split("the", 1)[1]
skyy = bluee.split("meet", 1)[0]
print skyy
</code>```

Title: can I split some text on python?

Body:
I want to split text on python and take some part, for example:

let the blue sky meet the blue sea

I want this for the result:

blue sky

this is my code

text = "let the blue sky meet the blue sea"
bluee = text.split("the", 1)[1]
print bluee

and the result from the code is
blue sky meet the blue sea

Body:
This would strip away the beggining of the text and then the last of the text.
raw_input() or input() could be used to have the user determine what part of the code to be stripped out

text = "let the blue sky meet the blue sea"
bluee = text.split("the", 1)[1]
skyy = bluee.split("meet", 1)[0]
print skyy


问:
schedule task through IPC connection can not be run correctly
Here is a windows 7 ultimate, which is logged on by a normal user, and this user is a member of administrators group, then I use another computer which is in the same LAN to build an IPC connection with that windows 7, I connect as administrator, and then I use schtasks build a schedule task, which is very simple, just executing a batch file, but I have no idea why this schedule task can not be run?

Below is the command I use to connect with the windows 7 and create schedule task:

```<code>net use \\10.10.10.148 "password" /user:administrator
copy simple.bat \\10.10.10.148\c$
schtasks /create /s 10.10.10.148 /u administrator /p password /tn test /sc once /st 08:00 /tr C:\simple.bat /ru administrator /f
</code>```

Here is the content of that simple.bat:

```<code>rd C:\windows\temp\ipc_test
</code>```

答: I figure out this myself, the reason why schedule task can't be run is the current user's privilege is lower than the schedule task's privilege</p>

Body:
Here is a windows 7 ultimate, which is logged on by a normal user, and this user is a member of administrators group, then I use another computer which is in the same LAN to build an IPC connection with that windows 7, I connect as administrator, and then I use schtasks build a schedule task, which is very simple, just executing a batch file, but I have no idea why this schedule task can not be run?

Below is the command I use to connect with the windows 7 and create schedule task:

net use \\10.10.10.148 "password" /user:administrator
copy simple.bat \\10.10.10.148\c$
schtasks /create /s 10.10.10.148 /u administrator /p password /tn test /sc once /st 08:00 /tr C:\simple.bat /ru administrator /f

Here is the content of that simple.bat:

rd C:\windows\temp\ipc_test


问:
How to access web.config values?
I wrote this in my web.config now how to access host,port in my code

I am using like this but it is unable to read pls help me

```<code>string smtphost = ConfigurationManager.AppSettings["host"].ToString();

<mailSettings>
    <smtp from="mail.crmprocorp.com" deliveryMethod="Network">
       <network
          defaultCredentials="false"
          enableSsl="false"
          host="smtp.gmail.com"
          port="25"
          password="password"
          userName="xyz@gmail.com"/>
    </smtp>
</mailSettings>
</code>```

答:
You have to use the ConfigurationManager and its method GetSection to do this.

MSDN docs:
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.getsection.aspx

ContentLicense: CC BY-SA 3.0

Title: How to access web.config values?

Body:
I wrote this in my web.config now how to access host,port in my code

I am using like this but it is unable to read pls help me

string smtphost = ConfigurationManager.AppSettings["host"].ToString();

<mailSettings>
    <smtp from="mail.crmprocorp.com" deliveryMethod="Network">
       <network
          defaultCredentials="false"
          enableSsl="false"
          host="smtp.gmail.com"
          port="25"
          password="password"
          userName="xyz@gmail.com"/>
    </smtp>
</mailSettings>


问:
fgets() issues with for loop in C
Why am I getting the following output when fgets is outside for loop:

Jim, Engineer

Jim, Engineer

Jim, Engineer

Jim, Engineer

and the following output when fgets is inside for loop:

Jim, Engineer

Pam, Nurse

Scar, Troublemaker

John, Smith

```<code>int main()
{
    int i;
    char line[255];
    FILE *fpointer = fopen("employees.txt", "r");

    for (i=0; i < 4; i++){
        fgets(line, 255, fpointer);
        printf("%s", line);
    }
    fclose(fpointer);

    return 0
}
</code>```

within fget(), "i" is not passed as an argument so how is it still iterating over each line in the .txt file?

答: fgets will read the file using fpointer (think of it as a cursor), and will increment it. So every time you use fgets you move forward in the file.

Title: fgets() issues with for loop in C

Body:
Why am I getting the following output when fgets is outside for loop:

Jim, Engineer

Jim, Engineer

Jim, Engineer

Jim, Engineer

and the following output when fgets is inside for loop:

Jim, Engineer

Pam, Nurse

Scar, Troublemaker

John, Smith

int main()
{
    int i;
    char line[255];
    FILE *fpointer = fopen("employees.txt", "r");

    for (i=0; i < 4; i++){
        fgets(line, 255, fpointer);
        printf("%s", line);
    }
    fclose(fpointer);

    return 0
}

within fget(), "i" is not passed as an argument so how is it still iterating over each line in the .txt file?


问:
How to set DockWidget at Top Right corner of QGIS?
I am trying to dock my plugin window at the top right corner of QGIS but unable to place it at the top if there is a window already present.

I have used the following code which makes the plugin window to appear at the right side but not at the top as some other window is already present at the top.

```<code>dock_widget = QDockWidget("My_Plugin", self.iface.mainWindow())
dock_widget.setWidget(MainWindow)
dock_widget.setFixedWidth(356)
dock_widget.setFixedHeight(620)

self.iface.addDockWidget(QtCore.Qt.RightDockWidgetArea, dock_widget)
dock_widget.setAllowedAreas(QtCore.Qt.RightDockWidgetArea |
QtCore.Qt.TopDockWidgetArea)
</code>```

Here is the example:

I want this Login Window above the Processing Toolbox, i.e., to be at the top right corner of QGIS and the Processing Toolbox should be below the Login Window.

答:
I use the below code to put my Pyqt5 application at bottom right corner of the screen. You may tweak some changes as per your requirement.</p>

```<code>def location_on_the_screen(self):
    ag = QDesktopWidget().availableGeometry()
    sg = QDesktopWidget().screenGeometry()

    widget = self.geometry()
    x = ag.width() - widget.width()
    y = 2 * ag.height() - sg.height() - widget.height()
    self.move(x, y)
</code>```

Body:
I am trying to dock my plugin window at the top right corner of QGIS but unable to place it at the top if there is a window already present.

I have used the following code which makes the plugin window to appear at the right side but not at the top as some other window is already present at the top.

dock_widget = QDockWidget("My_Plugin", self.iface.mainWindow())
dock_widget.setWidget(MainWindow)
dock_widget.setFixedWidth(356)
dock_widget.setFixedHeight(620)

self.iface.addDockWidget(QtCore.Qt.RightDockWidgetArea, dock_widget)
dock_widget.setAllowedAreas(QtCore.Qt.RightDockWidgetArea |
QtCore.Qt.TopDockWidgetArea)

Here is the example:

I want this Login Window above the Processing Toolbox, i.e., to be at the top right corner of QGIS and the Processing Toolbox should be below the Login Window.

Body:
I use the below code to put my Pyqt5 application at bottom right corner of the screen. You may tweak some changes as per your requirement.

def location_on_the_screen(self):
    ag = QDesktopWidget().availableGeometry()
    sg = QDesktopWidget().screenGeometry()

    widget = self.geometry()
    x = ag.width() - widget.width()
    y = 2 * ag.height() - sg.height() - widget.height()
    self.move(x, y)


问:
Problem of connection between lambda function and MySQL on RDS
I am trying to access a MySQL database on Amazon RDS from an AWS Lambda Python function. After running test, it give a error of connection failed:

"errorMessage": "2019-05-27T15:14:26.967Z f6e8ae8d-1dfc-4be5-9e00-a2c937e4ca2c Task timed out after 3.00 seconds"

I believe that is cause by the configuration of VPC or NAT or Security Group.

I tried to follow:

AWS Lambda: Enable Outgoing Internet Access within VPC

Tutorial: Configuring a Lambda Function to Access Amazon RDS in an Amazon VPC - AWS Lambda

But still not working

I have:

A default VPC with one Internet Gateway attached

2 subnets with IPv4 CIDR xxx.xx.0.0/20 (subnet001) and xxx.xx.16.0/20 (subnet002) associated with one route table and one Network ACL.

NAT Gateway associate with subnet001

My question is:

According to these two tutorials, I will need one VPC, four subnets (1,2,3,4), first two subnets associate with the main route table that access to local and internet gateway. And second two subnets associate with "lambda-to-internet" route table that access to local and a NAT gateway.

The NAT gateway should associate with subnet 1. Am I correct?

And for network ACL, do all four subnets associate with same ACL?

In Lambda VPC setting, do I add all four subnets or only last two subnets?

rds_host = "my_host_name"
name = "my_username"
password = "my_password"
db_name = "my_db_name"

conn = pymysql.connect(rds_host, user=name, passwd=password, db=db_name, connect_timeout=5)
```

答:
You have a lot of information in your question, so it is hard to reply to it all, but it seems that your basic question is how to allow the AWS Lambda function to connect to the Amazon RDS instance.

Your configuration will need to be:

The Lambda function configured to connect to the VPC (any subnet, it doesn't matter)

The Amazon RDS instance launched in the same VPC

A security group (Lambda-SG) on the Lambda function - it doesn't need any configuration, but it needs to exist

A security group (RDS-SG) on the Amazon RDS db instance that permits inbound traffic from Lambda-SG on port 3306

Please note that RDS-SG is permitting a connection from Lambda-SG. A security group can refer to another security group.

Also, increase the timeout for your Lambda function. It is currently set to 3 seconds, which might not be enough to accomplish what you are trying to do. The connection timeout is set to 5 seconds, so you will need the Lambda function to run longer than this time to confirm what is happening.

That's all you need. You don't need a NAT Gateway for this setup. It is only required if you wish the Lambda function to be connect to the VPC AND have the ability to connect to the Internet. You only need one subnet (for the RDS db instance) for what you have described, but your architecture might require more for other resources you are using. Event the Internet Gateway is not needed for the Lambda and RDS bits. But, focus on getting the Lambda-RDS connection going and then you can clean up things.


问:
Why does java hashmap treeify the bin at the count of 8 and untreeify at the count of 6?
Please enlighten me. I can only imagine that this situation can avoid the  treeify and untreeify frequently while the count of the bin is 8.

```<code>/**
 * The bin count threshold for using a tree rather than list for a
 * bin.  Bins are converted to trees when adding an element to a
 * bin with at least this many nodes. The value must be greater
 * than 2 and should be at least 8 to mesh with assumptions in
 * tree removal about conversion back to plain bins upon
 * shrinkage.
 */
static final int TREEIFY_THRESHOLD = 8;

/**
 * The bin count threshold for untreeifying a (split) bin during a
 * resize operation. Should be less than TREEIFY_THRESHOLD, and at
 * most 6 to mesh with shrinkage detection under removal.
 */
static final int UNTREEIFY_THRESHOLD = 6;
</code>```

Actually, I am asking why the values are not the same. Can you show me the specific statics about the reason why they use the different count?

答: Hashmap is the implementation of hashtable data structure. When we insert a key, value pair , using a hash function system will identify the hash value for the key and insert into a corresponding bin. If you insert another key, value pair and hash value of the second key also provide the same value it will go to the same bin. This scenario is called hash collision. If the size of the bin is small, while searching for the element later, List/array implementation of bin provide better performance. Otherwise bin size is large a binary tree may help to identify the key easily. What you have noticed is a a performance optimization of the hashmap.</p>

Body:
Please enlighten me. I can only imagine that this situation can avoid the  treeify and untreeify frequently while the count of the bin is 8.

/**
 * The bin count threshold for using a tree rather than list for a
 * bin.  Bins are converted to trees when adding an element to a
 * bin with at least this many nodes. The value must be greater
 * than 2 and should be at least 8 to mesh with assumptions in
 * tree removal about conversion back to plain bins upon
 * shrinkage.
 */
static final int TREEIFY_THRESHOLD = 8;

/**
 * The bin count threshold for untreeifying a (split) bin during a
 * resize operation. Should be less than TREEIFY_THRESHOLD, and at
 * most 6 to mesh with shrinkage detection under removal.
 */
static final int UNTREEIFY_THRESHOLD = 6;

Actually, I am asking why the values are not the same. Can you show me the specific statics about the reason why they use the different count?


问:
How to move selected code segment to the left in VS Code?
The question is, how do I move the selected block of code by one or several tabs, but not to the right (which is done by selecting a code and pressing Tab key), but to the left? Without selection each line one by one and deleting whitespace?

Moving parts of code from one place to another with differences in indent levels is a bit hard without knowing the shortcut.

What I mean (Imgur)

Thanks!

答:
For what you want,

Shift+Tab

should do the trick. However, I would like to recommend this extension which I find easier to use when formatting blocks of text: Indent One space

Note however this extension only indents selections by exactly one space, forward or backwards.


问:
Varnish policy engine on Ubuntu
I'm following the Varnish docs relating to policy-engine and am confused how to install it on Ubuntu.  I can't find any repo that seems to have it or any trace of how to install it online.  Has it been renamed or something?  I'm using Varnish 6.0 on Ubuntu.

Thanks,

答:
The Policy Engine is a Varnish Enterprise product, you need a subscription to get access to the repositories.

On top of that, it's been discontinued, may I ask where you found a link to that page?

Title: Varnish policy engine on Ubuntu


问:
Duplicate value of a field with respect to other field
I want to get duplicate value of a field with respect to other field.
duplicate value of RAP07C.SSISEQ on RAP07C.SSITYP

I used 'HAVING COUNT(RAP07C.SSISEQ) > 1' with respect to RAP07C.SSITYP, But I am getting the records if they have two or more records even though the two value of RAP07C.SSISEQ is same with respect to RAP07C.SSITYP. But I want records with the different value of RAP07C.SSISEQ.

```<code>SELECT DISTINCT
  /*+ use_hash(RAP01 rap07a RAP07C) */
  Rap01.plcy,
  Rap01.j01_PT_LINE_cat_Cd AS j01_PT_LINE_cat_Cd,
  Rap01.J01_Pt_State_Cd    AS J01_Pt_State_Cd,
  COUNT(RAP07C.SSISEQ)     AS Count_of_SSISEQ,
  --RAP07C.SSISEQ,
  RAP07C.SSITYP
  --
FROM Rap01
  --
JOIN RAP07C
ON RAP07C.J41_PT_LINE_CAT_CD  = rap01.j01_pt_line_cat_cd
AND RAP07C.J41_PT_CDB_PART_ID = rap01.j01_pt_cdb_part_id
AND RAP07C.J41_PT_STATE_CD    = rap01.j01_pt_state_cd
AND RAP07C.PLCY               = rap01.plcy
AND RAP07C.dropdt_t           = '31-DEC-9999'
  --
WHERE Rap01.Line3 IN ('010','016')
GROUP BY RAP01.plcy,
  j01_PT_LINE_cat_Cd,
  J01_Pt_State_Cd,
  RAP07C.SSITYP
HAVING COUNT(RAP07C.SSISEQ) > 1;
</code>```

I want different values of RAP07C.SSISEQ with respect to RAP07C.SSITYP
Like: IFS - 001 IFS - 001 as I got above two values 001 with respect to IFS, But I need to get only different values for IFS (RAP07C.SSITYP) as IFS - 001 IFS - 002.

答:
Try putting the word DISTINCT inside the COUNT.</p>

```<code>SELECT
  Rap01.plcy,
  Rap01.j01_PT_LINE_cat_Cd AS j01_PT_LINE_cat_Cd,
  Rap01.J01_Pt_State_Cd    AS J01_Pt_State_Cd,
  COUNT(DISTINCT RAP07C.SSISEQ)     AS Count_of_SSISEQ,
  RAP07C.SSITYP

FROM Rap01

JOIN RAP07C
ON RAP07C.J41_PT_LINE_CAT_CD  = rap01.j01_pt_line_cat_cd
AND RAP07C.J41_PT_CDB_PART_ID = rap01.j01_pt_cdb_part_id
AND RAP07C.J41_PT_STATE_CD    = rap01.j01_pt_state_cd
AND RAP07C.PLCY               = rap01.plcy
AND RAP07C.dropdt_t           = '31-DEC-9999'

WHERE Rap01.Line3 IN ('010','016')
GROUP BY RAP01.plcy,
  j01_PT_LINE_cat_Cd,
  J01_Pt_State_Cd,
  RAP07C.SSITYP
HAVING COUNT(DISTINCT RAP07C.SSISEQ) > 1;
</code>```

Body:
I want to get duplicate value of a field with respect to other field.
duplicate value of RAP07C.SSISEQ on RAP07C.SSITYP

I used 'HAVING COUNT(RAP07C.SSISEQ) > 1' with respect to RAP07C.SSITYP, But I am getting the records if they have two or more records even though the two value of RAP07C.SSISEQ is same with respect to RAP07C.SSITYP. But I want records with the different value of RAP07C.SSISEQ.

SELECT DISTINCT
  /*+ use_hash(RAP01 rap07a RAP07C) */
  Rap01.plcy,
  Rap01.j01_PT_LINE_cat_Cd AS j01_PT_LINE_cat_Cd,
  Rap01.J01_Pt_State_Cd    AS J01_Pt_State_Cd,
  COUNT(RAP07C.SSISEQ)     AS Count_of_SSISEQ,
  --RAP07C.SSISEQ,
  RAP07C.SSITYP
  --
FROM Rap01
  --
JOIN RAP07C
ON RAP07C.J41_PT_LINE_CAT_CD  = rap01.j01_pt_line_cat_cd
AND RAP07C.J41_PT_CDB_PART_ID = rap01.j01_pt_cdb_part_id
AND RAP07C.J41_PT_STATE_CD    = rap01.j01_pt_state_cd
AND RAP07C.PLCY               = rap01.plcy
AND RAP07C.dropdt_t           = '31-DEC-9999'
  --
WHERE Rap01.Line3 IN ('010','016')
GROUP BY RAP01.plcy,
  j01_PT_LINE_cat_Cd,
  J01_Pt_State_Cd,
  RAP07C.SSITYP
HAVING COUNT(RAP07C.SSISEQ) > 1;

I want different values of RAP07C.SSISEQ with respect to RAP07C.SSITYP
Like: IFS - 001 IFS - 001 as I got above two values 001 with respect to IFS, But I need to get only different values for IFS (RAP07C.SSITYP) as IFS - 001 IFS - 002.

Body:
Try putting the word DISTINCT inside the COUNT.

SELECT
  Rap01.plcy,
  Rap01.j01_PT_LINE_cat_Cd AS j01_PT_LINE_cat_Cd,
  Rap01.J01_Pt_State_Cd    AS J01_Pt_State_Cd,
  COUNT(DISTINCT RAP07C.SSISEQ)     AS Count_of_SSISEQ,
  RAP07C.SSITYP

FROM Rap01

JOIN RAP07C
ON RAP07C.J41_PT_LINE_CAT_CD  = rap01.j01_pt_line_cat_cd
AND RAP07C.J41_PT_CDB_PART_ID = rap01.j01_pt_cdb_part_id
AND RAP07C.J41_PT_STATE_CD    = rap01.j01_pt_state_cd
AND RAP07C.PLCY               = rap01.plcy
AND RAP07C.dropdt_t           = '31-DEC-9999'

WHERE Rap01.Line3 IN ('010','016')
GROUP BY RAP01.plcy,
  j01_PT_LINE_cat_Cd,
  J01_Pt_State_Cd,
  RAP07C.SSITYP
HAVING COUNT(DISTINCT RAP07C.SSISEQ) > 1;


答:
Try the following to get the MailSettingsSectionGroup (assuming this is a web application)</p>

```<code>Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
MailSettingsSectionGroup settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
string smtpHost = settings.Smtp.Network.Host;
</code>```

Title: How to access web.config values?

Body:
Try the following to get the MailSettingsSectionGroup (assuming this is a web application)

Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
MailSettingsSectionGroup settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
string smtpHost = settings.Smtp.Network.Host;


问:
How do I create multiple data frames using a for loop in python
I'm trying to make multiple dataframes that are subsets of existing dataframes.

I have df_list which is actually a list of datasets:

df_list = [df1B, df2B, df3B, df4B, df5B, df6B, df7B, df8B, df9B, df10B, df11B, df12B, df13B, df14B, df15B, df16B, df17B, df18B, df19B, df20B, df21B, df22B, df23B, df24B, df25B, df26B, df27B, df28B, df30B, df31B, df32B, df33B, df34B, df35B]
```

<p>If I want to make a subset of a single data set I do this and it works:</p>

<pre class="lang-py prettyprint-override"><code>df2B = df2B.groupby(['Location']).get_group(36)
</code>```

It takes all locations with number 36, but when I try to do it for all the data sets in a for loop it doesn't work

for df in df_list:
    df = df.groupby(['Location']).get_group(36)
```

But this is not making it for each dataset. It doesn't show any error message but it doesn't do anything else either :(

Should I just write the same line 35 times ??? I hope I have a better option.

答:
You're assigning to your loop variable, which is then thrown away on the next go around. DataFrame.append isn't inplace, and doesn't have an inplace parameter. Instead:

df1 = pd.DataFrame({'gr': [1,1,2,2], 'v': [1,2,3,2]})
df2 = pd.DataFrame({'gr': [1,1,2,2], 'v': [6,5,4,3]})
df_combined = pd.DataFrame({'gr': [], 'v':[]})
df_combined
Empty DataFrame
Columns: [gr, v]
Index: []
for df in [df1, df2]:
    df_combined = df_combined.append(df.groupby('gr').get_group(1))
df_combined
#     gr    v
# 0  1.0  1.0
# 1  1.0  2.0
# 0  1.0  6.0
# 1  1.0  5.0
```

<p>Unless you want a list of DataFrames, which it suddenly seems like you do. (I was thrown by <code>df.append()</code>. For a <code>list</code>, <code>append</code> adds to the end in place. For a DataFrame, it does not. In the list case, you want:</p>

<pre class="lang-py prettyprint-override"><code># setup as before
combined_dfs = []
for df in [df1, df2]:
    combined_dfs = df_combined.append(df.groupby('gr').get_group(1))
</code>```

It's a funny way to use DataFrames, but there ya go! :D

Body:
I'm trying to make multiple dataframes that are subsets of existing dataframes.

I have df_list which is actually a list of datasets:

df_list = [df1B, df2B, df3B, df4B, df5B, df6B, df7B, df8B, df9B, df10B, df11B, df12B, df13B, df14B, df15B, df16B, df17B, df18B, df19B, df20B, df21B, df22B, df23B, df24B, df25B, df26B, df27B, df28B, df30B, df31B, df32B, df33B, df34B, df35B]

If I want to make a subset of a single data set I do this and it works:

df2B = df2B.groupby(['Location']).get_group(36)

It takes all locations with number 36, but when I try to do it for all the data sets in a for loop it doesn't work

for df in df_list:
    df = df.groupby(['Location']).get_group(36)

But this is not making it for each dataset. It doesn't show any error message but it doesn't do anything else either :(

Should I just write the same line 35 times ??? I hope I have a better option.

Body:
You're assigning to your loop variable, which is then thrown away on the next go around. DataFrame.append isn't inplace, and doesn't have an inplace parameter. Instead:

df1 = pd.DataFrame({'gr': [1,1,2,2], 'v': [1,2,3,2]})
df2 = pd.DataFrame({'gr': [1,1,2,2], 'v': [6,5,4,3]})
df_combined = pd.DataFrame({'gr': [], 'v':[]})
df_combined
Empty DataFrame
Columns: [gr, v]
Index: []
for df in [df1, df2]:
    df_combined = df_combined.append(df.groupby('gr').get_group(1))
df_combined
#     gr    v
# 0  1.0  1.0
# 1  1.0  2.0
# 0  1.0  6.0
# 1  1.0  5.0

Unless you want a list of DataFrames, which it suddenly seems like you do. (I was thrown by df.append(). For a list, append adds to the end in place. For a DataFrame, it does not. In the list case, you want:

# setup as before
combined_dfs = []
for df in [df1, df2]:
    combined_dfs = df_combined.append(df.groupby('gr').get_group(1))

It's a funny way to use DataFrames, but there ya go! :D


问:
Wordpress plugin - users send files to owner
I'm doing a WordPress page and I need that the people that visit the page can send to me (the owner) images.

I don't want them to be able to upload them to the page, I just want to be able to receive the images via mail.

Is there any wordpress plugin that can do this?

答:
You can use google forms:
https://www.google.com/forms/about/

Here is the example:
https://www.iamm-kw.net/

scroll down to the button "Send Video"
when you click or tap the button, you will go to google forms website where you can log in with your google account and submit almost any heavy file.
You will be notified via email that somebody sent you a file.
The file may be logged in google sheets (kind of excel doc) with all the form values.
For example:
Name Joe Last Name Dow File Description this is my first attempt to take a good photo in the woods. Comments: please, accept this file
This Google sheets file will keep a log of all their uploads and whatever fields you specify in the upload form.
Cons: to upload a file they will need a Google account
Every time somebody visits the forms site, even without uploading anything, Google will send you a letter, that you have 15 GB left and if you don't want your users to have problems with upload, please upgrade your storage.
Pros: Fast and convenient. No plugins, no codes. big files, you can keep logs.


问:
Parsing date form dd-MM-yyyy to dd MMM yyyy
I want to parse dd-MM-yyyy date format into dd MMM yyyy I get the reference but it cannot convert date in a proper manner it mismatches the date and month.

Suppose my date is

```<code>string dat = "11-01-2019"
</code>```

and I am using

```<code>string date = DateTime.Parse(dat).ToString("dd MMM yyyy");
</code>```

but it returns 01 Nov 2019. But actually, it is 11 Jan 2019 because the format of date is dd-MM-yyyy I don't understand how to correct it any method of parsing I am using it returns 01 Nov 2019 that is wrong. Please help me to resolve the issue

答:
You'll need to specify the culture the date is formatted for. I'm assuming UK here:

```<code>var ukCulture = System.Globalization.CultureInfo.GetCultureInfo("en-gb");
string dat = "11-01-2019";
string date = DateTime.Parse(dat, ukCulture).ToString("dd MMM yyyy");
Console.WriteLine(date);
</code>```

Try it online

Note that you'll get a FormatException if you enter an invalid date here, so it might be better to use TryParse:

```<code>var ukCulture = System.Globalization.CultureInfo.GetCultureInfo("en-gb");
string dat = "11-01-2019";
DateTime parsedDate;
if (DateTime.TryParse(dat, ukCulture, System.Globalization.DateTimeStyles.None, out parsedDate))
{
    string date = parsedDate.ToString("dd MMM yyyy");
    Console.WriteLine(date);
}
else
{
    Console.WriteLine("invalid date");
}
</code>```

Try it online

Body:
I want to parse dd-MM-yyyy date format into dd MMM yyyy I get the reference but it cannot convert date in a proper manner it mismatches the date and month.

Suppose my date is

string dat = "11-01-2019"

and I am using

string date = DateTime.Parse(dat).ToString("dd MMM yyyy");

but it returns 01 Nov 2019. But actually, it is 11 Jan 2019 because the format of date is dd-MM-yyyy I don't understand how to correct it any method of parsing I am using it returns 01 Nov 2019 that is wrong. Please help me to resolve the issue

Body:
You'll need to specify the culture the date is formatted for. I'm assuming UK here:

var ukCulture = System.Globalization.CultureInfo.GetCultureInfo("en-gb");
string dat = "11-01-2019";
string date = DateTime.Parse(dat, ukCulture).ToString("dd MMM yyyy");
Console.WriteLine(date);

Try it online

Note that you'll get a FormatException if you enter an invalid date here, so it might be better to use TryParse:

var ukCulture = System.Globalization.CultureInfo.GetCultureInfo("en-gb");
string dat = "11-01-2019";
DateTime parsedDate;
if (DateTime.TryParse(dat, ukCulture, System.Globalization.DateTimeStyles.None, out parsedDate))
{
    string date = parsedDate.ToString("dd MMM yyyy");
    Console.WriteLine(date);
}
else
{
    Console.WriteLine("invalid date");
}

Try it online


问:
Horizontal and vertical scroll bar if the content overflows the specified width and height in div

#myleft {
  float: left;
  width: 20%;
  position: relative;
}

#myRight {
  float: left;
  width: 80%;
  position: relative;
}

.displayBox {
  float: left;
  width: 33%;
  position: relative;
  height: 60px;
  overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <div id="myLeft">
    <h4>Left Content</h4>
  </div>
  <div id="myRight">
    <div class="displayBox">
      <p>Display the first content on BOX 1</p>
    </div>
    <div class="displayBox">
      <p>Display the first content on BOX 2. The content might overflow if it exceeds the height of 60px otherwise its perfectly fine.</p>
    </div>
    <div class="displayBox">
      <p>Display the first content on BOX 3</p>
    </div>
    <div class="displayBox">
      <p>Display the first content on BOX 4 and horizontal scroll bar</p>
    </div>
  </div>
  <div></code>```

There might be three or more div inside myRight div. I want the all the divs on the same row without overflowing to the next row with horizontal scroll. For content overflow, I have specified each div with height of 60px and overflow:auto which gives me vertical scroll bar. Similarly, I want horizontal scroll if there are more than 3 divs.

答:
Instead of using float, you could use display: flex.

display: flex aligns block children side-by-side (similar to float). Adding flex: 0 0 auto; to these children stops them from wrapping.

To display the horizontal scrollbar, you can use overflow-x: auto;.

.container {
  display: flex;
}

#myLeft {
  width: 20%;
}

#myRight {
  width: 80%;
  display: flex;
  overflow-x: auto;
}

.displayBox {
  width: calc(100% / 3); /* to achieve perfect thirds */
  flex: 0 0 auto;
  height: 60px;
  overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div id="myLeft">
    <h4>Left Content</h4>
  </div>
  <div id="myRight">
    <div class="displayBox">
      <p>Display the first content on BOX 1</p>
    </div>
    <div class="displayBox">
      <p>Display the first content on BOX 2. The content might overflow if it exceeds the height of 60px otherwise its perfectly fine.</p>
    </div>
    <div class="displayBox">
      <p>Display the first content on BOX 3</p>
    </div>
    <div class="displayBox">
      <p>Display the first content on BOX 4 and horizontal scroll bar</p>
    </div>
  </div>
</div></code>```

Body:
#myleft {
  float: left;
  width: 20%;
  position: relative;
}

#myRight {
  float: left;
  width: 80%;
  position: relative;
}

.displayBox {
  float: left;
  width: 33%;
  position: relative;
  height: 60px;
  overflow: auto;
}

Left Content

Display the first content on BOX 1

Display the first content on BOX 2. The content might overflow if it exceeds the height of 60px otherwise its perfectly fine.

Display the first content on BOX 3

Display the first content on BOX 4 and horizontal scroll bar

There might be three or more div inside myRight div. I want the all the divs on the same row without overflowing to the next row with horizontal scroll. For content overflow, I have specified each div with height of 60px and overflow:auto which gives me vertical scroll bar. Similarly, I want horizontal scroll if there are more than 3 divs.

Body:
Instead of using float, you could use display: flex.

display: flex aligns block children side-by-side (similar to float). Adding flex: 0 0 auto; to these children stops them from wrapping.

To display the horizontal scrollbar, you can use overflow-x: auto;.

.container {
  display: flex;
}

#myLeft {
  width: 20%;
}

#myRight {
  width: 80%;
  display: flex;
  overflow-x: auto;
}

.displayBox {
  width: calc(100% / 3); /* to achieve perfect thirds */
  flex: 0 0 auto;
  height: 60px;
  overflow: auto;
}

<div class="container">
  <div id="myLeft">
    <h4>Left Content</h4>
  </div>
  <div id="myRight">
    <div class="displayBox">
      <p>Display the first content on BOX 1</p>
    </div>
    <div class="displayBox">
      <p>Display the first content on BOX 2. The content might overflow if it exceeds the height of 60px otherwise its perfectly fine.</p>
    </div>
    <div class="displayBox">
      <p>Display the first content on BOX 3</p>
    </div>
    <div class="displayBox">
      <p>Display the first content on BOX 4 and horizontal scroll bar</p>
    </div>
  </div>
</div>


问:
How to fix: "Metadata contains a reference that cannot be resolved:'http://<host>:<port><path>?wsdl'." for "Configure WCF Web Service Reference" in vs
I have been trying to publish a WCF web service on my IIS server using a nonstandard HTTPS port. Access to the server should only be possible after authentication (via basic authentication). The web service I created for testing purposes is the base project you get by default when creating a WCF Service Application in Visual Studio. The only modifications I made are in the web.config file:

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <bindings>
      <basicHttpBinding>
        <binding name="secureHttpBinding">
          <security mode="Transport">
            <transport clientCredentialType="Basic"/>
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <services>
      <service name="SoapApi.Service1">
        <endpoint address=""
                  binding="basicHttpBinding"
                  bindingConfiguration="secureHttpBinding"
                  contract="SoapApi.IService1"/>

        <endpoint address="mex"
                  binding="mexHttpsBinding"
                  contract="IMetadataExchange" />
      </service>
    </services>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>
```

<p>After the service was published on the local file system and the IIS was configured. I was able to reach the WSDL file on the server after authentication from the browser on my local PC. But if I'm trying to add the service to a simple client application using the <code>Configure WCF Web Service Reference</code> wizard from Visual Studio, I get the following error message:</p>

```Metadata contains a reference that cannot be resolved:'http://<host>:<port><path>?wsdl'.
```

<p>and the full error message:</p>

```An error occurred while attempting to find services at 'http://<host>:<port><path>?wsdl'. The remote server returned an error: (403) Forbidden.
```

<p>Since this error indicates that I don't have access permission, I thought why not turn off authentication and try if it works. I activated anonymous access for the website in IIS and deactivated basic authentication.
Furthermore I changed the following passage in the <code>web.config</code> file:</p>

<pre class="lang-xml prettyprint-override"><code><basicHttpBinding>
    <binding name="secureHttpBinding">
      <security mode="Transport">
        <transport clientCredentialType="None"/>
      </security>
    </binding>
 </basicHttpBinding>
</code>```

I can still access the WSDL file from my browser, but nevertheless I still get the same error when adding the service reference to the client. The same happens if I test it via dotnet-svcutil http://<host>:<port><path>?wsdl

If I try to add the service reference locally everything works without any issues.

Additional information:

I already installed .NET Framework 4.6 and it's  WCF HTTP Activation handler.

I added the permission IIS_IUSRS to the folder containing the service.

Any ideas to why this happens and what I could do to fix this problem?

答:
If you use transport security mode, why not use https addresses?  The https/http base address should be configured in IIS site binding module.

In addition, since you are using basic authentication, please turn on anonymous authentication and basic authentication in the IIS authentication module.

On my side, I can add service references correctly using the Core-based console application.

Besides, Please enable the following windows feature for WCF.

Feel free to let me know if there is anything I can help with.

Body:
I have been trying to publish a WCF web service on my IIS server using a nonstandard HTTPS port. Access to the server should only be possible after authentication (via basic authentication). The web service I created for testing purposes is the base project you get by default when creating a WCF Service Application in Visual Studio. The only modifications I made are in the web.config file:

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <bindings>
      <basicHttpBinding>
        <binding name="secureHttpBinding">
          <security mode="Transport">
            <transport clientCredentialType="Basic"/>
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <services>
      <service name="SoapApi.Service1">
        <endpoint address=""
                  binding="basicHttpBinding"
                  bindingConfiguration="secureHttpBinding"
                  contract="SoapApi.IService1"/>

        <endpoint address="mex"
                  binding="mexHttpsBinding"
                  contract="IMetadataExchange" />
      </service>
    </services>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

After the service was published on the local file system and the IIS was configured. I was able to reach the WSDL file on the server after authentication from the browser on my local PC. But if I'm trying to add the service to a simple client application using the Configure WCF Web Service Reference wizard from Visual Studio, I get the following error message:

Metadata contains a reference that cannot be resolved:'http://<host>:<port><path>?wsdl'.

and the full error message:

An error occurred while attempting to find services at 'http://<host>:<port><path>?wsdl'. The remote server returned an error: (403) Forbidden.

Since this error indicates that I don't have access permission, I thought why not turn off authentication and try if it works. I activated anonymous access for the website in IIS and deactivated basic authentication.
Furthermore I changed the following passage in the web.config file:

<basicHttpBinding>
    <binding name="secureHttpBinding">
      <security mode="Transport">
        <transport clientCredentialType="None"/>
      </security>
    </binding>
 </basicHttpBinding>

I can still access the WSDL file from my browser, but nevertheless I still get the same error when adding the service reference to the client. The same happens if I test it via dotnet-svcutil http://<host>:<port><path>?wsdl

If I try to add the service reference locally everything works without any issues.

Additional information:

I already installed .NET Framework 4.6 and it's  WCF HTTP Activation handler.

I added the permission IIS_IUSRS to the folder containing the service.

Any ideas to why this happens and what I could do to fix this problem?


问:
How to compare element position in xpath
I am trying to compare customer account values to display only different values and ignore duplicate in XPath:

XML code:

```<code><info>
  <Customer CustAccount="1"/>
  <Customer CustAccount="2"/>
  <Customer CustAccount="2"/>
  <Customer CustAccount="3"/>
</info>
</code>```

The result should compare customer 1/2/3 and display:

```<code>customer 1
customer 2
customer 3
</code>```

答:
Here is the pure xpath 1.0 solution.

Sample xml:

```<code><root >
    <info>
      <Customer CustAccount="1"/>
      <Customer CustAccount="2"/>
      <Customer CustAccount="2"/>
      <Customer CustAccount="3"/>
    </info>
</root>
</code>```

xpath 1.0:

```<code>/root/info/Customer[not(./@CustAccount=preceding::Customer/@CustAccount)]
</code>```

Evidence:

Body:
I am trying to compare customer account values to display only different values and ignore duplicate in XPath:

XML code:

<info>
  <Customer CustAccount="1"/>
  <Customer CustAccount="2"/>
  <Customer CustAccount="2"/>
  <Customer CustAccount="3"/>
</info>

The result should compare customer 1/2/3 and display:

customer 1
customer 2
customer 3

Body:
Here is the pure xpath 1.0 solution.

Sample xml:

<root >
    <info>
      <Customer CustAccount="1"/>
      <Customer CustAccount="2"/>
      <Customer CustAccount="2"/>
      <Customer CustAccount="3"/>
    </info>
</root>

xpath 1.0:

/root/info/Customer[not(./@CustAccount=preceding::Customer/@CustAccount)]

Evidence:


问:
How to make a rotated image fill available space in Flutter?
I'm trying to display an image as a rounded diamond shape. I can get the rotations to work and if I use debugPaintSizeEnabled it shows the diamond shape, but the image won't fill that space. How can I get it to expand to fill the diamond?

Here's a screenshot:

This is the code that creates the diamond widget:

```<code>Transform.rotate(
        angle: math.pi / 4,
        child: ClipRRect(
          borderRadius: new BorderRadius.circular(24.0),
          child: Transform.rotate(
            angle: - math.pi / 4,
            child: Image(
              image: AssetImage("img/kitten_200_1.jpeg"),
              fit: BoxFit.cover,
            ),
          ),
        ),
      ),
</code>```

答:
1) Transform.rotate doesn't affect child's sizing and positioning — it changes how the child is painted only.

2) Because there is no image data in white "triangles" at your screenshot, to fill them with image we should scale the image up. But then it will overlap neighbor widgets, so we will also scale the diamond down.

```<code>double L = 100; // image side length
double R = 24; // rounding radius
double k = sqrt(2) - R / L * 2 * (sqrt(2) - 1); // a little bit of geometry
</code>```

Now scale!

```<code>Transform.rotate(
  angle: pi / 4,
  child: Transform.scale(
    scale: 1 / k,
    child: ClipRRect(
      borderRadius: new BorderRadius.circular(R),
      child: Transform.rotate(
        angle: - pi / 4,
        child: Transform.scale(
          scale: k,
          child: Image(
            image: ...,
            width: L,
            height: L,
            fit: BoxFit.cover,
          ),
        ),
      ),
    ),
  ),
);
</code>```

Body:
I'm trying to display an image as a rounded diamond shape. I can get the rotations to work and if I use debugPaintSizeEnabled it shows the diamond shape, but the image won't fill that space. How can I get it to expand to fill the diamond?

Here's a screenshot:

This is the code that creates the diamond widget:

Transform.rotate(
        angle: math.pi / 4,
        child: ClipRRect(
          borderRadius: new BorderRadius.circular(24.0),
          child: Transform.rotate(
            angle: - math.pi / 4,
            child: Image(
              image: AssetImage("img/kitten_200_1.jpeg"),
              fit: BoxFit.cover,
            ),
          ),
        ),
      ),

Body:
1) Transform.rotate doesn't affect child's sizing and positioning — it changes how the child is painted only.

2) Because there is no image data in white "triangles" at your screenshot, to fill them with image we should scale the image up. But then it will overlap neighbor widgets, so we will also scale the diamond down.

double L = 100; // image side length
double R = 24; // rounding radius
double k = sqrt(2) - R / L * 2 * (sqrt(2) - 1); // a little bit of geometry

Now scale!

Transform.rotate(
  angle: pi / 4,
  child: Transform.scale(
    scale: 1 / k,
    child: ClipRRect(
      borderRadius: new BorderRadius.circular(R),
      child: Transform.rotate(
        angle: - pi / 4,
        child: Transform.scale(
          scale: k,
          child: Image(
            image: ...,
            width: L,
            height: L,
            fit: BoxFit.cover,
          ),
        ),
      ),
    ),
  ),
);


问:
Automatically parse query parameter to object when defined in NestJS
I am writing a NestJS application. Some of the endpoints support sorting e.g. http://127.0.0.1:3000/api/v1/members?sort=-id&take=100 Which means sort by id descending.

This parameter arrives as a @Query parameter and is passed to my service. This service transforms it into an object which is used by TypeORM:

```<code>{
  id: 'DESC'
}
</code>```

I don't want to call this conversion method manually every time I need sorting.

I've tried an intercepter but this one could not easily change the request parameters into the desired object.

A pipe worked but then I still need to add @Query(new SortPipe()) for every endpoint definition.

Another option is in the repository itself. The NestJS documentation is very well written, but misses guidance in where to put what.

Is there someone who had a similar issue with converting Query parameters before they are used in NestJS, and can explain what approach is the best within NestJS?

This question might look like an opinion based question, however I am looking for the way it is supposed to be done with the NestJS philosophy in mind.

答:
Pipes are probably the easiest way to accomplish this. Instead of adding your pipe for every endpoint definition you can add a global pipe that will be called on every endpoint. In your main.ts:

async function bootstrap() {
  ...
  app.useGlobalPipes(new SortPipe());
  ...
}
```

<p>You can then create a pipe like this:</p>

<pre class="lang-js prettyprint-override"><code>import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';

@Injectable()
export class SortPipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    const { type } = metadata;
    // Make sure to only run your logic on queries
    if (type === 'query') return this.transformQuery(value);

    return value;
  }

  transformQuery(query: any) {
    if (typeof query !== 'object' || !value) return query;

    const { sort } = query;
    if (sort) query.sort = convertForTypeOrm(sort);

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

If you do not want sort value on ALL endpoints to be automatically converted, you can pass custom parameter to @Query(), for example @Query('sort'). And then:

  transform(value: any, metadata: ArgumentMetadata) {
    const { type, data } = metadata;
    // Make sure to only run your logic on queries when 'sort' is supplied
    if (type === 'query' && data === 'sort') return this.transformQuery(value);

    return value;
  }
```

Body:
I am writing a NestJS application. Some of the endpoints support sorting e.g. http://127.0.0.1:3000/api/v1/members?sort=-id&take=100 Which means sort by id descending.

This parameter arrives as a @Query parameter and is passed to my service. This service transforms it into an object which is used by TypeORM:

{
  id: 'DESC'
}

I don't want to call this conversion method manually every time I need sorting.

I've tried an intercepter but this one could not easily change the request parameters into the desired object.

A pipe worked but then I still need to add @Query(new SortPipe()) for every endpoint definition.

Another option is in the repository itself. The NestJS documentation is very well written, but misses guidance in where to put what.

Is there someone who had a similar issue with converting Query parameters before they are used in NestJS, and can explain what approach is the best within NestJS?

This question might look like an opinion based question, however I am looking for the way it is supposed to be done with the NestJS philosophy in mind.

Body:
Pipes are probably the easiest way to accomplish this. Instead of adding your pipe for every endpoint definition you can add a global pipe that will be called on every endpoint. In your main.ts:

async function bootstrap() {
  ...
  app.useGlobalPipes(new SortPipe());
  ...
}

You can then create a pipe like this:

import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';

@Injectable()
export class SortPipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    const { type } = metadata;
    // Make sure to only run your logic on queries
    if (type === 'query') return this.transformQuery(value);

    return value;
  }

  transformQuery(query: any) {
    if (typeof query !== 'object' || !value) return query;

    const { sort } = query;
    if (sort) query.sort = convertForTypeOrm(sort);

    return query;
  }
}

If you do not want sort value on ALL endpoints to be automatically converted, you can pass custom parameter to @Query(), for example @Query('sort'). And then:

  transform(value: any, metadata: ArgumentMetadata) {
    const { type, data } = metadata;
    // Make sure to only run your logic on queries when 'sort' is supplied
    if (type === 'query' && data === 'sort') return this.transformQuery(value);

    return value;
  }


问:
Why am I having to redeclare an extern function?
I'm currently reading Advanced Programming in the Unix Environment by Richard Stevens, and I wrote a basic program to test out how to create filesystem links. After that worked without a problem, I decided to implement some options, starting with the ability to specify -s via the command line to create a symbolic link instead of a hard link. To do this, I typedef'd link_fn, which is set to link unless the user specifies -s in which case it is set to symlink.

The problem is that I have to include extern int symlink(const char* actualpath, const char* sympath);, or I get the following error when I run the makefile:

```<code>link/link.c: In function ‘main’:
link/link.c:30:18: error: ‘symlink’ undeclared (first use in this function)
   30 |             fn = symlink;
      |                  ^~~~~~~
link/link.c:30:18: note: each undeclared identifier is reported only once for each function it appears in
make: *** [Makefile;31: link.o] Error 1
</code>```

What's weird is I double-checked both the book and the man pages (man 2 symlink) and both of them say the symlink function is declared in the unistd.h header. My header section looks like this:

```<code>#if defined(__unix__)
    #include <unistd.h>

    #include <dirent.h>
    #include <fcntl.h>

    #include <sys/mman.h>
    #include <sys/random.h>
    #include <sys/stat.h>
    #include <sys/syscall.h>
    #include <sys/sysctl.h>
    #include <sys/sysinfo.h>
    #include <sys/termios.h>
    #include <sys/types.h>
    #include <sys/user.h>
#elif defined(_WIN32)
    ...
#endif // OS-Dependent modules

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
...
</code>```

I first made sure __unix__ was defined, and both the symlink and link functions work without a problem, but only as long as I declare symlink as external, like so:

```<code>extern int symlink(const char* actualpath, const char* sympath);
</code>```

I then ran gcc with the -E option to see if unistd.h was actually being included and, sure enough, it was being included successfully and the symlink function was right there:

```<code>extern int symlink (const char *__from, const char *__to)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))) ;
</code>```

So why is it that I'm getting a compiler error when I don't declare the symlink function prototype myself? And why is it that the link function isn't giving me this problem when they're declared in the same header file, in the exact same way?

Here is the link function, also from the preprocessor output I generated while debugging.

```<code>extern int link (const char *__from, const char *__to)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))) ;
</code>```

```<code>#if defined(__unix__)
    #include <unistd.h>

    #include <dirent.h>
    #include <fcntl.h>
#elif defined(_WIN32)
    // Removed for brevity
#endif // OS-Dependent modules

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

#if !defined(FALSE) || !defined(TRUE)
enum { FALSE, TRUE };
#endif // TRUE || FALSE

// Why does the compiler require this declaration, and only for symlink?
extern int symlink(const char* actualpath, const char* sympath);

typedef int (*link_fn)(const char* path, const char* link_path);

int main(int argc, char *argv[])
{
    if (argc == 2) {
        if (strcmp(argv[1], "--help") == 0) {
            printf("\nUsage: %s <Existing Filename> <New Filename>\n\n", argv[0]);
            printf("Options: \n");
            printf("  -s    Create symbolic link instead of a hard link\n\n");

            return EXIT_SUCCESS;
        }
    }

    if (argc < 3) {
        fprintf(stderr, "Usage: %s <Existing Filename> <New Filename>\n", argv[0]);

        return EXIT_FAILURE;
    }

    link_fn fn = link;

    for (size_t i = 1; i < (size_t) argc - 2; ++i) {
        if (strcmp(argv[i], "-s") == 0) {
            fn = symlink;
        }
    }

    const char* existing_path = argv[argc - 2];
    const char* new_path      = argv[argc - 1];

    errno = 0;

    const int return_code = fn(existing_path, new_path);

    if (return_code == -1) {
        fprintf(stderr, "[Error] %s\n", strerror(errno));

        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
</code>```

The program is being compiled using:

```<code>CC=gcc
CFLAGS="-std=c17 -Wall -Wextra -Werror -pedantic"
</code>```

System Info

```<code>gcc version 9.1.0
Manjaro Linux 18.0.4
x86-64
</code>```

MRE

Here is a minimal example, on the counsel of Eric Postpischil:

```<code>#if defined(__unix__)
#include <unistd.h>
#endif

int (*a)(const char*, const char*) = link;
int (*b)(const char*, const char*) = symlink;

int main(void)
{
    //
}
</code>```

Running make yields the following output:

```<code>gcc -I include -E -o link.pp link/link.c
gcc -I include -S -masm=intel -o link.asm link/link.c
gcc -std=c17 -Wall -Wextra -Werror -pedantic  -I include -c -o link.o link/link.c
link/link.c:9:38: error: ‘symlink’ undeclared here (not in a function)
    9 | int (*b)(const char*, const char*) = symlink;
      |                                      ^~~~~~~
make: *** [Makefile;31: link.o] Error 1
</code>```

The preprocessed output is as follows.

```<code> 1  # 1 "link/link.c"
 2  # 1 "<built-in>"
 3  # 1 "<command-line>"
 4  # 31 "<command-line>"
 5  # 1 "/usr/include/stdc-predef.h" 1 3 4
 6  # 32 "<command-line>" 2
 7  # 1 "link/link.c"
 ...
12  # 1 "/usr/include/unistd.h" 1 3 4
13  # 25 "/usr/include/unistd.h" 3 4
14  # 1 "/usr/include/features.h" 1 3 4
15  # 450 "/usr/include/features.h" 3 4
16  # 1 "/usr/include/sys/cdefs.h" 1 3 4
17  # 452 "/usr/include/sys/cdefs.h" 3 4
18  # 1 "/usr/include/bits/wordsize.h" 1 3 4
19  # 453 "/usr/include/sys/cdefs.h" 2 3 4
20  # 1 "/usr/include/bits/long-double.h" 1 3 4
21  # 454 "/usr/include/sys/cdefs.h" 2 3 4
22  # 451 "/usr/include/features.h" 2 3 4
23  # 474 "/usr/include/features.h" 3 4
24  # 1 "/usr/include/gnu/stubs.h" 1 3 4
25  # 10 "/usr/include/gnu/stubs.h" 3 4
26  # 1 "/usr/include/gnu/stubs-64.h" 1 3 4
27  # 11 "/usr/include/gnu/stubs.h" 2 3 4
28  # 475 "/usr/include/features.h" 2 3 4
29  # 26 "/usr/include/unistd.h" 2 3 4
...
32  # 202 "/usr/include/unistd.h" 3 4
33  # 1 "/usr/include/bits/posix_opt.h" 1 3 4
34  # 203 "/usr/include/unistd.h" 2 3 4
...
38  # 1 "/usr/include/bits/environments.h" 1 3 4
39  # 22 "/usr/include/bits/environments.h" 3 4
40  # 1 "/usr/include/bits/wordsize.h" 1 3 4
41  # 23 "/usr/include/bits/environments.h" 2 3 4
42  # 207 "/usr/include/unistd.h" 2 3 4
43  # 217 "/usr/include/unistd.h" 3 4
44  # 1 "/usr/include/bits/types.h" 1 3 4
45  # 27 "/usr/include/bits/types.h" 3 4
46  # 1 "/usr/include/bits/wordsize.h" 1 3 4
47  # 28 "/usr/include/bits/types.h" 2 3 4
48  # 1 "/usr/include/bits/timesize.h" 1 3 4
49  # 29 "/usr/include/bits/types.h" 2 3 4
...
53  # 31 "/usr/include/bits/types.h" 3 4
54  typedef unsigned char __u_char;
</code>```

Other function declarations and enums are declared for about a thousand lines. Then, on line 1169:

```<code>  1169  extern int link (const char *__from, const char *__to)
  1170       __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))) ;
  1171
  1172
  1173
  1174
  1175  extern int linkat (int __fromfd, const char *__from, int __tofd,
  1176       const char *__to, int __flags)
  1177       __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 4))) ;
  1178
  1179
  1180
  1181
  1182  extern int symlink (const char *__from, const char *__to)
  1183       __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))) ;
</code>```

And skipping a few hundred lines of similar declarations:

```<code>  1416
  1417  # 6 "link/link.c" 2
  1418
  1419
  1420
  1421  # 8 "link/link.c"
  1422  int (*a)(const char*, const char*) = link;
  1423  int (*b)(const char*, const char*) = symlink;
  1424
  1425  int main(void)
  1426  {
  1427
  1428  }
</code>```

答:
In order for symlink to be declared, you need to #define the correct feature-test macro, as indicated in the symlink manpage:

```<code>Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

       symlink():
           _XOPEN_SOURCE >= 500 || _POSIX_C_SOURCE >= 200112L
               || /* Glibc versions <= 2.19: */ _BSD_SOURCE
</code>```

You should get in the habit of using feature-test macros, although the Gnu headers generally allow you to omit them if you use the default -std option, or any -std option starting with gnu. gnu "standards" define the _GNU_SOURCE feature-test macro, which effectively bypasses all feature tests. That might be considered convenient by some, but it leads to annoying portability issues.

Although it is technically better to put the definition at the top of every source file, I find it more convenient to put -D_XOPEN_SOURCE=700 in my CFLAGS, which also guarantees that the definition comes before any #include.

Also, please be aware that if you want to accurately preprocess source code, you need to ensure that your CFLAGS are the same for the preprocessing command as for your compilation. Otherwise you might miss the fact that some symbols are not defined (or predefined) with stricter -std options.

Body:
I'm currently reading Advanced Programming in the Unix Environment by Richard Stevens, and I wrote a basic program to test out how to create filesystem links. After that worked without a problem, I decided to implement some options, starting with the ability to specify -s via the command line to create a symbolic link instead of a hard link. To do this, I typedef'd link_fn, which is set to link unless the user specifies -s in which case it is set to symlink.

The problem is that I have to include extern int symlink(const char* actualpath, const char* sympath);, or I get the following error when I run the makefile:

link/link.c: In function ‘main’:
link/link.c:30:18: error: ‘symlink’ undeclared (first use in this function)
   30 |             fn = symlink;
      |                  ^~~~~~~
link/link.c:30:18: note: each undeclared identifier is reported only once for each function it appears in
make: *** [Makefile;31: link.o] Error 1

What's weird is I double-checked both the book and the man pages (man 2 symlink) and both of them say the symlink function is declared in the unistd.h header. My header section looks like this:

#if defined(__unix__)
    #include <unistd.h>

    #include <dirent.h>
    #include <fcntl.h>

    #include <sys/mman.h>
    #include <sys/random.h>
    #include <sys/stat.h>
    #include <sys/syscall.h>
    #include <sys/sysctl.h>
    #include <sys/sysinfo.h>
    #include <sys/termios.h>
    #include <sys/types.h>
    #include <sys/user.h>
#elif defined(_WIN32)
    ...
#endif // OS-Dependent modules

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

I first made sure __unix__ was defined, and both the symlink and link functions work without a problem, but only as long as I declare symlink as external, like so:

extern int symlink(const char* actualpath, const char* sympath);

I then ran gcc with the -E option to see if unistd.h was actually being included and, sure enough, it was being included successfully and the symlink function was right there:

extern int symlink (const char *__from, const char *__to)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))) ;

So why is it that I'm getting a compiler error when I don't declare the symlink function prototype myself? And why is it that the link function isn't giving me this problem when they're declared in the same header file, in the exact same way?

Here is the link function, also from the preprocessor output I generated while debugging.

extern int link (const char *__from, const char *__to)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))) ;

#if defined(__unix__)
    #include <unistd.h>

    #include <dirent.h>
    #include <fcntl.h>
#elif defined(_WIN32)
    // Removed for brevity
#endif // OS-Dependent modules

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

#if !defined(FALSE) || !defined(TRUE)
enum { FALSE, TRUE };
#endif // TRUE || FALSE

// Why does the compiler require this declaration, and only for symlink?
extern int symlink(const char* actualpath, const char* sympath);

typedef int (*link_fn)(const char* path, const char* link_path);

int main(int argc, char *argv[])
{
    if (argc == 2) {
        if (strcmp(argv[1], "--help") == 0) {
            printf("\nUsage: %s <Existing Filename> <New Filename>\n\n", argv[0]);
            printf("Options: \n");
            printf("  -s    Create symbolic link instead of a hard link\n\n");

            return EXIT_SUCCESS;
        }
    }

    if (argc < 3) {
        fprintf(stderr, "Usage: %s <Existing Filename> <New Filename>\n", argv[0]);

        return EXIT_FAILURE;
    }

    link_fn fn = link;

    for (size_t i = 1; i < (size_t) argc - 2; ++i) {
        if (strcmp(argv[i], "-s") == 0) {
            fn = symlink;
        }
    }

    const char* existing_path = argv[argc - 2];
    const char* new_path      = argv[argc - 1];

    errno = 0;

    const int return_code = fn(existing_path, new_path);

    if (return_code == -1) {
        fprintf(stderr, "[Error] %s\n", strerror(errno));

        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

The program is being compiled using:

CC=gcc
CFLAGS="-std=c17 -Wall -Wextra -Werror -pedantic"

System Info

gcc version 9.1.0
Manjaro Linux 18.0.4
x86-64

MRE

Here is a minimal example, on the counsel of Eric Postpischil:

#if defined(__unix__)
#include <unistd.h>
#endif

int (*a)(const char*, const char*) = link;
int (*b)(const char*, const char*) = symlink;

int main(void)
{
    //
}

Running make yields the following output:

gcc -I include -E -o link.pp link/link.c
gcc -I include -S -masm=intel -o link.asm link/link.c
gcc -std=c17 -Wall -Wextra -Werror -pedantic  -I include -c -o link.o link/link.c
link/link.c:9:38: error: ‘symlink’ undeclared here (not in a function)
    9 | int (*b)(const char*, const char*) = symlink;
      |                                      ^~~~~~~
make: *** [Makefile;31: link.o] Error 1

The preprocessed output is as follows.

 1  # 1 "link/link.c"
 2  # 1 "<built-in>"
 3  # 1 "<command-line>"
 4  # 31 "<command-line>"
 5  # 1 "/usr/include/stdc-predef.h" 1 3 4
 6  # 32 "<command-line>" 2
 7  # 1 "link/link.c"
 ...
12  # 1 "/usr/include/unistd.h" 1 3 4
13  # 25 "/usr/include/unistd.h" 3 4
14  # 1 "/usr/include/features.h" 1 3 4
15  # 450 "/usr/include/features.h" 3 4
16  # 1 "/usr/include/sys/cdefs.h" 1 3 4
17  # 452 "/usr/include/sys/cdefs.h" 3 4
18  # 1 "/usr/include/bits/wordsize.h" 1 3 4
19  # 453 "/usr/include/sys/cdefs.h" 2 3 4
20  # 1 "/usr/include/bits/long-double.h" 1 3 4
21  # 454 "/usr/include/sys/cdefs.h" 2 3 4
22  # 451 "/usr/include/features.h" 2 3 4
23  # 474 "/usr/include/features.h" 3 4
24  # 1 "/usr/include/gnu/stubs.h" 1 3 4
25  # 10 "/usr/include/gnu/stubs.h" 3 4
26  # 1 "/usr/include/gnu/stubs-64.h" 1 3 4
27  # 11 "/usr/include/gnu/stubs.h" 2 3 4
28  # 475 "/usr/include/features.h" 2 3 4
29  # 26 "/usr/include/unistd.h" 2 3 4
...
32  # 202 "/usr/include/unistd.h" 3 4
33  # 1 "/usr/include/bits/posix_opt.h" 1 3 4
34  # 203 "/usr/include/unistd.h" 2 3 4
...
38  # 1 "/usr/include/bits/environments.h" 1 3 4
39  # 22 "/usr/include/bits/environments.h" 3 4
40  # 1 "/usr/include/bits/wordsize.h" 1 3 4
41  # 23 "/usr/include/bits/environments.h" 2 3 4
42  # 207 "/usr/include/unistd.h" 2 3 4
43  # 217 "/usr/include/unistd.h" 3 4
44  # 1 "/usr/include/bits/types.h" 1 3 4
45  # 27 "/usr/include/bits/types.h" 3 4
46  # 1 "/usr/include/bits/wordsize.h" 1 3 4
47  # 28 "/usr/include/bits/types.h" 2 3 4
48  # 1 "/usr/include/bits/timesize.h" 1 3 4
49  # 29 "/usr/include/bits/types.h" 2 3 4
...
53  # 31 "/usr/include/bits/types.h" 3 4
54  typedef unsigned char __u_char;

Other function declarations and enums are declared for about a thousand lines. Then, on line 1169:

  1169  extern int link (const char *__from, const char *__to)
  1170       __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))) ;
  1171
  1172
  1173
  1174
  1175  extern int linkat (int __fromfd, const char *__from, int __tofd,
  1176       const char *__to, int __flags)
  1177       __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 4))) ;
  1178
  1179
  1180
  1181
  1182  extern int symlink (const char *__from, const char *__to)
  1183       __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))) ;

And skipping a few hundred lines of similar declarations:

  1416
  1417  # 6 "link/link.c" 2
  1418
  1419
  1420
  1421  # 8 "link/link.c"
  1422  int (*a)(const char*, const char*) = link;
  1423  int (*b)(const char*, const char*) = symlink;
  1424
  1425  int main(void)
  1426  {
  1427
  1428  }

Body:
In order for symlink to be declared, you need to #define the correct feature-test macro, as indicated in the symlink manpage:

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

       symlink():
           _XOPEN_SOURCE >= 500 || _POSIX_C_SOURCE >= 200112L
               || /* Glibc versions <= 2.19: */ _BSD_SOURCE

You should get in the habit of using feature-test macros, although the Gnu headers generally allow you to omit them if you use the default -std option, or any -std option starting with gnu. gnu "standards" define the _GNU_SOURCE feature-test macro, which effectively bypasses all feature tests. That might be considered convenient by some, but it leads to annoying portability issues.

Although it is technically better to put the definition at the top of every source file, I find it more convenient to put -D_XOPEN_SOURCE=700 in my CFLAGS, which also guarantees that the definition comes before any #include.

Also, please be aware that if you want to accurately preprocess source code, you need to ensure that your CFLAGS are the same for the preprocessing command as for your compilation. Otherwise you might miss the fact that some symbols are not defined (or predefined) with stricter -std options.