问:
Run an R Markdown based on interactive parameter choice
I am trying to do the following on R Markdown. Basically, I would like the user to be able to select between two values of a parameter called "Machine" and based on the value selected run some chunks and not others. I know that the "eval" option might be useful here but I have no clue on how to use it in order to reach my goal.
My code for the moment is this (in R Markdown):

```<code>    ---
title: "SUM and SAM"
output: html_document
params:
  machine:
  label: "Machine"
  value: SUM
  input: select
  choices: [SUM, SAM]
  printcode:
    label: "Display Code:"
    value: TRUE
  date: !r Sys.Date()
  data:
    label: "Input dataset:"
    value: None
    input: file
  years_of_study:
    input: slider
    min: 2018
    max: 2020
    step: 1
    round: 1
    sep: ''
    value: [2018, 2019]

---

```{r setup, include=FALSE}

############# IMPORTANT ###################################
#Remember to Knit with Parameters here using the "Knit button"--> "Knit with Parameters".
####################################################

#If you only want the parameters to be shown, run the following.
#knit_with_parameters('~/Desktop/Papers/git_hub/sum_sam.Rmd')

#This must be left uncommented if we want to show the content of the Markdown file once "Knit with Parameters" is pressed.
knitr::opts_chunk$set(echo = TRUE)
```
<p>Say now I would like a chunk that will execute only if machine = SAM. How can I do that?</p>
<p>Was thinking about something like:</p>
```{r pressure, echo=FALSE, eval=params$machine}
plot(pressure)
```

but does not work

Thank you,

Federico

答:
Let there be a file called foo.Rmd with this content:

```<code>---
title: "SUM and SAM"
output: html_document
params:
  machine:
    input: select
    choices: [SUM, SAM]
    value: SUM
---

```{r, eval = params$machine == "SAM", echo=FALSE}
print("SAM was chosen")
```

```{r, eval = params$machine == "SUM", echo=FALSE}
print("SUM was chosen")
```
</code>```

Then you can do:

```<code>rmarkdown::render("foo.Rmd", params = list(machine = "SAM"))
</code>```

Alternativeley, there is the option knit with parameters in RStudio:

Resulting in foo.html:

Body:
I am trying to do the following on R Markdown. Basically, I would like the user to be able to select between two values of a parameter called "Machine" and based on the value selected run some chunks and not others. I know that the "eval" option might be useful here but I have no clue on how to use it in order to reach my goal.
My code for the moment is this (in R Markdown):

    ---
title: "SUM and SAM"
output: html_document
params:
  machine:
  label: "Machine"
  value: SUM
  input: select
  choices: [SUM, SAM]
  printcode:
    label: "Display Code:"
    value: TRUE
  date: !r Sys.Date()
  data:
    label: "Input dataset:"
    value: None
    input: file
  years_of_study:
    input: slider
    min: 2018
    max: 2020
    step: 1
    round: 1
    sep: ''
    value: [2018, 2019]

---

```{r setup, include=FALSE}

############# IMPORTANT ###################################
#Remember to Knit with Parameters here using the "Knit button"--> "Knit with Parameters".
####################################################

#If you only want the parameters to be shown, run the following.
#knit_with_parameters('~/Desktop/Papers/git_hub/sum_sam.Rmd')

#This must be left uncommented if we want to show the content of the Markdown file once "Knit with Parameters" is pressed.
knitr::opts_chunk$set(echo = TRUE)

Say now I would like a chunk that will execute only if machine = SAM. How can I do that?

Was thinking about something like:

{r pressure, echo=FALSE, eval=params$machine}
plot(pressure)

but does not work

Thank you,

Federico

Body:
Let there be a file called foo.Rmd with this content:

---
title: "SUM and SAM"
output: html_document
params:
  machine:
    input: select
    choices: [SUM, SAM]
    value: SUM
---

```{r, eval = params$machine == "SAM", echo=FALSE}
print("SAM was chosen")
```

```{r, eval = params$machine == "SUM", echo=FALSE}
print("SUM was chosen")
```

Then you can do:

rmarkdown::render("foo.Rmd", params = list(machine = "SAM"))

Alternativeley, there is the option knit with parameters in RStudio:

Resulting in foo.html:


来源: stackexchange

问:
GPG verify file and detached signature with given public key
I have a public key pubkey.asc.
Also I have a file file.txt and its detached signature file.txt.asc.

I want to check the following steps:

file.txt.asc is a signature for file.txt

file.txt.asc was created using secret key from a keyring with public key pubkey.asc

I can do the 1st step using gpg --verify file.txt.asc file.txt. This command outputs public key fingerprint which was used to create a signature:

```<code>gpg: Signature made <date and time>
gpg: using RSA key <fingerprint>
...
</code>```

I can see pubkey.asc fingerprint just by running gpg pubkey.asc.

Can I use this information and just check if fingerprints are equal to perform 2nd step? If not, how can I verify a file signature with given public key?

I saw this question about how to verify if signature matches public key, but it only works if key has extension .gpg which is not my case.

答:
OpenPGP key's fingerprint is a SHA1 hash of public key itself plus some additional data, and it uniquely identifies the key (excluding collision cases, which are not known yet for OpenPGP key fingerprints).

So, yeah, seeing 'good signature made by key [fingerprint]' is enough to rely on fact that signature is made by the aforementioned key.

ContentLicense: CC BY-SA 4.0

Body:
I have a public key pubkey.asc.
Also I have a file file.txt and its detached signature file.txt.asc.

I want to check the following steps:

file.txt.asc is a signature for file.txt

file.txt.asc was created using secret key from a keyring with public key pubkey.asc

I can do the 1st step using gpg --verify file.txt.asc file.txt. This command outputs public key fingerprint which was used to create a signature:

gpg: Signature made <date and time>
gpg: using RSA key <fingerprint>
...

I can see pubkey.asc fingerprint just by running gpg pubkey.asc.

Can I use this information and just check if fingerprints are equal to perform 2nd step? If not, how can I verify a file signature with given public key?

I saw this question about how to verify if signature matches public key, but it only works if key has extension .gpg which is not my case.


问:
How to pass data from nodejs to inside html script tags
I'm using expressjs as a server on 8000 port. I want to send a string value from expressjs file to html script tags and use this string value in script tags.
name variable is coming as a empty string now.
How can i console.log name variable's value?

static-pages-server.js:

```<code> app.get('/index', function(req, res) {
        var name = "hello";
        res.render(__dirname + "/static-pages/journey-analize-report/index.html", {name:name});
    });
</code>```

index.html:

```<code> <script type="text/javascript">
        console.log(name);
 </script>
</code>```

Edit : I used ejs and now problem is how should i describe name attribute in script tags? Below code is giving syntax error.

```<code><script type="text/javascript">
        console.log(<%=name%>);
 </script>
</code>```

答:
Local variables sent to a view via the locals parameter using the res.render() method aren't directly accessible. Instead you need to refer to those using it's variable name wrapped inside double curly brackets. So if you want to use it inside a JavaScript function, you need declare a local variable and give it the content of your name local.

Simply modify your index.html like this:

```<code><script type="text/javascript">
    let name = "{{name}}";
    console.log(name);
</script>
</code>```

Body:
I'm using expressjs as a server on 8000 port. I want to send a string value from expressjs file to html script tags and use this string value in script tags.
name variable is coming as a empty string now.
How can i console.log name variable's value?

static-pages-server.js:

 app.get('/index', function(req, res) {
        var name = "hello";
        res.render(__dirname + "/static-pages/journey-analize-report/index.html", {name:name});
    });

index.html:

Edit : I used ejs and now problem is how should i describe name attribute in script tags? Below code is giving syntax error.

Body:
Local variables sent to a view via the locals parameter using the res.render() method aren't directly accessible. Instead you need to refer to those using it's variable name wrapped inside double curly brackets. So if you want to use it inside a JavaScript function, you need declare a local variable and give it the content of your name local.

Simply modify your index.html like this:

<script type="text/javascript">
    let name = "{{name}}";
    console.log(name);
</script>


问:
In Ramda.js, why must use identity to get `R.countBy()` to work?
My apologies if this is a duplicate. I didn't find an answer elsewhere.

Ramda.js provides the countBy() function. From the documentation we can see:

const R = require("ramda")

const letters = ['a', 'b', 'A', 'a', 'B', 'c'];
R.countBy(R.toLower)(letters);   //=> {'a': 3, 'b': 2, 'c': 1}
```
<p>But what if we already have our <code>letters</code> in lowercase? That is, we don't need any extra step, but just to count. For example, let's say I want to simply count <code>letters2</code> array:</p>
<pre class="lang-js prettyprint-override"><code>const letters2 = ["a", "a", "a", "a", "b", "b", "c", "c", "c", "c"]
R.countBy(letters2) // doesn't work
</code>```

Instead, we must add some identity expression such as:

R.countBy(x => x)(letters2)
// gives {"a": 4, "b": 2, "c": 4}
```
<p>or</p>
<pre class="lang-js prettyprint-override"><code>R.countBy(R.identity)(letters2)
</code>```

This isn't always the case with other Ramda functions (e.g., R.isNil()). I'm trying to understand where this extra step of identity comes from. To me it seems unnecessary, but I'm probably missing something.

Thanks!

答:
The reason is that ramda simply does not make any assumption on how you want to count your list...

const  list = ['A', 'b', 'c', 'D', 'e', 'f', 'g', 'G', 'F'];

// simply count
console.log(
  R.countBy(R.identity, list),
)

// or count case insensitively
console.log(
  R.countBy(R.toLower, list),
)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.js" integrity="sha512-ZZcBsXW4OcbCTfDlXbzGCamH1cANkg6EfZAN2ukOl7s5q8skbB+WndmAqFT8fuMzeuHkceqd5UbIDn7fcqJFgg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script></code>```

Also, do not forget that you can build up your functions by leveraging partial application.

Note the wording, countBy as if Ramda wants to be told how to count. but nothing prevents you from building your own count.

```<code>const count = R.countBy(R.identity);

console.log(count(list))
</code>```

Body:
My apologies if this is a duplicate. I didn't find an answer elsewhere.

Ramda.js provides the countBy() function. From the documentation we can see:

const R = require("ramda")

const letters = ['a', 'b', 'A', 'a', 'B', 'c'];
R.countBy(R.toLower)(letters);   //=> {'a': 3, 'b': 2, 'c': 1}

But what if we already have our letters in lowercase? That is, we don't need any extra step, but just to count. For example, let's say I want to simply count letters2 array:

const letters2 = ["a", "a", "a", "a", "b", "b", "c", "c", "c", "c"]
R.countBy(letters2) // doesn't work

Instead, we must add some identity expression such as:

R.countBy(x => x)(letters2)
// gives {"a": 4, "b": 2, "c": 4}

or

R.countBy(R.identity)(letters2)

This isn't always the case with other Ramda functions (e.g., R.isNil()). I'm trying to understand where this extra step of identity comes from. To me it seems unnecessary, but I'm probably missing something.

Thanks!

Body:
The reason is that ramda simply does not make any assumption on how you want to count your list...

const  list = ['A', 'b', 'c', 'D', 'e', 'f', 'g', 'G', 'F'];

// simply count
console.log(
  R.countBy(R.identity, list),
)

// or count case insensitively
console.log(
  R.countBy(R.toLower, list),
)

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.js" integrity="sha512-ZZcBsXW4OcbCTfDlXbzGCamH1cANkg6EfZAN2ukOl7s5q8skbB+WndmAqFT8fuMzeuHkceqd5UbIDn7fcqJFgg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Also, do not forget that you can build up your functions by leveraging partial application.

Note the wording, countBy as if Ramda wants to be told how to count. but nothing prevents you from building your own count.

const count = R.countBy(R.identity);

console.log(count(list))


问:
Not able to Push React code in Github master
Not able to Push React code in Github master due to larger size.

```<code>git push -u origin master
Enumerating objects: 41025, done.
Counting objects: 100% (41025/41025), done.
Delta compression using up to 4 threads
Compressing objects: 100% (25146/25146), done.
Writing objects: 100% (41025/41025), 190.44 MiB | 5.20 MiB/s, done.
Total 41025 (delta 14626), reused 41025 (delta 14626), pack-reused 0
remote: Resolving deltas: 100% (14626/14626), done.
remote: warning: File node_modules/.cache/default-development/20.pack is 54.54 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
remote: warning: File node_modules/.cache/default-development/101.pack is 79.78 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
remote: error: Trace: 8dfc24e220167542a79ef96d0c9f68e0381fecd6e731ab98b3ad1c16716d2e46
remote: error: See http://git.io/iEPt8g for more information.
remote: error: File node_modules/.cache/default-development/0.pack is 164.76 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: File node_modules/.cache/default-development/65.pack is 164.10 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.
To https://github.com/u121/DemoPage.git
 ! [remote rejected]   master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://github.com/u121/DemoPage.git'
</code>```

Getting this error when i use git push -u origin master  in app

答:
File node_modules/.cache/default-development/0.pack is 164.76 MB; this exceeds GitHub's file size limit of 100.00 MB.

In general, you don't want to push the node modules folder, but rather only push your package.json / package-lock.json and use npm install to download your dependencies.

Body:
Not able to Push React code in Github master due to larger size.

git push -u origin master
Enumerating objects: 41025, done.
Counting objects: 100% (41025/41025), done.
Delta compression using up to 4 threads
Compressing objects: 100% (25146/25146), done.
Writing objects: 100% (41025/41025), 190.44 MiB | 5.20 MiB/s, done.
Total 41025 (delta 14626), reused 41025 (delta 14626), pack-reused 0
remote: Resolving deltas: 100% (14626/14626), done.
remote: warning: File node_modules/.cache/default-development/20.pack is 54.54 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
remote: warning: File node_modules/.cache/default-development/101.pack is 79.78 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
remote: error: Trace: 8dfc24e220167542a79ef96d0c9f68e0381fecd6e731ab98b3ad1c16716d2e46
remote: error: See http://git.io/iEPt8g for more information.
remote: error: File node_modules/.cache/default-development/0.pack is 164.76 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: File node_modules/.cache/default-development/65.pack is 164.10 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.
To https://github.com/u121/DemoPage.git
 ! [remote rejected]   master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://github.com/u121/DemoPage.git'

Getting this error when i use git push -u origin master  in app


问:
How to write Json response to a CSV file in Jmeter
I want to write my JSON response values in CSV in Jmeter,pls help me with the code to extract and write in CSV.

JSON response looks like below-

{"isSuccess":true,"response":{"appDetailsId":8350,"lifeAssuredId":11816,"proposerId":11816,"bitlyLink":"","pQuoteNo":"PA00000232","validationResponse":{"fieldValidationResponse":{"isFieldLevelValidationSuccess":true,"fieldLevelErrorMessage":[]},"businessValidationResponse":{"isBusinessLevelValidationSuccess":true,"businessLevelErrorMessage":[]}}},"errorMessage":null}

答:
Extract the "values" you want using i.e. JSON Path Extractor or JSON JMesPath Extractor. If you need help in coming up with correct JsonPath or JMesPath expression - update your question with the values you need to extract.

Declare the JMeter Variable names holding the values using sample_variables property

Add Flexible File Writer to your test plan (install it using JMeter Plugins Manager if it's not there yet)

Configure Flexible File Writer to store the values into the file of your choice.


问:
Getting data out of XML by Xquery to text
I have a fairly large set of large XML files, from each of which I want to extract some data. I'm using an evaluation version of Altova XMLSpy, in which I managed to get an XPATH to work. However, I need the data in CSV or text format, so I can use it in R or Excel for further evaluation and I cannot copy the results of the XPATH to a file. I found that using XQUERY I would be able to, but I fail to get the XQUERY to work for at least one file.

The XML is structured like:

```<code><d2LogicalModel xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://datex2.eu/schema/2_0/2_0" modelBaseVersion="2.0" xsi:schemaLocation="http://datex2.eu/schema/2_0/2_0 D:\NDW\CSS\DataGenerator\DATEXIISchema_2_0_2_0.xsd">
<payloadPublication xmlns="http://datex2.eu/schema/2_0/2_0" xsi:type="MeasuredDataPublication" lang="nl">
    <publicationTime>2011-04-21T05:58:34Z</publicationTime>
    <publicationCreator>
        <country>nl</country>
        <nationalIdentifier>NDW-CNS</nationalIdentifier>
    </publicationCreator>
    <measurementSiteTableReference>NDW01_MT_321</measurementSiteTableReference>
    <headerInformation>
        <areaOfInterest>national</areaOfInterest>
        <confidentiality>restrictedToAuthorities</confidentiality>
        <informationStatus>real</informationStatus>
    </headerInformation>
    <siteMeasurements>
        <measurementSiteReference>GRT01_MORO_1002_2</measurementSiteReference>
        <measurementTimeDefault>2011-04-21T05:57:00Z</measurementTimeDefault>
        <measuredValue index="1">
            <basicDataValue xsi:type="TrafficSpeed"/>
        </measuredValue>
        <measuredValue index="2">
            <basicDataValue xsi:type="TrafficSpeed"/>
        </measuredValue>
        <measuredValue index="3">
            <basicDataValue xsi:type="TrafficSpeed"/>
        </measuredValue>
        <measuredValue index="4">
            <basicDataValue xsi:type="TrafficSpeed"/>
        </measuredValue>
        <measuredValue index="5">
            <basicDataValue xsi:type="TrafficSpeed"/>
        </measuredValue>
        <measuredValue index="6">
            <basicDataValue xsi:type="TrafficSpeed"/>
        </measuredValue>
    </siteMeasurements>
    <siteMeasurements>
        <measurementSiteReference>RWS01_MONIBAS_0021hrr2131ra</measurementSiteReference>
        <measurementTimeDefault>2011-04-21T05:57:00Z</measurementTimeDefault>
        <measuredValue index="1">
            <basicDataValue xsi:type="TrafficFlow">
                <time>2011-04-21T05:56:00Z</time>
                <vehicleFlow>900</vehicleFlow>
            </basicDataValue>
        </measuredValue>
        <measuredValue index="2">
            <basicDataValue xsi:type="TrafficSpeed">
                <numberOfInputValuesUsed>60</numberOfInputValuesUsed>
                <standardDeviation>0</standardDeviation>
                <time>2011-04-21T05:56:00Z</time>
                <averageVehicleSpeed>115</averageVehicleSpeed>
            </basicDataValue>
        </measuredValue>
        <measuredValue index="3">
            <basicDataValue xsi:type="TrafficFlow">
                <time>2011-04-21T05:56:00Z</time>
                <vehicleFlow>1020</vehicleFlow>
            </basicDataValue>
        </measuredValue>
        <measuredValue index="4">
            <basicDataValue xsi:type="TrafficSpeed">
                <numberOfInputValuesUsed>60</numberOfInputValuesUsed>
                <standardDeviation>0</standardDeviation>
                <time>2011-04-21T05:56:00Z</time>
                <averageVehicleSpeed>104</averageVehicleSpeed>
            </basicDataValue>
        </measuredValue>
    </siteMeasurements>
</code>```

I want to filter on a specific value for measurementSiteReference and get the results of all measuredValue with a basicDataValue for TrafficFlow, preferably in the format of:

```<code>index, value, timestamp
1, 900, 05:56:00
3, 1020, 05:56:00
</code>```

I have the following XPATH:

```<code>//text()[contains(.,"GEO01_Z_RWSTI1011")]/parent::*/parent::*/descendant::measuredValue[(@index)]/basicDataValue/vehicleFlow
</code>```

This gives me the results for one file, but I cannot find a way to convert that XPATH to an XQUERY. The current XQUERY returns no results:

```<code>let $nl := "
"
for $x in doc("TrafficSpeed 20110421 0800-1559\0800_trafficspeed")/d2LogicalModel/payloadPublication/siteMeasurements
where $x/measurementSiteReference/text()[contains(.,"GEO01_Z_RWSTI1011")]
return concat($x/measurementSiteReference/measuredValue,$nl)
</code>```

How could I get the return I want using XQUERY?

答:
Your elements are bound to a namespace xmlns="http://datex2.eu/schema/2_0/2_0", but you are not namespace qualifying your elements in your XPATH statements.  So, your XPATH statements don't select the elements that you want.

You would want to do something like this to declare a namespace and use it in your XPath statements:

```<code>declare namespace datex = "http://datex2.eu/schema/2_0/2_0";

let $nl := "
"

for $x in doc("TrafficSpeed 20110421 0800-1559\0800_trafficspeed")/datex:d2LogicalModel/datex:payloadPublication/datex:siteMeasurements
where $x/datex:measurementSiteReference/text()[contains(.,"GEO01_Z_RWSTI1011")]
return concat($x/datex:measurementSiteReference/datex:measuredValue,$nl)
</code>```

However, you will then likely run into a problem using concat() on a sequence, and that the current code doesn't produce your desired output.

ContentLicense: CC BY-SA 3.0

Body:
I have a fairly large set of large XML files, from each of which I want to extract some data. I'm using an evaluation version of Altova XMLSpy, in which I managed to get an XPATH to work. However, I need the data in CSV or text format, so I can use it in R or Excel for further evaluation and I cannot copy the results of the XPATH to a file. I found that using XQUERY I would be able to, but I fail to get the XQUERY to work for at least one file.

The XML is structured like:

<d2LogicalModel xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://datex2.eu/schema/2_0/2_0" modelBaseVersion="2.0" xsi:schemaLocation="http://datex2.eu/schema/2_0/2_0 D:\NDW\CSS\DataGenerator\DATEXIISchema_2_0_2_0.xsd">
<payloadPublication xmlns="http://datex2.eu/schema/2_0/2_0" xsi:type="MeasuredDataPublication" lang="nl">
    <publicationTime>2011-04-21T05:58:34Z</publicationTime>
    <publicationCreator>
        <country>nl</country>
        <nationalIdentifier>NDW-CNS</nationalIdentifier>
    </publicationCreator>
    <measurementSiteTableReference>NDW01_MT_321</measurementSiteTableReference>
    <headerInformation>
        <areaOfInterest>national</areaOfInterest>
        <confidentiality>restrictedToAuthorities</confidentiality>
        <informationStatus>real</informationStatus>
    </headerInformation>
    <siteMeasurements>
        <measurementSiteReference>GRT01_MORO_1002_2</measurementSiteReference>
        <measurementTimeDefault>2011-04-21T05:57:00Z</measurementTimeDefault>
        <measuredValue index="1">
            <basicDataValue xsi:type="TrafficSpeed"/>
        </measuredValue>
        <measuredValue index="2">
            <basicDataValue xsi:type="TrafficSpeed"/>
        </measuredValue>
        <measuredValue index="3">
            <basicDataValue xsi:type="TrafficSpeed"/>
        </measuredValue>
        <measuredValue index="4">
            <basicDataValue xsi:type="TrafficSpeed"/>
        </measuredValue>
        <measuredValue index="5">
            <basicDataValue xsi:type="TrafficSpeed"/>
        </measuredValue>
        <measuredValue index="6">
            <basicDataValue xsi:type="TrafficSpeed"/>
        </measuredValue>
    </siteMeasurements>
    <siteMeasurements>
        <measurementSiteReference>RWS01_MONIBAS_0021hrr2131ra</measurementSiteReference>
        <measurementTimeDefault>2011-04-21T05:57:00Z</measurementTimeDefault>
        <measuredValue index="1">
            <basicDataValue xsi:type="TrafficFlow">
                <time>2011-04-21T05:56:00Z</time>
                <vehicleFlow>900</vehicleFlow>
            </basicDataValue>
        </measuredValue>
        <measuredValue index="2">
            <basicDataValue xsi:type="TrafficSpeed">
                <numberOfInputValuesUsed>60</numberOfInputValuesUsed>
                <standardDeviation>0</standardDeviation>
                <time>2011-04-21T05:56:00Z</time>
                <averageVehicleSpeed>115</averageVehicleSpeed>
            </basicDataValue>
        </measuredValue>
        <measuredValue index="3">
            <basicDataValue xsi:type="TrafficFlow">
                <time>2011-04-21T05:56:00Z</time>
                <vehicleFlow>1020</vehicleFlow>
            </basicDataValue>
        </measuredValue>
        <measuredValue index="4">
            <basicDataValue xsi:type="TrafficSpeed">
                <numberOfInputValuesUsed>60</numberOfInputValuesUsed>
                <standardDeviation>0</standardDeviation>
                <time>2011-04-21T05:56:00Z</time>
                <averageVehicleSpeed>104</averageVehicleSpeed>
            </basicDataValue>
        </measuredValue>
    </siteMeasurements>

I want to filter on a specific value for measurementSiteReference and get the results of all measuredValue with a basicDataValue for TrafficFlow, preferably in the format of:

index, value, timestamp
1, 900, 05:56:00
3, 1020, 05:56:00

I have the following XPATH:

//text()[contains(.,"GEO01_Z_RWSTI1011")]/parent::*/parent::*/descendant::measuredValue[(@index)]/basicDataValue/vehicleFlow

This gives me the results for one file, but I cannot find a way to convert that XPATH to an XQUERY. The current XQUERY returns no results:

let $nl := "
"
for $x in doc("TrafficSpeed 20110421 0800-1559\0800_trafficspeed")/d2LogicalModel/payloadPublication/siteMeasurements
where $x/measurementSiteReference/text()[contains(.,"GEO01_Z_RWSTI1011")]
return concat($x/measurementSiteReference/measuredValue,$nl)

How could I get the return I want using XQUERY?

Body:
Your elements are bound to a namespace xmlns="http://datex2.eu/schema/2_0/2_0", but you are not namespace qualifying your elements in your XPATH statements.  So, your XPATH statements don't select the elements that you want.

You would want to do something like this to declare a namespace and use it in your XPath statements:

declare namespace datex = "http://datex2.eu/schema/2_0/2_0";

let $nl := "&#10;"

for $x in doc("TrafficSpeed 20110421 0800-1559\0800_trafficspeed")/datex:d2LogicalModel/datex:payloadPublication/datex:siteMeasurements
where $x/datex:measurementSiteReference/text()[contains(.,"GEO01_Z_RWSTI1011")]
return concat($x/datex:measurementSiteReference/datex:measuredValue,$nl)

However, you will then likely run into a problem using concat() on a sequence, and that the current code doesn't produce your desired output.


问:
Print words in string in reverse order C
I take user input using fgets() and store it into a temp array. I then concatenate that to a main array called userInput so that the user can enter multiple lines.

Let's say the user enters the following:

```<code>This is a sentence
This is a new line
</code>```

I need it to print each line in the order they were entered but reverse the order of words like below:

```<code>sentence a is This
line new a is This
</code>```

I have the current approach but I get this:

```<code>line
new a is sentence
This a is This
</code>```

Below is my code where I call reversePrint() with a string to reverse:

```<code>void printToSpace(const char *str) {
  do {
    putc(*str, stdout);
  } while(*str++ != ' ');
}

void reversePrint(const char *str) {
  const char *p = strchr(str, ' ');
  if (p == NULL) {
    printf("%s", str);
  }
  else {
    reversePrint(p + 1);
    printToSpace(str);
  }
}
</code>```

答:
```<code>#include <stdio.h>
#include <string.h>
#define MAX_LEN 100000

int main()
{
    char str[MAX_LEN], temp[MAX_LEN];
    printf("Enter the Sentence to print reverse : ");
    scanf("%[^\n]%*c", &str);
    int i, left, right, length = strlen(str);
    left = 0;
    right = length - 1;

    printf("%d \n", length);

    for(i=0;i<length;i++)
    {
        temp[i] = str[right];
        right--;
    }

     printf("%s",temp);

     return 0;
}
</code>```

Body:
I take user input using fgets() and store it into a temp array. I then concatenate that to a main array called userInput so that the user can enter multiple lines.

Let's say the user enters the following:

This is a sentence
This is a new line

I need it to print each line in the order they were entered but reverse the order of words like below:

sentence a is This
line new a is This

I have the current approach but I get this:

line
new a is sentence
This a is This

Below is my code where I call reversePrint() with a string to reverse:

void printToSpace(const char *str) {
  do {
    putc(*str, stdout);
  } while(*str++ != ' ');
}

void reversePrint(const char *str) {
  const char *p = strchr(str, ' ');
  if (p == NULL) {
    printf("%s", str);
  }
  else {
    reversePrint(p + 1);
    printToSpace(str);
  }
}


问:
How can W3C CSS Validator identify a css3 document?
I'm having a issue!

Is there a way to identify a css3 file for the W3C validator?

In the HTML5 we put <!DOCTYPE html> but in a CSS file what can we put?

When I validate my css file and it contains some css3 elements (@font-face, box-shadow, etc), it says that it's not valid! 'cause it doesn't know it's css3. So... is there a method?

Thanks so much. Davide.

答:
Use the folling link with your URL in place of the question (???) marks:

http://jigsaw.w3.org/css-validator/validator?profile=css3&usermedium=all&warning=1&vextwarning=&lang=en&uri=http%3A%2F%2F???


问:
How do I interact with Uniswap V2 in a Truffle test suite?
I am looking for a way to create an automated test suite with Truffle that can test my smart contract's interactions with Uniswap V2. The Uniswap docs briefly mention testing with Truffle but do not provide any examples. I am looking to test it using a mainnet fork with ganache.

I'm guessing it's a similar process to the accepted answer for this question, but I'm specifically looking for a way to do it using Truffle and web3.js.

As an example, if I were testing the following contract:

```<code>pragma solidity ^0.6.6;

interface IUniswap {
  function swapExactETHForTokens(
    uint amountOutMin,
    address[] calldata path,
    address to,
    uint deadline)
  external
  payable
  returns (uint[] memory amounts);
  function WETH() external pure returns (address);
}

contract MyContract {
  IUniswap uniswap;

  constructor(address _uniswap) public {
    uniswap = IUniswap(_uniswap);
  }

  function swapExactETHForTokens(uint amountOutMin, address token) external payable {
    address[] memory path = new address[](2);
    path[0] = uniswap.WETH();
    path[1] = token;
    uniswap.swapExactETHForTokens{value: msg.value}(
      amountOutMin,
      path,
      msg.sender,
      now
    );
  }
}
</code>```

How would I create a unit test to verify that swapExactETHForTokens() swaps ETH for say, DAI? For the value of _uniswap I've been using UniswapV2Router02.

Any help would be greatly appreciated.

答:
If you use Uniswap platform to swap a token, you are going to have 2 steps. You are going to approve the token, in this step metamask will pop-up and you are going to confirm it. Then Uniswap will do the actual swap, it takes the tokens out of your wallet and does the exchange for you.

This is the swapExactETHForTokens function

```<code>function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        virtual
        override
        payable
        ensure(deadline)
        returns (uint[] memory amounts)
    {
        require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
        amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
        require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
        IWETH(WETH).deposit{value: amounts[0]}();
        assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
        _swap(amounts, path, to);
    }
</code>```

last function _swap calls the swap function:

From documentation

It is also important to ensure that your contract controls enough
ETH/tokens to make the swap, and has granted approval to the router to
withdraw this many tokens.

Imagine you want to swap 50 DAI for as much ETH as possible from your
smart contract.

transferFrom

Before swapping, our smart contracts needs to be in control of 50 DAI.
The easiest way to accomplish this is by calling transferFrom on DAI
with the owner set to msg.sender:

```<code>uint amountIn = 50 * 10 ** DAI.decimals();
require(DAI.transferFrom(msg.sender, address(this), amountIn), 'transferFrom failed.');
</code>```

Eventually Uniswap will transferFrom, but before your token has to approve the transaction, it has to add uniswap address to its allowance mapping.

```<code>mapping(address=>mapping(address=>uint)) public allowance;
// token address is allowign uniswap address for this much token
</code>```

You cannot test the current implementation of your contract unless you have a swap token set and your swap token has to call approve.

If you had front end app, when you call your contract's swap function, metamask would pop up and you would confirm it. However in a test environment you need the actual ERC20 contract, you deploy it and you call the approve. In front end you would have two functions swapToken and approve. You would call them in this order?

```<code>const startSwap = async () => {
    await approve()
    await swapToken()
}
</code>```

In test suite:

```<code>const MyContract = artifacts.require("MyContract");
const Dai = artifacts.require("Dai");

// ganache provides an array of accounts
contract("Uniswap", (ganachProvidedAccounts) => {
  let myContract,dai;
  // intialize the contracts before each test
  before(async () => {
    myContract = await myContract.new();
    dai = await Dai.new();
  })

  describe("Swapping", async () => {
    it("swap tokens", async () => {
      let result;

      // first ask for approval of 100 token transfer
      await dai.approve(myContract.address, tokens("100"), {
        from:ganachProvidedAccounts[0] ,
      });
      // // check staking for customer
      await myContract.swapExactETHForTokens("100"), { from: ganachProvidedAccounts[0] });
      // make your assetion
})})
</code>```

Body:
I am looking for a way to create an automated test suite with Truffle that can test my smart contract's interactions with Uniswap V2. The Uniswap docs briefly mention testing with Truffle but do not provide any examples. I am looking to test it using a mainnet fork with ganache.

I'm guessing it's a similar process to the accepted answer for this question, but I'm specifically looking for a way to do it using Truffle and web3.js.

As an example, if I were testing the following contract:

pragma solidity ^0.6.6;

interface IUniswap {
  function swapExactETHForTokens(
    uint amountOutMin,
    address[] calldata path,
    address to,
    uint deadline)
  external
  payable
  returns (uint[] memory amounts);
  function WETH() external pure returns (address);
}

contract MyContract {
  IUniswap uniswap;

  constructor(address _uniswap) public {
    uniswap = IUniswap(_uniswap);
  }

  function swapExactETHForTokens(uint amountOutMin, address token) external payable {
    address[] memory path = new address[](2);
    path[0] = uniswap.WETH();
    path[1] = token;
    uniswap.swapExactETHForTokens{value: msg.value}(
      amountOutMin,
      path,
      msg.sender,
      now
    );
  }
}

How would I create a unit test to verify that swapExactETHForTokens() swaps ETH for say, DAI? For the value of _uniswap I've been using UniswapV2Router02.

Any help would be greatly appreciated.

Body:
If you use Uniswap platform to swap a token, you are going to have 2 steps. You are going to approve the token, in this step metamask will pop-up and you are going to confirm it. Then Uniswap will do the actual swap, it takes the tokens out of your wallet and does the exchange for you.

This is the swapExactETHForTokens function

function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        virtual
        override
        payable
        ensure(deadline)
        returns (uint[] memory amounts)
    {
        require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
        amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
        require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
        IWETH(WETH).deposit{value: amounts[0]}();
        assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
        _swap(amounts, path, to);
    }

last function _swap calls the swap function:

From documentation

It is also important to ensure that your contract controls enough
ETH/tokens to make the swap, and has granted approval to the router to
withdraw this many tokens.

Imagine you want to swap 50 DAI for as much ETH as possible from your
smart contract.

transferFrom

Before swapping, our smart contracts needs to be in control of 50 DAI.
The easiest way to accomplish this is by calling transferFrom on DAI
with the owner set to msg.sender:

uint amountIn = 50 * 10 ** DAI.decimals();
require(DAI.transferFrom(msg.sender, address(this), amountIn), 'transferFrom failed.');

Eventually Uniswap will transferFrom, but before your token has to approve the transaction, it has to add uniswap address to its allowance mapping.

mapping(address=>mapping(address=>uint)) public allowance;
// token address is allowign uniswap address for this much token

You cannot test the current implementation of your contract unless you have a swap token set and your swap token has to call approve.

If you had front end app, when you call your contract's swap function, metamask would pop up and you would confirm it. However in a test environment you need the actual ERC20 contract, you deploy it and you call the approve. In front end you would have two functions swapToken and approve. You would call them in this order?

const startSwap = async () => {
    await approve()
    await swapToken()
}

In test suite:

const MyContract = artifacts.require("MyContract");
const Dai = artifacts.require("Dai");

// ganache provides an array of accounts
contract("Uniswap", (ganachProvidedAccounts) => {
  let myContract,dai;
  // intialize the contracts before each test
  before(async () => {
    myContract = await myContract.new();
    dai = await Dai.new();
  })

  describe("Swapping", async () => {
    it("swap tokens", async () => {
      let result;

      // first ask for approval of 100 token transfer
      await dai.approve(myContract.address, tokens("100"), {
        from:ganachProvidedAccounts[0] ,
      });
      // // check staking for customer
      await myContract.swapExactETHForTokens("100"), { from: ganachProvidedAccounts[0] });
      // make your assetion
})})


问:
multiple npm commnd aliases for same npm script
Is there a way to create many aliases / command names for same same npm scripts in package.json.

ex: i want following, i.e either user runs
npm run cmd1 or npm run cmd2 same thing happens.

package.json:

```<code>{
  "name": "....",
  "version": "1.0.0",
  "description": ".....",
  "scripts": {
    "cmd1 [or] cmd2": "some big script here",
    // "cmd2": "same big script here", // don't want this redundant line

    // something like
    "install [or] i": "initialization script here",
    "start [or] begin": "starter script here",

  }
}
</code>```

答:
I think, it's not possible. However, you could stick to the following attempt, which skips the redundant statement of your script:</p>
```<code>"scripts": {
  "cmd1": "npm run cmd3",
  "cmd2": "npm run cmd3",
  "cmd3": "big script here",
  ...
}
</code>```

Body:
Is there a way to create many aliases / command names for same same npm scripts in package.json.

ex: i want following, i.e either user runs
npm run cmd1 or npm run cmd2 same thing happens.

package.json:

{
  "name": "....",
  "version": "1.0.0",
  "description": ".....",
  "scripts": {
    "cmd1 [or] cmd2": "some big script here",
    // "cmd2": "same big script here", // don't want this redundant line

    // something like
    "install [or] i": "initialization script here",
    "start [or] begin": "starter script here",

  }
}

Body:
I think, it's not possible. However, you could stick to the following attempt, which skips the redundant statement of your script:

"scripts": {
  "cmd1": "npm run cmd3",
  "cmd2": "npm run cmd3",
  "cmd3": "big script here",
  ...
}


问:
React native determine when text is cut off
I am using react-native with a limited number of lines, that are shown as ... using

```<code><Text numberOfLines={4}> {myText} </Text>
</code>```

Now my issue is, if the text is cut off I would like to show it some special image, to navigate to a new view. I am wondering whether there is a property i can use to test if the text is being cut off?

答:
There's now a new event called onTextLayout which can give you the number of lines in your text. Once you fetch this number, you could check if it's greater than the max number of lines you want to have, and if that's the case you can set some state that adds a numberOfLines prop and can be also used to determine if the text was truncated.

Here's an example of how you could get the number of lines:

```<code> <Text
  onTextLayout={(e) => console.log("Number of lines: " + e.nativeEvent.lines.length) }
>
  {someText}
</Text>
</code>```

Body:
I am using react-native with a limited number of lines, that are shown as ... using

<Text numberOfLines={4}> {myText} </Text>

Now my issue is, if the text is cut off I would like to show it some special image, to navigate to a new view. I am wondering whether there is a property i can use to test if the text is being cut off?

Body:
There's now a new event called onTextLayout which can give you the number of lines in your text. Once you fetch this number, you could check if it's greater than the max number of lines you want to have, and if that's the case you can set some state that adds a numberOfLines prop and can be also used to determine if the text was truncated.

Here's an example of how you could get the number of lines:

 <Text
  onTextLayout={(e) => console.log("Number of lines: " + e.nativeEvent.lines.length) }
>
  {someText}
</Text>


问:
How to make statements in python script behave just like them executed in interactive shell
I have an instrument that is connected to a serial comm port.  I use Python 3.2 in Windows XP, plus pySerial module.  I have a problem when I execute a script consisting of a series of statements that open the comm port, configure it, write strings to and receive strings from it.  Thoese strings aer either commands pertinent to the instrument (control) or responses from the instrument (response).

When those statements are executed in a python interpreter interactively (at >>>), I get what I expect and the results are good and correct.  However, when I execute the script, either within the interpreter or from a shell, I don’t get what I want.  The statements in the script is the same as what I use in the interactive interpreter.

Why do I get the strange behavior and how can I change the script to make it to behave like in interactive interpreter?

```<code>def read(comport):

    wrt_str=b'movt 3000'+b'\r\n'
    ret_str=comport.write(wrt_str)

    wrt_str=b'scan'+b'\r\n'
    ret_str=comport.write(wrt_str)

    rsp_str=comport.readlines() #########1

    wrt_str=b'hllo'+b'\r\n'
    ret_str=comport.write(wrt_str)

    rsp_str=comport.readlines()#########2
</code>```

The problem is with the lines above with #######.  In interactive mode, there is about 1 second delay at #1, and 9 seonds delay at #2.  I get correct responses there.  However, if I execute the script above, there is no delay at all and I get incorrect results (garbage).  I set the read timeout to 0 in comm port set up, as

```<code>comport.timeout=0
</code>```

So the comport should be in blocking mode if it waits for the end of line or end of file.

Update (Aug 19, 2011)

I have an update to the original post I made a few days ago.  I think I know what the problem is and want to know if anyone has a solution:

After putting "print" and "time.sleep(delay)" after every statement, I found when the script is running, it appears going around the pyserial statement, such as "comport.write(..)" or "comport.readlines(...)" while the pyserial command is executing (appearing as waiting and busying doing some thing, you know serial port is slow).  So for example, when I exec all statements in a python interactive shell, I am not able to type and run a new statement if the previous one is not returned.  Let's ay, if comport.readlines() is not returning, I can't type and run the next comport.write(...) statemtn.  However, in a script that is running, if the comport.readlines() is busy reading, the next statement is running, if the next statement happens to be a comport.write() which will abort the reading.

Is there any way to force the python script to behave like running exactly sequentially?

答:
I read the document of pyserial:

```<code>timeout = None: wait forever
timeout = 0: non-blocking mode (return immediately on read)
timeout = x: set timeout to x seconds (float allowed)
</code>```

if you set comport.timeout=0 then readlines() will return immediately. Try set comport.timeout = 10.

Body:
I have an instrument that is connected to a serial comm port.  I use Python 3.2 in Windows XP, plus pySerial module.  I have a problem when I execute a script consisting of a series of statements that open the comm port, configure it, write strings to and receive strings from it.  Thoese strings aer either commands pertinent to the instrument (control) or responses from the instrument (response).

When those statements are executed in a python interpreter interactively (at >>>), I get what I expect and the results are good and correct.  However, when I execute the script, either within the interpreter or from a shell, I don’t get what I want.  The statements in the script is the same as what I use in the interactive interpreter.

Why do I get the strange behavior and how can I change the script to make it to behave like in interactive interpreter?

def read(comport):

    wrt_str=b'movt 3000'+b'\r\n'
    ret_str=comport.write(wrt_str)

    wrt_str=b'scan'+b'\r\n'
    ret_str=comport.write(wrt_str)

    rsp_str=comport.readlines() #########1

    wrt_str=b'hllo'+b'\r\n'
    ret_str=comport.write(wrt_str)

    rsp_str=comport.readlines()#########2

The problem is with the lines above with #######.  In interactive mode, there is about 1 second delay at #1, and 9 seonds delay at #2.  I get correct responses there.  However, if I execute the script above, there is no delay at all and I get incorrect results (garbage).  I set the read timeout to 0 in comm port set up, as

comport.timeout=0

So the comport should be in blocking mode if it waits for the end of line or end of file.

Update (Aug 19, 2011)

I have an update to the original post I made a few days ago.  I think I know what the problem is and want to know if anyone has a solution:

After putting "print" and "time.sleep(delay)" after every statement, I found when the script is running, it appears going around the pyserial statement, such as "comport.write(..)" or "comport.readlines(...)" while the pyserial command is executing (appearing as waiting and busying doing some thing, you know serial port is slow).  So for example, when I exec all statements in a python interactive shell, I am not able to type and run a new statement if the previous one is not returned.  Let's ay, if comport.readlines() is not returning, I can't type and run the next comport.write(...) statemtn.  However, in a script that is running, if the comport.readlines() is busy reading, the next statement is running, if the next statement happens to be a comport.write() which will abort the reading.

Is there any way to force the python script to behave like running exactly sequentially?

Body:
I read the document of pyserial:

timeout = None: wait forever
timeout = 0: non-blocking mode (return immediately on read)
timeout = x: set timeout to x seconds (float allowed)

if you set comport.timeout=0 then readlines() will return immediately. Try set comport.timeout = 10.


问:
What happens if you check for < condition in ternary or conditional operator(x < y ? num1 : num2) in c, but the input value is equal
So I was just trying to write a C code for comparing numbers, which one of the three number is largest and which one is the smallest.

Then I found that I can use the ternary operator (ex: x < y ? num1 : num2), so I thought yeah okay this will work and then I wrote this code:

```<code>#include <stdio.h>
int main(){
int num1, num2, num3, largest, smallest;

printf("Enter three integers: ");
scanf("%d %d %d", &num1, &num2, &num3);

//largest among three integers.

largest = num1 > num2 ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 : num3);
printf("\nThe largest among the three is: %d", largest);

//smallest among three integers

smallest = num1 < num2 ? (num1 < num3 ? num1 : num3) : (num2 < num3 ? num2 : num3);
printf("\nThe smallest among the three is: %d", smallest);

return 0;
}
</code>```

So, if I give input like num1 = 10, num2 = 20 and num3 = 30, then the output is

```<code>Enter three integers: 10 20 30

The largest among the three is: 30
The smallest among the three is: 10
</code>```

But what happens when all these numbers are equal? Will the condition of the Ternary operator be true or false?

```<code>Enter three integers: 20 20 20

The largest among the three is: 20
The smallest among the three is: 20
</code>```

I don't know what the condition but the program works fine nothing wrong the output is correct.

I am using this on windows 10 latest and gcc.exe (MinGW.org GCC-6.3.0-1) 6.3.0

I am sorry if this is a lame question but I didn't found anything about this.

答:
If the first expression of the conditional operator evaluates to false then the result of the conditional operator is the value of the third expression.

For example in this statement

```<code>largest = num1 > num2 ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 : num3);
</code>```

if num1 is not greater than num2 (that is the expression with the relational operator num1 > num2 evaluates to false) then this (third) expression evaluates

```<code>(num2 > num3 ? num2 : num3)
</code>```

Again if num2 is not greater than num3 then the result of this expression and of the whole enclosing expression is the value of num3,

Body:
So I was just trying to write a C code for comparing numbers, which one of the three number is largest and which one is the smallest.

Then I found that I can use the ternary operator (ex: x < y ? num1 : num2), so I thought yeah okay this will work and then I wrote this code:

#include <stdio.h>
int main(){
int num1, num2, num3, largest, smallest;

printf("Enter three integers: ");
scanf("%d %d %d", &num1, &num2, &num3);

//largest among three integers.

largest = num1 > num2 ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 : num3);
printf("\nThe largest among the three is: %d", largest);

//smallest among three integers

smallest = num1 < num2 ? (num1 < num3 ? num1 : num3) : (num2 < num3 ? num2 : num3);
printf("\nThe smallest among the three is: %d", smallest);

return 0;
}

So, if I give input like num1 = 10, num2 = 20 and num3 = 30, then the output is

Enter three integers: 10 20 30

The largest among the three is: 30
The smallest among the three is: 10

But what happens when all these numbers are equal? Will the condition of the Ternary operator be true or false?

Enter three integers: 20 20 20

The largest among the three is: 20
The smallest among the three is: 20

I don't know what the condition but the program works fine nothing wrong the output is correct.

I am using this on windows 10 latest and gcc.exe (MinGW.org GCC-6.3.0-1) 6.3.0

I am sorry if this is a lame question but I didn't found anything about this.

Body:
If the first expression of the conditional operator evaluates to false then the result of the conditional operator is the value of the third expression.

For example in this statement

largest = num1 > num2 ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 : num3);

if num1 is not greater than num2 (that is the expression with the relational operator num1 > num2 evaluates to false) then this (third) expression evaluates

(num2 > num3 ? num2 : num3)

Again if num2 is not greater than num3 then the result of this expression and of the whole enclosing expression is the value of num3,


问:
Spring circular references prohibited in 2.6 version
I have an issue for circular reference calling.
Even if I set true to this option, I cannot fix my issue.
How can I fix it?
Here are my code snippets which are shown below step by step.

Here is my application.properties file shown below.

```<code>...
spring.main.allow-circular-references= true
...
</code>```

Here is my error message shown below.

```<code>Description:

The dependencies of some of the beans in the application context form a cycle:

   userController (field com.photoapp.users.service.UserService com.photoapp.users.controller.UserController.userService)
┌─────┐
|  userServiceImpl defined in file [C:\Users\de\Desktop\sts-4.9.0.RELEASE\workspace\PhotoAppApiUsers\target\classes\com\photoapp\users\service\impl\UserServiceImpl.class]
↑     ↓
|  webSecurity defined in file [C:\Users\de\Desktop\sts-4.9.0.RELEASE\workspace\PhotoAppApiUsers\target\classes\com\photoapp\users\security\WebSecurity.class]
└─────┘

Action:

Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.
</code>```

Here is my userServiceImpl class

```<code>@Service
@Transactional
public class UserServiceImpl implements UserService{

    UserMapper userMapper;

    UserRepository userRepository;

    PasswordEncoder passwordEncoder;

    @Autowired
    public UserServiceImpl(UserMapper userMapper,UserRepository userRepository,PasswordEncoder passwordEncoder) {
        super();
        this.userMapper = userMapper;
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public UserDto createUser(UserDto userDetails) {
        // TODO Auto-generated method stub

        userDetails.setUserId(UUID.randomUUID().toString());

        User user = userMapper.userDtotoUser(userDetails);

        String encodedPassword = passwordEncoder.encode(userDetails.getPassword());
        user.setEncryptedPassword(encodedPassword);

        userRepository.save(user);

        UserDto returnValue = userMapper.userToUserDto(user);

        return returnValue;

    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO Auto-generated method stub
        User user = userRepository.findByEmail(username);

        if(user == null)
            throw new UsernameNotFoundException(username);

        return new org.springframework.security.core.userdetails.User(user.getEmail(),
                user.getEncryptedPassword(),
                true, true, true, true, new ArrayList<>());
    }

    @Override
    public UserDto getUserDetailsByEmail(String email) {
        User user = userRepository.findByEmail(email);

        if(user == null)
            throw new UsernameNotFoundException(email);

        UserDto returnValue = userMapper.userToUserDto(user);

        return returnValue;
    }

    @Override
    public UserDto getUserByUserId(String userId) {
        // TODO Auto-generated method stub
        return null;
    }

}
</code>```

Here is my WebSecurity class

```<code>@Configuration
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {

    private Environment environment;
    private UserService userService;

    @Autowired
    public WebSecurity(Environment environment, UserService userService) {
        super();
        this.environment = environment;
        this.userService = userService;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // TODO Auto-generated method stub
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/users").hasIpAddress(environment.getProperty("gateway.ip"))
        .and()
        .addFilter(getAuthenticationFilter());
        http.headers().frameOptions().disable();
    }

    private AuthenticationFilter getAuthenticationFilter() throws Exception{
        AuthenticationFilter authenticationFilter = new AuthenticationFilter(userService, environment, authenticationManager());
        //authenticationFilter.setAuthenticationManager(authenticationManager());
        authenticationFilter.setFilterProcessesUrl(environment.getProperty("login.url.path"));
        return authenticationFilter;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }
}
</code>```

答:
Try using @Lazy

```<code>public class WebSecurity extends WebSecurityConfigurerAdapter {

    private Environment environment;
    @Lazy
    private UserService userService;
</code>```

Reference: https://www.baeldung.com/spring-lazy-annotation

Body:
I have an issue for circular reference calling.
Even if I set true to this option, I cannot fix my issue.
How can I fix it?
Here are my code snippets which are shown below step by step.

Here is my application.properties file shown below.

...
spring.main.allow-circular-references= true
...

Here is my error message shown below.

Description:

The dependencies of some of the beans in the application context form a cycle:

   userController (field com.photoapp.users.service.UserService com.photoapp.users.controller.UserController.userService)
┌─────┐
|  userServiceImpl defined in file [C:\Users\de\Desktop\sts-4.9.0.RELEASE\workspace\PhotoAppApiUsers\target\classes\com\photoapp\users\service\impl\UserServiceImpl.class]
↑     ↓
|  webSecurity defined in file [C:\Users\de\Desktop\sts-4.9.0.RELEASE\workspace\PhotoAppApiUsers\target\classes\com\photoapp\users\security\WebSecurity.class]
└─────┘

Action:

Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.

Here is my userServiceImpl class

@Service
@Transactional
public class UserServiceImpl implements UserService{

    UserMapper userMapper;

    UserRepository userRepository;

    PasswordEncoder passwordEncoder;

    @Autowired
    public UserServiceImpl(UserMapper userMapper,UserRepository userRepository,PasswordEncoder passwordEncoder) {
        super();
        this.userMapper = userMapper;
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public UserDto createUser(UserDto userDetails) {
        // TODO Auto-generated method stub

        userDetails.setUserId(UUID.randomUUID().toString());

        User user = userMapper.userDtotoUser(userDetails);

        String encodedPassword = passwordEncoder.encode(userDetails.getPassword());
        user.setEncryptedPassword(encodedPassword);

        userRepository.save(user);

        UserDto returnValue = userMapper.userToUserDto(user);

        return returnValue;

    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO Auto-generated method stub
        User user = userRepository.findByEmail(username);

        if(user == null)
            throw new UsernameNotFoundException(username);

        return new org.springframework.security.core.userdetails.User(user.getEmail(),
                user.getEncryptedPassword(),
                true, true, true, true, new ArrayList<>());
    }

    @Override
    public UserDto getUserDetailsByEmail(String email) {
        User user = userRepository.findByEmail(email);

        if(user == null)
            throw new UsernameNotFoundException(email);

        UserDto returnValue = userMapper.userToUserDto(user);

        return returnValue;
    }

    @Override
    public UserDto getUserByUserId(String userId) {
        // TODO Auto-generated method stub
        return null;
    }

}

Here is my WebSecurity class

@Configuration
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {

    private Environment environment;
    private UserService userService;

    @Autowired
    public WebSecurity(Environment environment, UserService userService) {
        super();
        this.environment = environment;
        this.userService = userService;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // TODO Auto-generated method stub
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/users").hasIpAddress(environment.getProperty("gateway.ip"))
        .and()
        .addFilter(getAuthenticationFilter());
        http.headers().frameOptions().disable();
    }

    private AuthenticationFilter getAuthenticationFilter() throws Exception{
        AuthenticationFilter authenticationFilter = new AuthenticationFilter(userService, environment, authenticationManager());
        //authenticationFilter.setAuthenticationManager(authenticationManager());
        authenticationFilter.setFilterProcessesUrl(environment.getProperty("login.url.path"));
        return authenticationFilter;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }
}

Body:
Try using @Lazy

public class WebSecurity extends WebSecurityConfigurerAdapter {

    private Environment environment;
    @Lazy
    private UserService userService;

Reference: https://www.baeldung.com/spring-lazy-annotation


问:
The listener for function 'Function1' was unable to start when running a timer function
I am getting this below error when I am running my timer function app in Azure Cloud. It is just a basic code and I wanted the log to be shown in Insight.

```<code>public static class Function1
{
    [FunctionName("Function1")]
    public static void Run([TimerTrigger("0 * * * * *")]TimerInfo myTimer, ILogger log)
    {
        log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
    }
}
</code>```

答:
It was a firewall issue.
Added the appropriate Virtual Network and Subnet  under Storage Account > Networking > Firewalls and Virtual Network</p>

Body:
I am getting this below error when I am running my timer function app in Azure Cloud. It is just a basic code and I wanted the log to be shown in Insight.

public static class Function1
{
    [FunctionName("Function1")]
    public static void Run([TimerTrigger("0 * * * * *")]TimerInfo myTimer, ILogger log)
    {
        log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
    }
}


问:
How to get all titles with child from one table
i have a table like this:

id
title
parent_id

1
title1
null

2
title2
1

3
title3
1

4
title4
2

5
title5
2

6
title6
3

i want to display all rows which have id in column parent_id so that the result is:

id
title

1
title1

2
title2

3
title3

答:
You can just check for NULL, there is no need to join

SELECT
  t.id,
  t.title
FROM YourTable t
WHERE t.parent_id IS NOT NULL;
```


问:
Get a flash object to be next to an input field
I am having trouble with getting two elements lined up properly.

Here is my HTML:

```<code><input class='pretty-border' id='shareinput' value='afdsdasfdasfadsff' />
<span>
    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
            width="14"
            height="14"
            id="clippy" >
        <param name="movie" value="/clippy.swf"/>
        <param name="allowScriptAccess" value="always" />
        <param name="quality" value="high" />
        <param name="scale" value="noscale" />
        <param NAME="FlashVars" value="id=clip_text">
        <param name="bgcolor" value="#FFFFFF">
        <embed src="/clippy.swf"
               width="14"
               height="14"
               name="clippy"
               quality="high"
               allowScriptAccess="always"
               type="application/x-shockwave-flash"
               pluginspage="http://www.macromedia.com/go/getflashplayer"
               FlashVars="id=clip_text"
               bgcolor="#FFFFFF"
        />
    </object>
</span>
</code>```

And this is my CSS:

```<code>input.pretty-border {
  float:left;
  font-size:1em;
  width: 300px;
  padding: 5px 10px;
  -moz-border-radius: 6px;
  -webkit-border-radius: 6px;
  border-radius: 6px;
  border: 4px solid #c9deff;
}
</code>```

Unfortunately, there is a line break between the objects as can be seen in the attached picture. How can I get rid of it?

答:
setting display:inline on the object seems to work (tested in Chrome & FF)

```<code>span object {display:inline;}
</code>```

Body:
I am having trouble with getting two elements lined up properly.

Here is my HTML:

<input class='pretty-border' id='shareinput' value='afdsdasfdasfadsff' />

    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
            width="14"
            height="14"
            id="clippy" >
        <param name="movie" value="/clippy.swf"/>
        <param name="allowScriptAccess" value="always" />
        <param name="quality" value="high" />
        <param name="scale" value="noscale" />
        <param NAME="FlashVars" value="id=clip_text">
        <param name="bgcolor" value="#FFFFFF">
        <embed src="/clippy.swf"
               width="14"
               height="14"
               name="clippy"
               quality="high"
               allowScriptAccess="always"
               type="application/x-shockwave-flash"
               pluginspage="http://www.macromedia.com/go/getflashplayer"
               FlashVars="id=clip_text"
               bgcolor="#FFFFFF"
        />
    </object>

And this is my CSS:

input.pretty-border {
  float:left;
  font-size:1em;
  width: 300px;
  padding: 5px 10px;
  -moz-border-radius: 6px;
  -webkit-border-radius: 6px;
  border-radius: 6px;
  border: 4px solid #c9deff;
}

Unfortunately, there is a line break between the objects as can be seen in the attached picture. How can I get rid of it?

Body:
setting display:inline on the object seems to work (tested in Chrome & FF)

span object {display:inline;}


答:
The error message is pretty clear. UserServiceImpl depends on WebSecurity which depends on UserServiceImpl.

The dependency from WebSecurity to UserServiceImpl is necessary. That means you need to break the dependency from UserServiceImpl to WebSecurity. This is caused by the password encoder. You need to move that out of WebSecurity. Maybe you can integrate it in UserServiceImpl?

Title: Spring circular references prohibited in 2.6 version


问:
A `return` is needed after `context.res` to stop execution
During Azure Function (AF) debugging, I noticed the both statements context.res={...} and context.res.send() won't end the execution and send back response. To test I create a brand new AF, take the auto-generated files and test using Postman. It goes well.

I then add a new line at the begining:

```<code>module.exports = async function (context, req) {
    context.res = {body:"line 1"};     // alone won't end execution
    context.res.send({body:"send()"};  // send() calls .done() implicitly per MS, still won't end.
    context.done();           // needed by sync, thought would do anyway, but neither
    context.log('JavaScript HTTP trigger function processed a request.');
    ...       // executed
    return;   // lastly it ends here
    var x = 1;  // never reach.
}
</code>```

However, explicit return; is not mentioned in MS Doc. Is it true return is required if to end execution in the middle?

答:
If you want to run/Execute some line of code in your function you have only function level access, not function execution level access. So, whatever you want to do in your function you need to do it before function execution.

    module.exports = async function (context, req) {
        context.log('JavaScript HTTP trigger function processed a request.');
        context.log('started and finised the context here');

        //Function execution Finishing point has context.res

        context.res.send({body: "Insert succeeded."});

        //After Fuction exection we can do some execution but it was function level not in a context level
        // while using async function we dont want to use context.done() & return untill is necessary

        var x = 1;
        console.log("X values is: "+x);

        //You can use return statement if you want to send any return value.
        //return;
    }
```

In your azure function use the async azure function. To call async and await helps to avoid major two problems. Check here to how efficiently use async and await in your function.

Note:
In Azure function not even run a single line of execution after return statement.

A return is needed after context.res to stop execution

Return is not necessary after the context.res.

Updated Explanation:

Context will not work after the function finishing point which are context.res / context.res.send.

When exporting an async function, return keyword is not needed until you have any output binding to return it.

Body:
During Azure Function (AF) debugging, I noticed the both statements context.res={...} and context.res.send() won't end the execution and send back response. To test I create a brand new AF, take the auto-generated files and test using Postman. It goes well.

I then add a new line at the begining:

module.exports = async function (context, req) {
    context.res = {body:"line 1"};     // alone won't end execution
    context.res.send({body:"send()"};  // send() calls .done() implicitly per MS, still won't end.
    context.done();           // needed by sync, thought would do anyway, but neither
    context.log('JavaScript HTTP trigger function processed a request.');
    ...       // executed
    return;   // lastly it ends here
    var x = 1;  // never reach.
}

However, explicit return; is not mentioned in MS Doc. Is it true return is required if to end execution in the middle?

Body:
If you want to run/Execute some line of code in your function you have only function level access, not function execution level access. So, whatever you want to do in your function you need to do it before function execution.

    module.exports = async function (context, req) {
        context.log('JavaScript HTTP trigger function processed a request.');
        context.log('started and finised the context here');

        //Function execution Finishing point has context.res

        context.res.send({body: "Insert succeeded."});

        //After Fuction exection we can do some execution but it was function level not in a context level
        // while using async function we dont want to use context.done() & return untill is necessary

        var x = 1;
        console.log("X values is: "+x);

        //You can use return statement if you want to send any return value.
        //return;
    }

In your azure function use the async azure function. To call async and await helps to avoid major two problems. Check here to how efficiently use async and await in your function.

Note:
In Azure function not even run a single line of execution after return statement.

A return is needed after context.res to stop execution

Return is not necessary after the context.res.

Updated Explanation:

Context will not work after the function finishing point which are context.res / context.res.send.

When exporting an async function, return keyword is not needed until you have any output binding to return it.


问:
Where { component } from 'react' is located when we are importing ReactJS?
So I'm new in ReactJS and wants to learn a couple of small things, and here is one. I wrote an import code on App.js like this:

```<code>import React, { Component } from 'react';
import './App.css';
import Axios from 'axios';
import Load from './Loading.js';
</code>```

I created a custom file for a loading animation and it's imported from import Load from './Loading.js'

the './Loading.js' is the file name and location, and the Load is a const that is exported from the Loading.js file

So my question is, if the Load is a const that I've been exported on the js file I've wrote, then where is the { Component } from 'react' is located? I was trying to find it on the node_modules folder but got no clue. even the react.js file that I thought it was on the node_modules/react folder, I couldn't find it

Thank you before!

答: Component is declared inside react library, it's located inside the node_modules inside react's folder (maybe it's hard to find because the files are minified and packed) if you are using VsCode, you can click on the component and where the cursor is pointing on it then press F12 it will redirect you to the file where it's exactly declared.

Body:
So I'm new in ReactJS and wants to learn a couple of small things, and here is one. I wrote an import code on App.js like this:

import React, { Component } from 'react';
import './App.css';
import Axios from 'axios';
import Load from './Loading.js';

I created a custom file for a loading animation and it's imported from import Load from './Loading.js'

the './Loading.js' is the file name and location, and the Load is a const that is exported from the Loading.js file

So my question is, if the Load is a const that I've been exported on the js file I've wrote, then where is the { Component } from 'react' is located? I was trying to find it on the node_modules folder but got no clue. even the react.js file that I thought it was on the node_modules/react folder, I couldn't find it

Thank you before!


问:
Can't notify users after updating service worker (workbox, cra)
I'm trying to let user know that the app is updated after installing the new service worker.
But the problem is after doing the typical skipWaiting() and ClientsClaim() and trying to send message to clients that there is an update, clients array is empty.

index.js

serviceWorkerRegistration.Register();
```
<p>serviceWorkerRegistration.js</p>
<pre class="lang-js prettyprint-override"><code>
function registerValidSW(swUrl, config) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        if (installingWorker == null) {
          return;
        }
        installingWorker.onstatechange = () => {
          if (installingWorker.state === "installed") {
            if (navigator.serviceWorker.controller) {
              // here workbox sends message to service-worker.js
              registration.waiting.postMessage({ type: "SKIP_WAITING" });

              if (config && config.onUpdate) {
                config.onUpdate(registration);
              }
            } else {
              if (config && config.onSuccess) {
                config.onSuccess(registration);
              }
            }
          }
        };
      };
    })
    .catch(error => {
      console.error("Error during service worker registration:", error);
    });
}
</code>```

service-worker.js

self.addEventListener("message", event => {
  if (event.data && event.data.type === "SKIP_WAITING") {
    skipWaiting();
    clientsClaim();
    //clients array is empty here
    self.clients.matchAll().then(clients => {
       clients.forEach(client => {
        client.postMessage("reload-window");
      });
    });
  }
});

```

Clients array is empty in service-worker.js, That being the case, I can't communicate with user.

(I've also setup notifications with this service worker, Clients array is not empty there as  a result I've no problem communicating with user)

Any help is greatly appreciated.

答:
I was able to reproduce the problem.

Should've been doing this part:

self.clients.matchAll().then(clients => {
       clients.forEach(client => {
        client.postMessage("reload-window");
      });
    });
```
<p>while listening to <code>activate</code> event like this:</p>
<pre class="lang-js prettyprint-override"><code>self.addEventListener("activate", () => {
  self.clients.matchAll().then(clients => {
    clients.forEach(client => {
      client.postMessage("reload-window");
    });
  });
});
</code>```

Body:
I'm trying to let user know that the app is updated after installing the new service worker.
But the problem is after doing the typical skipWaiting() and ClientsClaim() and trying to send message to clients that there is an update, clients array is empty.

index.js

serviceWorkerRegistration.Register();

serviceWorkerRegistration.js

function registerValidSW(swUrl, config) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        if (installingWorker == null) {
          return;
        }
        installingWorker.onstatechange = () => {
          if (installingWorker.state === "installed") {
            if (navigator.serviceWorker.controller) {
              // here workbox sends message to service-worker.js
              registration.waiting.postMessage({ type: "SKIP_WAITING" });

              if (config && config.onUpdate) {
                config.onUpdate(registration);
              }
            } else {
              if (config && config.onSuccess) {
                config.onSuccess(registration);
              }
            }
          }
        };
      };
    })
    .catch(error => {
      console.error("Error during service worker registration:", error);
    });
}

service-worker.js

self.addEventListener("message", event => {
  if (event.data && event.data.type === "SKIP_WAITING") {
    skipWaiting();
    clientsClaim();
    //clients array is empty here
    self.clients.matchAll().then(clients => {
       clients.forEach(client => {
        client.postMessage("reload-window");
      });
    });
  }
});

Clients array is empty in service-worker.js, That being the case, I can't communicate with user.

(I've also setup notifications with this service worker, Clients array is not empty there as  a result I've no problem communicating with user)

Any help is greatly appreciated.

Body:
I was able to reproduce the problem.

Should've been doing this part:

self.clients.matchAll().then(clients => {
       clients.forEach(client => {
        client.postMessage("reload-window");
      });
    });

while listening to activate event like this:

self.addEventListener("activate", () => {
  self.clients.matchAll().then(clients => {
    clients.forEach(client => {
      client.postMessage("reload-window");
    });
  });
});


问:
Regex replace word in string that are not in quotes
I'm looking to do replacements in unknown third-party inputs in strings that sometimes have quotes among them.

I want to replace a wholeword whereever it occurs unless it's in double or single-quotes, and unless the quote is escaped.

Example: Replacing FOO by BAR

Input:

```<code>FOO "FOO" 'FOO' "    1 + FOO + 2 " ABCFOOXYZ "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"FOO\"
</code>```

Expected output:

```<code>BAR "FOO" 'FOO' "    1 + FOO + 2 " ABCFOOXYZ "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"BAR\"
</code>```

More tests:

```<code>name: FOO
favoriteQuote: "I am my own FOO."
children: 'FOO\'s children'
cars: ownersList[FOO]
statement = FOO + " is the owner of the house."
</code>```

Expected output:

```<code>name: BAR
favoriteQuote: "I am my own FOO."
children: 'FOO\'s children'
cars: ownersList[BAR]
statement = BAR + " is the owner of the house."
</code>```

I saw this question: Match and replace a word not in quotes (string contains escaped quotes) which I thought was similar and could be a good starting point the accepted answer does not work at all:

https://regex101.com/r/Lfan64/5

If anyone could help me get the expected result from my regex that would be great, thanks.

答:
If I am understanding your requirements correctly, you may try this regex for your cases:

((['"])(?:\\.|(?!\2).)*(?<!\\)\2)|\bFOO\b/g
```
<p>Updated RegEx Demo</p>
<p>This regex uses alternation to match and discard what we need to keep on LHS of <code>|</code> whereas on RHS we match whatever we want to replace in the result.</p>
<p><strong>Code:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const str = String.raw`name: FOO
favoriteQuote: "I am my own FOO."
children: 'FOO\'s children'
cars: ownersList[FOO]
statement = FOO + " is the owner of the house."
FOO "FOO" 'FOO' "    1 + FOO + 2 " ABCFOOXYZ "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"FOO\"`;

var repl = str.replace(/((['"])(?:\\.|(?!\2).)*(?<!\\)\2)|\bFOO\b/g,
  (_, g) => g || "BAR");

console.log(repl);  </code>```

RegEx Details:

(: Start capture group #1

(['"]): Match ' or " in capture group #2

(?:\\.|(?!\2).)*: Match an escaped character or any character except the quote we matched in capture group #2

(?<!\\)\2: Match whatever quote we matched in capture group #2 as long as it is not preceded by a \

): End capture group #1

|: OR

\bFOO\b: Match complete word FOO

Body:
I'm looking to do replacements in unknown third-party inputs in strings that sometimes have quotes among them.

I want to replace a wholeword whereever it occurs unless it's in double or single-quotes, and unless the quote is escaped.

Example: Replacing FOO by BAR

Input:

FOO "FOO" 'FOO' "    1 + FOO + 2 " ABCFOOXYZ "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"FOO\"

Expected output:

BAR "FOO" 'FOO' "    1 + FOO + 2 " ABCFOOXYZ "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"BAR\"

More tests:

name: FOO
favoriteQuote: "I am my own FOO."
children: 'FOO\'s children'
cars: ownersList[FOO]
statement = FOO + " is the owner of the house."

Expected output:

name: BAR
favoriteQuote: "I am my own FOO."
children: 'FOO\'s children'
cars: ownersList[BAR]
statement = BAR + " is the owner of the house."

I saw this question: Match and replace a word not in quotes (string contains escaped quotes) which I thought was similar and could be a good starting point the accepted answer does not work at all:

https://regex101.com/r/Lfan64/5

If anyone could help me get the expected result from my regex that would be great, thanks.

Body:
If I am understanding your requirements correctly, you may try this regex for your cases:

((['"])(?:\\.|(?!\2).)*(?<!\\)\2)|\bFOO\b/g

Updated RegEx Demo

This regex uses alternation to match and discard what we need to keep on LHS of | whereas on RHS we match whatever we want to replace in the result.

Code:

const str = String.raw`name: FOO
favoriteQuote: "I am my own FOO."
children: 'FOO\'s children'
cars: ownersList[FOO]
statement = FOO + " is the owner of the house."
FOO "FOO" 'FOO' "    1 + FOO + 2 " ABCFOOXYZ "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"FOO\"`;

var repl = str.replace(/((['"])(?:\\.|(?!\2).)*(?<!\\)\2)|\bFOO\b/g,
  (_, g) => g || "BAR");

console.log(repl);

RegEx Details:

(: Start capture group #1

(['"]): Match ' or " in capture group #2

(?:\\.|(?!\2).)*: Match an escaped character or any character except the quote we matched in capture group #2

(?<!\\)\2: Match whatever quote we matched in capture group #2 as long as it is not preceded by a \

): End capture group #1

|: OR

\bFOO\b: Match complete word FOO


问:
SQL Server proc running 5x slower than plain query
I have the following query:

```<code>DECLARE @DaysNotUsed int = 14
DECLARE @DaysNotPhoned int = 7

--Total Unique Students
DECLARE @totalStudents TABLE (SchoolID uniqueidentifier, TotalUniqueStudents int)
INSERT INTO @totalStudents
SELECT
        SSGG.School,
        COUNT(DISTINCT S.StudentID)
    FROM Student S
        INNER JOIN StudentStudents_GroupGroups SSGG ON (SSGG.Students = S.StudentID AND SSGG.School = S.School)
        INNER JOIN [Group] G ON (G.GroupID = SSGG.Groups AND G.School = SSGG.School)
        INNER JOIN SessionHistory SH ON (SH.Student = S.StudentID AND SH.School = S.School AND SH.StartDateTime > GETDATE() - @DaysNotUsed)
    WHERE G.IsBuiltIn = 0
        AND S.HasStartedProduct = 1
    GROUP BY SSGG.School

--Last Used On
DECLARE @lastUsed TABLE (SchoolID uniqueidentifier, LastUsedOn datetime)
INSERT INTO @lastUsed
SELECT
        vi.SchoolID,
        MAX(sh.StartDateTime)
    FROM View_Installation as vi
        INNER JOIN SessionHistory as sh on sh.School = vi.SchoolID
    GROUP BY vi.SchoolID

SELECT
        VI.SchoolID,
        INS.DateAdded,
        INS.Removed,
        INS.DateRemoved,
        INS.DateToInclude,
        VI.SchoolName AS [School Name],
        VI.UsersLicensed AS [Licenses],
        ISNULL(TS.TotalUniqueStudents, 0) as [Total Unique Students],
        ISNULL(TS.TotalUniqueStudents, 0) * 100 / VI.UsersLicensed as [% of Students Using],
        S.State,
        LU.LastUsedOn,
        DATEDIFF(DAY, LU.LastUsedOn, GETDATE()) AS [Days Not Used],
        SI.AreaSalesManager AS [Sales Rep],
        SI.CaseNumber AS [Case #],
        SI.RenewalDate AS [Renewal Date],
        SI.AssignedTo AS [Assigned To],
        SI.Notes AS [Notes]
    FROM View_Installation VI
        INNER JOIN School S ON S.SchoolID = VI.SchoolID
        LEFT OUTER JOIN @totalStudents TS on TS.SchoolID = VI.SchoolID
        INNER JOIN @lastUsed LU on LU.SchoolID = VI.SchoolID
        LEFT OUTER JOIN InactiveReports..SchoolInfo SI ON S.SchoolID = SI.SchoolID
        LEFT OUTER JOIN InactiveReports..InactiveSchools INS ON S.SchoolID = INS.SchoolID
    WHERE VI.UsersLicensed > 0
        AND VI.LastPhoneHome > GETDATE() - @DaysNotPhoned
        AND
        (
            (
                SELECT COUNT(DISTINCT S.StudentID)
                    FROM Student S
                        INNER JOIN StudentStudents_GroupGroups SSGG ON (SSGG.Students = S.StudentID AND SSGG.School = S.School)
                        INNER JOIN [Group] G ON (G.GroupID = SSGG.Groups AND G.School = SSGG.School)
                    WHERE G.IsBuiltIn = 0
                        AND S.School = VI.SchoolID
            ) * 100 / VI.UsersLicensed < 50
            OR
            VI.SchoolID NOT IN
            (
                SELECT DISTINCT SH1.School
                FROM SessionHistory SH1
                WHERE SH1.StartDateTime > GETDATE() - @DaysNotUsed
            )
        )
    ORDER BY [Days Not Used] DESC
</code>```

Running just plain sql like this in SSMS take about 10 seconds to run.  When I created a stored procedure with exactly the same code, the query takes 50 seconds instead.  The only difference in the actual code of the proc is a SET NOCOUNT ON that the IDE put in by default, but adding that line to the query doesn't have any impact.  Any idea what would cause such a dramatic slow down like this?

EDIT I neglected the declare statements at the beginning.  These are not in the proc, but are parameters to it.  Could this be the difference?

答: Also, in addition to everything else mentioned, if you are on SQL Server 2008 and up, have a look at OPTIMIZE FOR UNKNOWN http://blogs.msdn.com/b/sqlprogrammability/archive/2008/11/26/optimize-for-unknown-a-little-known-sql-server-2008-feature.aspx

Body:
I have the following query:

DECLARE @DaysNotUsed int = 14
DECLARE @DaysNotPhoned int = 7

--Total Unique Students
DECLARE @totalStudents TABLE (SchoolID uniqueidentifier, TotalUniqueStudents int)
INSERT INTO @totalStudents
SELECT
        SSGG.School,
        COUNT(DISTINCT S.StudentID)
    FROM Student S
        INNER JOIN StudentStudents_GroupGroups SSGG ON (SSGG.Students = S.StudentID AND SSGG.School = S.School)
        INNER JOIN [Group] G ON (G.GroupID = SSGG.Groups AND G.School = SSGG.School)
        INNER JOIN SessionHistory SH ON (SH.Student = S.StudentID AND SH.School = S.School AND SH.StartDateTime > GETDATE() - @DaysNotUsed)
    WHERE G.IsBuiltIn = 0
        AND S.HasStartedProduct = 1
    GROUP BY SSGG.School

--Last Used On
DECLARE @lastUsed TABLE (SchoolID uniqueidentifier, LastUsedOn datetime)
INSERT INTO @lastUsed
SELECT
        vi.SchoolID,
        MAX(sh.StartDateTime)
    FROM View_Installation as vi
        INNER JOIN SessionHistory as sh on sh.School = vi.SchoolID
    GROUP BY vi.SchoolID

SELECT
        VI.SchoolID,
        INS.DateAdded,
        INS.Removed,
        INS.DateRemoved,
        INS.DateToInclude,
        VI.SchoolName AS [School Name],
        VI.UsersLicensed AS [Licenses],
        ISNULL(TS.TotalUniqueStudents, 0) as [Total Unique Students],
        ISNULL(TS.TotalUniqueStudents, 0) * 100 / VI.UsersLicensed as [% of Students Using],
        S.State,
        LU.LastUsedOn,
        DATEDIFF(DAY, LU.LastUsedOn, GETDATE()) AS [Days Not Used],
        SI.AreaSalesManager AS [Sales Rep],
        SI.CaseNumber AS [Case #],
        SI.RenewalDate AS [Renewal Date],
        SI.AssignedTo AS [Assigned To],
        SI.Notes AS [Notes]
    FROM View_Installation VI
        INNER JOIN School S ON S.SchoolID = VI.SchoolID
        LEFT OUTER JOIN @totalStudents TS on TS.SchoolID = VI.SchoolID
        INNER JOIN @lastUsed LU on LU.SchoolID = VI.SchoolID
        LEFT OUTER JOIN InactiveReports..SchoolInfo SI ON S.SchoolID = SI.SchoolID
        LEFT OUTER JOIN InactiveReports..InactiveSchools INS ON S.SchoolID = INS.SchoolID
    WHERE VI.UsersLicensed > 0
        AND VI.LastPhoneHome > GETDATE() - @DaysNotPhoned
        AND
        (
            (
                SELECT COUNT(DISTINCT S.StudentID)
                    FROM Student S
                        INNER JOIN StudentStudents_GroupGroups SSGG ON (SSGG.Students = S.StudentID AND SSGG.School = S.School)
                        INNER JOIN [Group] G ON (G.GroupID = SSGG.Groups AND G.School = SSGG.School)
                    WHERE G.IsBuiltIn = 0
                        AND S.School = VI.SchoolID
            ) * 100 / VI.UsersLicensed < 50
            OR
            VI.SchoolID NOT IN
            (
                SELECT DISTINCT SH1.School
                FROM SessionHistory SH1
                WHERE SH1.StartDateTime > GETDATE() - @DaysNotUsed
            )
        )
    ORDER BY [Days Not Used] DESC

Running just plain sql like this in SSMS take about 10 seconds to run.  When I created a stored procedure with exactly the same code, the query takes 50 seconds instead.  The only difference in the actual code of the proc is a SET NOCOUNT ON that the IDE put in by default, but adding that line to the query doesn't have any impact.  Any idea what would cause such a dramatic slow down like this?

EDIT I neglected the declare statements at the beginning.  These are not in the proc, but are parameters to it.  Could this be the difference?


问:
Generate row number based on group of number and increase the number if different digit appears
We want to generate row number based on Series column order by Sequence column. For row 1 to 3, series is 1 hence those should be grouped as 1. On row 4, 0 appears and that is causing series to break hence grouping should change from there.

Data and output example:

Below is the code to generate the data.

```<code>        Select 1 AS Sequence,1 AS Series UNION ALL
Select 2 AS Sequence,1 AS Series UNION ALL
Select 3 AS Sequence,1 AS Series UNION ALL
Select 4 AS Sequence,0 AS Series UNION ALL
Select 5 AS Sequence,1 AS Series UNION ALL
Select 6 AS Sequence,1 AS Series UNION ALL
Select 7 AS Sequence,1 AS Series UNION ALL
Select 8 AS Sequence,1 AS Series UNION ALL
Select 9 AS Sequence,0 AS Series UNION ALL
Select 10 AS Sequence,0 AS Series UNION ALL
Select 11 AS Sequence,0 AS Series UNION ALL
Select 12 AS Sequence,0 AS Series UNION ALL
Select 13 AS Sequence,0 AS Series UNION ALL
Select 14 AS Sequence,0 AS Series UNION ALL
Select 15 AS Sequence,0 AS Series UNION ALL
Select 16 AS Sequence,0 AS Series UNION ALL
Select 17 AS Sequence,0 AS Series UNION ALL
Select 18 AS Sequence,0 AS Series UNION ALL
Select 19 AS Sequence,0 AS Series UNION ALL
Select 20 AS Sequence,0 AS Series UNION ALL
Select 21 AS Sequence,1 AS Series UNION ALL
Select 22 AS Sequence,1 AS Series UNION ALL
Select 23 AS Sequence,1 AS Series
</code>```

答:
You can try to use LAG window function in a subquery then use SUM
condition aggregate window function to make it.

```<code>;with cte as (
   Select 1 AS Sequence,1 AS Series UNION ALL
Select 2 AS Sequence,1 AS Series UNION ALL
Select 3 AS Sequence,1 AS Series UNION ALL
Select 4 AS Sequence,0 AS Series UNION ALL
Select 5 AS Sequence,1 AS Series UNION ALL
Select 6 AS Sequence,1 AS Series UNION ALL
Select 7 AS Sequence,1 AS Series UNION ALL
Select 8 AS Sequence,1 AS Series UNION ALL
Select 9 AS Sequence,0 AS Series UNION ALL
Select 10 AS Sequence,0 AS Series UNION ALL
Select 11 AS Sequence,0 AS Series UNION ALL
Select 12 AS Sequence,0 AS Series UNION ALL
Select 13 AS Sequence,0 AS Series UNION ALL
Select 14 AS Sequence,0 AS Series UNION ALL
Select 15 AS Sequence,0 AS Series UNION ALL
Select 16 AS Sequence,0 AS Series UNION ALL
Select 17 AS Sequence,0 AS Series UNION ALL
Select 18 AS Sequence,0 AS Series UNION ALL
Select 19 AS Sequence,0 AS Series UNION ALL
Select 20 AS Sequence,0 AS Series UNION ALL
Select 21 AS Sequence,1 AS Series UNION ALL
Select 22 AS Sequence,1 AS Series UNION ALL
Select 23 AS Sequence,1 AS Series
)

SELECT  Sequence,Series,
       SUM(CASE WHEN n_Series <> Series THEN 1 ELSE 0 END) OVER(ORDER BY Sequence) + 1 generalNumber
FROM (
 SELECT *,LAG(Series) OVER( ORDER BY Sequence) n_Series
 FROM CTE
) t1
</code>```

sqlfiddle

Body:
We want to generate row number based on Series column order by Sequence column. For row 1 to 3, series is 1 hence those should be grouped as 1. On row 4, 0 appears and that is causing series to break hence grouping should change from there.

Data and output example:

Below is the code to generate the data.

        Select 1 AS Sequence,1 AS Series UNION ALL
Select 2 AS Sequence,1 AS Series UNION ALL
Select 3 AS Sequence,1 AS Series UNION ALL
Select 4 AS Sequence,0 AS Series UNION ALL
Select 5 AS Sequence,1 AS Series UNION ALL
Select 6 AS Sequence,1 AS Series UNION ALL
Select 7 AS Sequence,1 AS Series UNION ALL
Select 8 AS Sequence,1 AS Series UNION ALL
Select 9 AS Sequence,0 AS Series UNION ALL
Select 10 AS Sequence,0 AS Series UNION ALL
Select 11 AS Sequence,0 AS Series UNION ALL
Select 12 AS Sequence,0 AS Series UNION ALL
Select 13 AS Sequence,0 AS Series UNION ALL
Select 14 AS Sequence,0 AS Series UNION ALL
Select 15 AS Sequence,0 AS Series UNION ALL
Select 16 AS Sequence,0 AS Series UNION ALL
Select 17 AS Sequence,0 AS Series UNION ALL
Select 18 AS Sequence,0 AS Series UNION ALL
Select 19 AS Sequence,0 AS Series UNION ALL
Select 20 AS Sequence,0 AS Series UNION ALL
Select 21 AS Sequence,1 AS Series UNION ALL
Select 22 AS Sequence,1 AS Series UNION ALL
Select 23 AS Sequence,1 AS Series

Body:
You can try to use LAG window function in a subquery then use SUM
condition aggregate window function to make it.

;with cte as (
   Select 1 AS Sequence,1 AS Series UNION ALL
Select 2 AS Sequence,1 AS Series UNION ALL
Select 3 AS Sequence,1 AS Series UNION ALL
Select 4 AS Sequence,0 AS Series UNION ALL
Select 5 AS Sequence,1 AS Series UNION ALL
Select 6 AS Sequence,1 AS Series UNION ALL
Select 7 AS Sequence,1 AS Series UNION ALL
Select 8 AS Sequence,1 AS Series UNION ALL
Select 9 AS Sequence,0 AS Series UNION ALL
Select 10 AS Sequence,0 AS Series UNION ALL
Select 11 AS Sequence,0 AS Series UNION ALL
Select 12 AS Sequence,0 AS Series UNION ALL
Select 13 AS Sequence,0 AS Series UNION ALL
Select 14 AS Sequence,0 AS Series UNION ALL
Select 15 AS Sequence,0 AS Series UNION ALL
Select 16 AS Sequence,0 AS Series UNION ALL
Select 17 AS Sequence,0 AS Series UNION ALL
Select 18 AS Sequence,0 AS Series UNION ALL
Select 19 AS Sequence,0 AS Series UNION ALL
Select 20 AS Sequence,0 AS Series UNION ALL
Select 21 AS Sequence,1 AS Series UNION ALL
Select 22 AS Sequence,1 AS Series UNION ALL
Select 23 AS Sequence,1 AS Series
)

SELECT  Sequence,Series,
       SUM(CASE WHEN n_Series <> Series THEN 1 ELSE 0 END) OVER(ORDER BY Sequence) + 1 generalNumber
FROM (
 SELECT *,LAG(Series) OVER( ORDER BY Sequence) n_Series
 FROM CTE
) t1

sqlfiddle