问:
Is there a way to find which function in typescript compiler correspond to which action in vscode
I want to know what happen in the typescript compiler when I select an item in the completion list, but I don't know what function it calls. Like:

```<code>x.
</code>```

when I typing the ., a completion list shows up, this action will trigger getCompletionsAtPosition in /service/completions.ts. I used to do it by searching similar name in typescript compiler, but it doesn't work all the time, is there an accurate way to find this out?

答:
VS Code uses the TypeScript server to power JavaScript and TypeScript features. You can look at VS Code's TS Server trace to see which actions are being invoked:

In VS Code, set "typescript.tsserver.trace": "messages"

Open the output panel and go to the TypeScript section.

This lists the server requests that are sent:

```<code>[Trace  - 2:11:30 PM] Sending request: updateOpen (4957). Response expected: no. Current queue length: 0
[Trace  - 2:11:30 PM] Sending request: getApplicableRefactors (4958). Response expected: yes. Current queue length: 0
[Trace  - 2:11:30 PM] Response received: getApplicableRefactors (4958). Request took 105 ms. Success: true
[Trace  - 2:11:30 PM] Sending request: geterr (4959). Response expected: yes. Current queue length: 1
[Trace  - 2:11:30 PM] Sending request: navtree (4960). Response expected: yes. Current queue length: 0
</code>```

getApplicableRefactors, geterr, and navtree are the request names. Look for these in the TS codebase

Body:
I want to know what happen in the typescript compiler when I select an item in the completion list, but I don't know what function it calls. Like:

x.

when I typing the ., a completion list shows up, this action will trigger getCompletionsAtPosition in /service/completions.ts. I used to do it by searching similar name in typescript compiler, but it doesn't work all the time, is there an accurate way to find this out?

Body:
VS Code uses the TypeScript server to power JavaScript and TypeScript features. You can look at VS Code's TS Server trace to see which actions are being invoked:

In VS Code, set "typescript.tsserver.trace": "messages"

Open the output panel and go to the TypeScript section.

This lists the server requests that are sent:

[Trace  - 2:11:30 PM] Sending request: updateOpen (4957). Response expected: no. Current queue length: 0
[Trace  - 2:11:30 PM] Sending request: getApplicableRefactors (4958). Response expected: yes. Current queue length: 0
[Trace  - 2:11:30 PM] Response received: getApplicableRefactors (4958). Request took 105 ms. Success: true
[Trace  - 2:11:30 PM] Sending request: geterr (4959). Response expected: yes. Current queue length: 1
[Trace  - 2:11:30 PM] Sending request: navtree (4960). Response expected: yes. Current queue length: 0

getApplicableRefactors, geterr, and navtree are the request names. Look for these in the TS codebase


来源: stackexchange

问:
How to add global style to angular 6/7 library
I was trying to add global styles in the same way like in angular app, but it totally does not work.

My libraries' name is example-lib, so I added styles.css to /projects/example-lib/. I added styles in main angular.json file:

```<code>...
"example-lib": {
  "root": "projects/example-lib",
  "sourceRoot": "projects/example-lib/src",
  "projectType": "library",
  "prefix": "ngx",
  "architect": {
    "build": {
      "builder": "@angular-devkit/build-ng-packagr:build",
      "options": {
        "tsConfig": "projects/example-lib/tsconfig.lib.json",
        "project": "projects/example-lib/ng-package.json",
        "styles": [
          "projects/example-lib/styles.css" <!-- HERE
        ],
      },
...
</code>```

But when I tried build library using command:

ng build example-lib

I got error:

```<code>  Schema validation failed with the following errors:
  Data path "" should NOT have additional properties(styles)
</code>```

I guess that is the other way to add global styles in separate library. Anyone can help me?

答:
From this issue solution

Install cpx and scss-bundle as Dev dependencies to your package.json. Then add the following entries in your package.json "scripts" property:

```<code>"scripts": {
  ...
  "build-mylib": "ng build mylib && npm run build-mylib-styles && npm run cp-mylib-assets",
  "build-mylib-styles": "cpx \"./projects/mylib/src/lib/style/**/*\" \"./dist/mylib/style\" && scss-bundle -e ./projects/mylib/src/lib/style/_style.scss -d ./dist/mylib/style/_styles.scss",
  "cp-mylib-assets": "cpx \"./src/assets/**/*\" \"./dist/mylib/assets\"",
  ...
}
</code>```

Replace "mylib" with your real library name and then just run in your terminal build-mylib. That would compile your scss assets to your dist folder.

You use this global styles in your actual Angular project just import them in your angular.json file within your project settings:

```<code>"styles": [
  "src/styles.scss",
  "dist/my-shiny-library/_theme.scss"
],
</code>```

(use dist if your project is in the same workspace, or node_moduled if its an imported library)

ContentLicense: CC BY-SA 4.0

Body:
I was trying to add global styles in the same way like in angular app, but it totally does not work.

My libraries' name is example-lib, so I added styles.css to /projects/example-lib/. I added styles in main angular.json file:

...
"example-lib": {
  "root": "projects/example-lib",
  "sourceRoot": "projects/example-lib/src",
  "projectType": "library",
  "prefix": "ngx",
  "architect": {
    "build": {
      "builder": "@angular-devkit/build-ng-packagr:build",
      "options": {
        "tsConfig": "projects/example-lib/tsconfig.lib.json",
        "project": "projects/example-lib/ng-package.json",
        "styles": [
          "projects/example-lib/styles.css"

Body:
From this issue solution

Install cpx and scss-bundle as Dev dependencies to your package.json. Then add the following entries in your package.json "scripts" property:

"scripts": {
  ...
  "build-mylib": "ng build mylib && npm run build-mylib-styles && npm run cp-mylib-assets",
  "build-mylib-styles": "cpx \"./projects/mylib/src/lib/style/**/*\" \"./dist/mylib/style\" && scss-bundle -e ./projects/mylib/src/lib/style/_style.scss -d ./dist/mylib/style/_styles.scss",
  "cp-mylib-assets": "cpx \"./src/assets/**/*\" \"./dist/mylib/assets\"",
  ...
}

Replace "mylib" with your real library name and then just run in your terminal build-mylib. That would compile your scss assets to your dist folder.

You use this global styles in your actual Angular project just import them in your angular.json file within your project settings:

"styles": [
  "src/styles.scss",
  "dist/my-shiny-library/_theme.scss"
],

(use dist if your project is in the same workspace, or node_moduled if its an imported library)


问:
How to expand v-expansion-panel by default with vue/vuetify?
I'd like to have an expansion panel <v-expansion-panel> open by default on page load, but cannot figure it out. I know for Angular, you put [expanded]="true", but this doesn't work with Vue. I haven't had luck anywhere finding this answer. I'm not sure if javascript is needed or not, or if it can be done right within the <v-expansion-panel> tag.

I tried <v-expansion-panel [expanded]="true" and it did show the buttons that are in that section, but that's it.

   <v-app>
      <v-expansion-panel
         v-model="search"
         expand
      >
.
.
.
   </v-app>

```

答:
Watch the PROPS section on the documentation:

https://vuetifyjs.com/en/components/expansion-panels#expansion-panel

The expand prop says: Leaves the expansion-panel open while selecting another.

This is not what you want.

You need to use value prop: Controls the opened/closed state of content in the expansion-panel. Corresponds to a zero-based index of the currently opened content. If expand prop is used then it is an array of Booleans where the index corresponds to the index of the content.

So, in your case:

 <v-app>
  <v-expansion-panel
     v-model="search"
     :value="0"
  >
  .
  .
  .
  </v-app>

```

Where "0" is the index of the expansion panel expanded by default.

I made an example here:

https://codepen.io/anon/pen/pmqyOP?&editable=true&editors=101#anon-login

Body:
Watch the PROPS section on the documentation:

https://vuetifyjs.com/en/components/expansion-panels#expansion-panel

The expand prop says: Leaves the expansion-panel open while selecting another.

This is not what you want.

You need to use value prop: Controls the opened/closed state of content in the expansion-panel. Corresponds to a zero-based index of the currently opened content. If expand prop is used then it is an array of Booleans where the index corresponds to the index of the content.

So, in your case:

<section>
 <v-app>
  <v-expansion-panel
     v-model="search"
     :value="0"
  >
  .
  .
  .
  </v-app>
</section>

Where "0" is the index of the expansion panel expanded by default.

I made an example here:

https://codepen.io/anon/pen/pmqyOP?&editable=true&editors=101#anon-login


问:
Configuring the maven java-docs plugin for multi module projects(Aggregate)
I would like to set up the maven java-docs plugin in my project to create an aggregated report that includes only some classes from some of the modules and output the report to a folder of choice.

I have already tried to work with the Maven documentation here however whats indicated there does not seem to work for me.
I have tried the following configuration in the past and ran it as:
mvn javadoc:javadoc, or even javadoc:aggregate with the following parent/child pom configurations:

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <version>3.1.0</version>
    <inherited>false</inherited>
    <configuration>
        <!-- Default configuration for all reports -->
    </configuration>
    <executions>
        <execution>
            <id>aggregate</id>
            <goals>
                <goal>aggregate</goal>
            </goals>
            <phase>package</phase>
            <configuration>
            </configuration>
        </execution>
    </executions>
</plugin>
</code>```

I have used something like this in the past:

parent pom.xml

```<code><pluginManagement>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <configuration>
            <skip>true</skip>
        </configuration>
    </plugin>
</pluginManagement>
...
<build>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>3.1.0</version>
        <configuration>
            <!-- Default configuration for all reports -->
        </configuration>
        <executions>
            <execution>
                <id>aggregate</id>
                <goals>
                    <goal>aggregate</goal>
                </goals>
                <phase>site</phase>
                <configuration>
                    <skip>false</skip>
                </configuration>
            </execution>
        </executions>
    </plugin>
</build>
</code>```

Desired child module pom.xml

```<code><build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-javadoc-plugin</artifactId>
            <configuration>
                <skip>false</skip>
                <noqualifier>all</noqualifier>
                <sourceFileIncludes>
                    <include>**\/\Class1.java</include>
                    <include>**\/\Class2.java</include>
                    <include>**\/\Interface3.java</include>
                    <include>**\/\Class4.java</include>
                </sourceFileIncludes>
                <reportOutputDirectory>${project.parent.basedir}/..</reportOutputDirectory>
                <destDir>java-docs</destDir>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

This configuration works fine if I am only generating from one single module, however once another child module is picked and configured as the one shown before, running mvn javadoc:aggregate continues to generate the docs for module 1 only, and module 2 gets ignored(or maybe even overriden)

Has anyone worked with a similar scenario, a multi module project structured like so:

```<code>ParentFolder
. . . module1
        pom.xml
. . . module3
        pom.xml
. . . module4
        pom.xml
pom.xml
</code>```

and have succeeded generating an aggregated java docs report using the maven java docs plugin, while excluding some classes and outputting the results to a folder of their choice?
Any help with this would be greatly appreciated!

答:
Do you have one parent POM that contains both plugin config for the child POMs, and module definitions? If so, you may want to consider separating this POM into a separate aggregator (module definitions) and parent (anything else in the current POM that should be shared with children).

This answer goes into a lot more detail about Maven build order and why the behavior occurs.

The aggregator POM will also hold the configuration for child module data that should be aggregated, such as Javadoc.

Body:
I would like to set up the maven java-docs plugin in my project to create an aggregated report that includes only some classes from some of the modules and output the report to a folder of choice.

I have already tried to work with the Maven documentation here however whats indicated there does not seem to work for me.
I have tried the following configuration in the past and ran it as:
mvn javadoc:javadoc, or even javadoc:aggregate with the following parent/child pom configurations:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <version>3.1.0</version>
    <inherited>false</inherited>
    <configuration>

    </configuration>
    <executions>
        <execution>
            <id>aggregate</id>
            <goals>
                <goal>aggregate</goal>
            </goals>
            <phase>package</phase>
            <configuration>
            </configuration>
        </execution>
    </executions>
</plugin>

I have used something like this in the past:

parent pom.xml

<pluginManagement>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <configuration>
            <skip>true</skip>
        </configuration>
    </plugin>
</pluginManagement>
...
<build>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>3.1.0</version>
        <configuration>

        </configuration>
        <executions>
            <execution>
                <id>aggregate</id>
                <goals>
                    <goal>aggregate</goal>
                </goals>
                <phase>site</phase>
                <configuration>
                    <skip>false</skip>
                </configuration>
            </execution>
        </executions>
    </plugin>
</build>

Desired child module pom.xml

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-javadoc-plugin</artifactId>
            <configuration>
                <skip>false</skip>
                <noqualifier>all</noqualifier>
                <sourceFileIncludes>
                    <include>**\/\Class1.java</include>
                    <include>**\/\Class2.java</include>
                    <include>**\/\Interface3.java</include>
                    <include>**\/\Class4.java</include>
                </sourceFileIncludes>
                <reportOutputDirectory>${project.parent.basedir}/..</reportOutputDirectory>
                <destDir>java-docs</destDir>
            </configuration>
        </plugin>
    </plugins>
</build>

This configuration works fine if I am only generating from one single module, however once another child module is picked and configured as the one shown before, running mvn javadoc:aggregate continues to generate the docs for module 1 only, and module 2 gets ignored(or maybe even overriden)

Has anyone worked with a similar scenario, a multi module project structured like so:

ParentFolder
. . . module1
        pom.xml
. . . module3
        pom.xml
. . . module4
        pom.xml
pom.xml

and have succeeded generating an aggregated java docs report using the maven java docs plugin, while excluding some classes and outputting the results to a folder of their choice?
Any help with this would be greatly appreciated!


问:
How can I print an item in a website using selenium
I need a way to search in a website for a specific keyword and output it to the console.

The xpath:

```<code>//*[@id="tab_actions_pending"]/div/div[1]/div/div/div[1]/div[2]/p
</code>```

I need the script to try to find the word 100% in that xpath and if it doesnt find it will pass and exit the script!

The website image with inspect open:

答:
Search in xpath is done via find_elements_by_xpath:</p>

```<code>driver.find_elements_by_xpath("//*[contains(text(), '100%')]")
</code>```

Body:
I need a way to search in a website for a specific keyword and output it to the console.

The xpath:

//*[@id="tab_actions_pending"]/div/div[1]/div/div/div[1]/div[2]/p

I need the script to try to find the word 100% in that xpath and if it doesnt find it will pass and exit the script!

The website image with inspect open:

Body:
Search in xpath is done via find_elements_by_xpath:

driver.find_elements_by_xpath("//*[contains(text(), '100%')]")


问:
Pandas: Handling Dataframes
A certain dataframe, has a similar break with the one below:

```<code>import pandas as pd

df = pd.DataFrame({'name': ['John', 'Elvis', 'Gerrard', 'Pitty'],
              'age': [22,23,24,25],
              'document': [111,222,333,4444]})
</code>```

How can I make a filter to return only the rows where the values in the document column are only 3 digits?

答:
This will work for positive and negative numbers in the document column:

```<code>df[df['document'].abs().astype(str).str.len() == 3]
</code>```

Title: Pandas: Handling Dataframes

Body:
A certain dataframe, has a similar break with the one below:

import pandas as pd

df = pd.DataFrame({'name': ['John', 'Elvis', 'Gerrard', 'Pitty'],
              'age': [22,23,24,25],
              'document': [111,222,333,4444]})

How can I make a filter to return only the rows where the values in the document column are only 3 digits?

Body:
This will work for positive and negative numbers in the document column:

df[df['document'].abs().astype(str).str.len() == 3]


问:
How change variable from function setTimeout inside an loop
How alternate value to variable dinamic_delay using conditions described below?</p>

```<code>var emails = []; // array
var number = 5;
var count = 0;
var dinamic_delay;
for (i = 0; i < emails.length; i++) {
    count++;
    if (count == number) {
        dinamic_delay = 3000;
        count = 0; // resset count
    } else {
        dinamic_delay = 500;
    }
    setTimeout(function (i) {
        sendemail(email[i]);
    }, dinamic_delay * i, i);
}
</code>```

答:
I had to remind myself how setTimeout works:

a. setTimeout(myfunction(), 5000)   -calls the function after at least 5000 millisecs from now (when this code is executed)

b. setTimeout(myfunction(), 5000)   -calls the function after at least 5000 millisecs from now (when this code is executed)

in other words there is not an automatic 10,000 millisec before b is called, e.g. might by 6000 ms

setInterval is useful if you want to call things at regular intervals.

The example below displays console.log message 3, 3, 3, 3, 10 seconds & repeats until the final email.

```<code>    const bigDelay_c = 10000;  //secs
    const smallDelay_c = 3000;  //secs
    const totalEmails_c = 18;   //total to process

    var totalEmailsProcessed = 0; //running total
    var timerId = 0;

    timerId = setInterval(alertFunc, smallDelay_c);

    function alertFunc() {

        //sendEmail logic here
        var currentdate = new Date();
        totalEmailsProcessed++;
        console.log(totalEmailsProcessed, currentdate.getHours() + ":" +
            currentdate.getMinutes() + ":" + currentdate.getSeconds());
        clearInterval(timerId);  //stop interval repeating

        //stop if all emails have been processed
        if (totalEmailsProcessed >= totalEmails_c) {
            console.log('all emails processed');
            return;
        }

        //5th item in every 5 get bigDelay_c
        if (totalEmailsProcessed % 5 == 4)
            timerId = setInterval(alertFunc, bigDelay_c);
        else
            timerId = setInterval(alertFunc, smallDelay_c);

    }
</code>```

Body:
How alternate value to variable dinamic_delay using conditions described below?

var emails = []; // array
var number = 5;
var count = 0;
var dinamic_delay;
for (i = 0; i < emails.length; i++) {
    count++;
    if (count == number) {
        dinamic_delay = 3000;
        count = 0; // resset count
    } else {
        dinamic_delay = 500;
    }
    setTimeout(function (i) {
        sendemail(email[i]);
    }, dinamic_delay * i, i);
}

Body:
I had to remind myself how setTimeout works:

a. setTimeout(myfunction(), 5000)   -calls the function after at least 5000 millisecs from now (when this code is executed)

b. setTimeout(myfunction(), 5000)   -calls the function after at least 5000 millisecs from now (when this code is executed)

in other words there is not an automatic 10,000 millisec before b is called, e.g. might by 6000 ms

setInterval is useful if you want to call things at regular intervals.

The example below displays console.log message 3, 3, 3, 3, 10 seconds & repeats until the final email.

    const bigDelay_c = 10000;  //secs
    const smallDelay_c = 3000;  //secs
    const totalEmails_c = 18;   //total to process

    var totalEmailsProcessed = 0; //running total
    var timerId = 0;

    timerId = setInterval(alertFunc, smallDelay_c);

    function alertFunc() {

        //sendEmail logic here
        var currentdate = new Date();
        totalEmailsProcessed++;
        console.log(totalEmailsProcessed, currentdate.getHours() + ":" +
            currentdate.getMinutes() + ":" + currentdate.getSeconds());
        clearInterval(timerId);  //stop interval repeating

        //stop if all emails have been processed
        if (totalEmailsProcessed >= totalEmails_c) {
            console.log('all emails processed');
            return;
        }

        //5th item in every 5 get bigDelay_c
        if (totalEmailsProcessed % 5 == 4)
            timerId = setInterval(alertFunc, bigDelay_c);
        else
            timerId = setInterval(alertFunc, smallDelay_c);

    }


问:
IE8 CSS Hack - best method?
Can anyone recommend the best way to hack IE8 styling via CSS, I've recently been making IE8 render as IE7 for ease -  but wondered if it was best to add IE8 hacks?</p>

答: Use the ie7-js Javascript library, which does some magic to make older IE versions behave more like proper browsers with their handling of HTML and CSS.  Then, as others have suggested, write your code in a standards-compliant manner which behaves well with the latest versions of Chrome, Firefox, Opera, etc.</p>

Title: IE8 CSS Hack - best method?

ContentLicense: CC BY-SA 3.0


问:
Absolute position with Bootstrap and jQuery slider
I have a problem with jQuery and Bootstrap. On the first page load 2 divs are loaded, what is not the intention. Second thing, when I add a position-absolute to my div, my css does weird things and the container appears not in the centre anymore. I want to do this because now the slider flips and it needs to keep 1 place in the middle.
Could you please advise me on possible solutions?

I have a full page demo too: https://mella.ga/test/k/scherm.html

答:
To fix your issue with the two divs being shown at the beginning you simply set display: none on your #slideshow with css, and with jQuery you show the #slideshow when document is loaded

```<code>$(document).ready(function(){
    $("#slideshow").fadeIn(1000);
});
</code>```

For your second question I might need some more explanation to help, since I am not quite sure what you mean by "css does weird things". Could you explain this better? What do you want your container to do?

Body:
To fix your issue with the two divs being shown at the beginning you simply set display: none on your #slideshow with css, and with jQuery you show the #slideshow when document is loaded

$(document).ready(function(){
    $("#slideshow").fadeIn(1000);
});

For your second question I might need some more explanation to help, since I am not quite sure what you mean by "css does weird things". Could you explain this better? What do you want your container to do?


问:
How to get a list of all files in Cloud Storage in a Firebase app?
I'm working on uploading images, everything works great, but I have 100 pictures and I would like to show all of them in my View, as I get the complete list of the images in a folder, I can not find any API for this work.

答:
As of May 2019, version 6.1.0 of the Firebase SDK for Cloud Storage now supports listing all objects from a bucket. You simply need to call listAll() in a Reference:

    // Since you mentioned your images are in a folder,
    // we'll create a Reference to that folder:
    var storageRef = firebase.storage().ref("your_folder");

    // Now we get the references of these images
    storageRef.listAll().then(function(result) {
      result.items.forEach(function(imageRef) {
        // And finally display them
        displayImage(imageRef);
      });
    }).catch(function(error) {
      // Handle any errors
    });

    function displayImage(imageRef) {
      imageRef.getDownloadURL().then(function(url) {
        // TODO: Display the image on the UI
      }).catch(function(error) {
        // Handle any errors
      });
    }
```

<p>Please <strong>note</strong> that in order to use this function, you must opt-in to version 2 of Security Rules, which can be done by making <code>rules_version = '2';</code> the first line of your security rules:</p>

<pre class="lang-js prettyprint-override"><code>    rules_version = '2';
    service firebase.storage {
      match /b/{bucket}/o {
        match /{allPaths=**} {
</code>```

I'd recommend checking the docs for further reference.

Also, according to setup, on Step 5, this script is not allowed for Node.js since require("firebase/app"); won't return firebase.storage() as a function. This is only achieved using import * as firebase from 'firebase/app';.

Body:
As of May 2019, version 6.1.0 of the Firebase SDK for Cloud Storage now supports listing all objects from a bucket. You simply need to call listAll() in a Reference:

    // Since you mentioned your images are in a folder,
    // we'll create a Reference to that folder:
    var storageRef = firebase.storage().ref("your_folder");

    // Now we get the references of these images
    storageRef.listAll().then(function(result) {
      result.items.forEach(function(imageRef) {
        // And finally display them
        displayImage(imageRef);
      });
    }).catch(function(error) {
      // Handle any errors
    });

    function displayImage(imageRef) {
      imageRef.getDownloadURL().then(function(url) {
        // TODO: Display the image on the UI
      }).catch(function(error) {
        // Handle any errors
      });
    }

Please note that in order to use this function, you must opt-in to version 2 of Security Rules, which can be done by making rules_version = '2'; the first line of your security rules:

    rules_version = '2';
    service firebase.storage {
      match /b/{bucket}/o {
        match /{allPaths=**} {

I'd recommend checking the docs for further reference.

Also, according to setup, on Step 5, this script is not allowed for Node.js since require("firebase/app"); won't return firebase.storage() as a function. This is only achieved using import * as firebase from 'firebase/app';.


问:
Simple CSS Positioning Question
Basically I'm trying to create a small div (header class) that sits on top of a main banner image div (banner class). I've been able to position it correctly when my browser window is maximized, but when I resize the browser the header div maintains the margins and shrinks down to much less than the banner's width. I realize this is because I have the margins set at fixed positions on the left and right so they're maintaining those positions... I'm just new to CSS and am not sure exactly what to do to prevent this from happening. I've been messing around with positioning for about an hour and just can't get it right.

CSS:

```<code><style type = "text/css">

body {
    background-color: #595959;
}

.header {
   background-color: #4CBB17;
    padding: 12px 0px 12px 0px;
    margin: 0px 137px 0px; 137px;
}

.banner {
    text-align: center;
}

</style>
</code>```

HTML:

```<code><html>
<head>
    <title>Thanks!</title>
    <link type="text/css" rel="stylesheet" href="style.css" />
</head>

<body>

    <div class="header">
    </div>

    <div class="banner">
        <img src="banner.jpg" />
    </div>

</body>
</html>
</code>```

Any help would be much appreciated!

答:
I´m not sure what you are trying to achieve exactly, but if you want the banner always to be the same size as the header, you can use:

```<code>.header, .banner {
    margin: 0px 137px 0px; 137px;
}
.header {
   background-color: #4CBB17;
    padding: 12px 0px 12px 0px;
}

.banner img {
    width: 100%;
}
</code>```

Or you get rid of the banner altogether and use a background image for the header.

Title: Simple CSS Positioning Question

Body:
Basically I'm trying to create a small div (header class) that sits on top of a main banner image div (banner class). I've been able to position it correctly when my browser window is maximized, but when I resize the browser the header div maintains the margins and shrinks down to much less than the banner's width. I realize this is because I have the margins set at fixed positions on the left and right so they're maintaining those positions... I'm just new to CSS and am not sure exactly what to do to prevent this from happening. I've been messing around with positioning for about an hour and just can't get it right.

CSS:

HTML:

    <title>Thanks!</title>
    <link type="text/css" rel="stylesheet" href="style.css" />

Any help would be much appreciated!

Body:
I´m not sure what you are trying to achieve exactly, but if you want the banner always to be the same size as the header, you can use:

.header, .banner {
    margin: 0px 137px 0px; 137px;
}
.header {
   background-color: #4CBB17;
    padding: 12px 0px 12px 0px;
}

.banner img {
    width: 100%;
}

Or you get rid of the banner altogether and use a background image for the header.


问:
When I make an ajax delete request with a checkbox An error occurs in the view function
When I make an ajax delete request with a checkbox

An error occurs in the view function.

I do not know why.

Thank you if you let me know.

error :

```<code>Traceback (most recent call last):
  File "C:\django_inflearn2\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\django_inflearn2\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\django_inflearn2\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\django_inflearn2\todo\views.py", line 23, in todo_delete_ajax
    todo_ids = request.POST['todo_arr']
  File "C:\django_inflearn2\venv\lib\site-packages\django\utils\datastructures.py", line 80, in __getitem__
    raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'todo_arr'
</code>```

code is below

jquery,ajax

```<code>$('#todo_delete_button').click(function(e){
    e.preventDefault();
    // todo_check
    var todo_arr = [];
    alert("삭제 버튼 ")
    // Get checked checkboxes
    $('.td_check').each(function() {
        if (jQuery(this).is(":checked")) {
            var id = this.id;
            todo_arr.push(id);
        }
    });
    alert('todo_arr : '+ todo_arr)

    $.ajax({
      type: "POST",
      url: 'todo_delete_ajax/',
      data: {
          todo_arr:todo_arr,
          csrfmiddlewaretoken: '{{ csrf_token }}'
      },
        success: function(result) {
            alert('todo_delete_ajax is success ');
        }
    });
})
</code>```

url

```<code>    path('status/',views.todo_status_list, name ="todo_status_list"),
</code>```

view

```<code>def todo_delete_ajax(request):
    # print("request " , request )
    todo_ids = request.POST['todo_arr']
    print("todo_ids : ", todo_ids)

    return redirect('/todo/')
</code>```

Is the format of jquery ajax wrong?

Is the url pattern wrong?

Is the argument value set incorrectly?

Is the view function wrong?

Thank you if you can tell me how to fix it.

答: "data" is a dictionary, and "todo_arr" is multi-valued. You might have to do a JSON.stringify() to get it to work.</p>

Body:
When I make an ajax delete request with a checkbox

An error occurs in the view function.

I do not know why.

Thank you if you let me know.

error :

Traceback (most recent call last):
  File "C:\django_inflearn2\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\django_inflearn2\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\django_inflearn2\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\django_inflearn2\todo\views.py", line 23, in todo_delete_ajax
    todo_ids = request.POST['todo_arr']
  File "C:\django_inflearn2\venv\lib\site-packages\django\utils\datastructures.py", line 80, in __getitem__
    raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'todo_arr'

code is below

jquery,ajax

$('#todo_delete_button').click(function(e){
    e.preventDefault();
    // todo_check
    var todo_arr = [];
    alert("삭제 버튼 ")
    // Get checked checkboxes
    $('.td_check').each(function() {
        if (jQuery(this).is(":checked")) {
            var id = this.id;
            todo_arr.push(id);
        }
    });
    alert('todo_arr : '+ todo_arr)

    $.ajax({
      type: "POST",
      url: 'todo_delete_ajax/',
      data: {
          todo_arr:todo_arr,
          csrfmiddlewaretoken: '{{ csrf_token }}'
      },
        success: function(result) {
            alert('todo_delete_ajax is success ');
        }
    });
})

url

    path('status/',views.todo_status_list, name ="todo_status_list"),

view

def todo_delete_ajax(request):
    # print("request " , request )
    todo_ids = request.POST['todo_arr']
    print("todo_ids : ", todo_ids)

    return redirect('/todo/')

Is the format of jquery ajax wrong?

Is the url pattern wrong?

Is the argument value set incorrectly?

Is the view function wrong?

Thank you if you can tell me how to fix it.


问:
Selenium: Point towards default Chrome session
Though I realize it's NOT "good" practice - I have a use case where I need to point (hook up) the Selenium driver to my default Chrome session/profile.

My default profile is here:
~/Library/Caches/Google/Chrome/Default

Here is how I'm seting it up currently: (not working)

```<code>from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument("--user-data-dir=~/Library/Caches/Google/Chrome")
options.add_argument("--profile-directory=Default")
browser = webdriver.Chrome(options=options, executable_path=r"./chromedriver")
browser.get("http://google.com")
</code>```

I'm using Chrome version 74.0.3729.169 and chromedriver version ChromeDriver 74.0.3729.6 (which is the compatible version).

When Chrome opens I don't see any cookies in Chrome's settings so it's clear it's NOT being pointed to my default session. Also, I see that a Selenium directory has been created (which appears to mean that it has failed to connect to the session at ~/Library/Caches/Google/Chrome/Default.

How do I hook up selenium to my default Chrome session? This is the same session as one sees when normally opening up Chrome.

I've looked at this other question, but the answer there fails to address how to point Selenium towards default session. Also - it's an outdated question - Chrome and Chromedriver have progressed a lot since then. Also, the question there assumes that the poster is able to connect to default session - I am not able to do that which suggests that the Chromedriver/Chrome have changed since then. Also that question is for Windows - I'm on a Mac where things work differently.

答:
Make sure you are pointing to the right folder using "Chrome://version".

I am using the windows but it should be similar in you mac case too.

Refer to this link for more information.

How to create a custom profile:

You can create your own custom profile by just running Chrome (on the command-line or through ChromeDriver) with the user-data-dir switch set to some new directory. If the path doesn't exist, Chrome will create a new profile in the specified location. You can then modify the profile settings as desired, and ChromeDriver can use the profile in the future. Open chrome://version in the browser to see what profile Chrome is using.

Reference:

http://chromedriver.chromium.org/capabilities

Body:
Though I realize it's NOT "good" practice - I have a use case where I need to point (hook up) the Selenium driver to my default Chrome session/profile.

My default profile is here:
~/Library/Caches/Google/Chrome/Default

Here is how I'm seting it up currently: (not working)

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument("--user-data-dir=~/Library/Caches/Google/Chrome")
options.add_argument("--profile-directory=Default")
browser = webdriver.Chrome(options=options, executable_path=r"./chromedriver")
browser.get("http://google.com")

I'm using Chrome version 74.0.3729.169 and chromedriver version ChromeDriver 74.0.3729.6 (which is the compatible version).

When Chrome opens I don't see any cookies in Chrome's settings so it's clear it's NOT being pointed to my default session. Also, I see that a Selenium directory has been created (which appears to mean that it has failed to connect to the session at ~/Library/Caches/Google/Chrome/Default.

How do I hook up selenium to my default Chrome session? This is the same session as one sees when normally opening up Chrome.

I've looked at this other question, but the answer there fails to address how to point Selenium towards default session. Also - it's an outdated question - Chrome and Chromedriver have progressed a lot since then. Also, the question there assumes that the poster is able to connect to default session - I am not able to do that which suggests that the Chromedriver/Chrome have changed since then. Also that question is for Windows - I'm on a Mac where things work differently.


问:
R filter matrix using dplyr
I'm trying to to filter a matrix using filter() from dplyr package.

```<code>mtcars_matrix = as.matrix(mtcars)
mtcars_matrix %>% dplyr::filter(hp>100) # threw an error
</code>```

Below code worked, I wish to not juggle between a matrix and a data.frame

```<code>mtcars_matrix %>% as.data.frame %>% dplyr::filter(hp>100) %>% as.matrix()
</code>```

Is there any way I can use dplyr to filter matrices?

Title: R filter matrix using dplyr

Body:
I'm trying to to filter a matrix using filter() from dplyr package.

mtcars_matrix = as.matrix(mtcars)
mtcars_matrix %>% dplyr::filter(hp>100) # threw an error

Below code worked, I wish to not juggle between a matrix and a data.frame

mtcars_matrix %>% as.data.frame %>% dplyr::filter(hp>100) %>% as.matrix()

Is there any way I can use dplyr to filter matrices?

Body:
Unfortunately dplyr::filter only works for data.frame and tibble, as commented by @akrun. One possible solution is to use the subset fuction.

df <- mtcars_matrix %>%
  base::subset(mtcars_matrix[,"hp"] > 100)
df

> df
                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant             18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360          14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 280            19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
Merc 280C           17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
Merc 450SE          16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3
Merc 450SL          17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3
Merc 450SLC         15.2   8 275.8 180 3.07 3.780 18.00  0  0    3    3
Cadillac Fleetwood  10.4   8 472.0 205 2.93 5.250 17.98  0  0    3    4
Lincoln Continental 10.4   8 460.0 215 3.00 5.424 17.82  0  0    3    4
Chrysler Imperial   14.7   8 440.0 230 3.23 5.345 17.42  0  0    3    4
Dodge Challenger    15.5   8 318.0 150 2.76 3.520 16.87  0  0    3    2
AMC Javelin         15.2   8 304.0 150 3.15 3.435 17.30  0  0    3    2
Camaro Z28          13.3   8 350.0 245 3.73 3.840 15.41  0  0    3    4
Pontiac Firebird    19.2   8 400.0 175 3.08 3.845 17.05  0  0    3    2
Lotus Europa        30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2
Ford Pantera L      15.8   8 351.0 264 4.22 3.170 14.50  0  1    5    4
Ferrari Dino        19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6
Maserati Bora       15.0   8 301.0 335 3.54 3.570 14.60  0  1    5    8
Volvo 142E          21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2


问:
How does react trigger componentDidMount with safari cache?
React 16 triggers componentDidMount() when going back in Safari, even tho the component never unmounted. How does react know when to mount?

```<code>class Foo extends React.Component {
  state = {
    loading: false
  }

  componentDidMount() {
    // when going back in safari
    // triggers in react 16, but not in 15.3 or preact
    console.log('mounted');
  }

  componentWillUnmount() {
    // will never trigger
    console.log('will unmount');
  }

  leave() {
    this.setState({
      loading: true
    });
    setTimeout(() => {
      window.location.href = 'https://github.com/';
    }, 2000);
  }

  render() {
    return this.state.loading ? <div>loading...</div> : <button onClick={this.leave.bind(this)}>leave</button>;
  }
}
</code>```

Background

Safari uses bfcache. If you go back it takes the last page from cache.

When using react 15.3 or libraries such as preact, leaving the page will not trigger componentWillUnmount and going back will not trigger componentDidMount.

This behaviour causes several issues - for example when you set your page state to loading before redirecting. If the user goes back, the state is still set to loading and you cannot even reset the state using componentDidMount, because it never triggers.

There is a solution, by using onpageshow, but since it only triggers one time, you have to reload the whole page using window.location.reload(). This is also the reason react cannot rely on this solution.

答:
I do not know exactly how React 16 is calling the mount, but it is a completely different engine, so It may be on purpose or not.
One thing you can do to work around the issue is to schedule a state reset just before redirecting, like this:

```

and then when you go back the execution resumes and it is possible to detect if its coming from history and reset the state.

you could actually setup this reset mechanism right on componentDidMount, the first time.

Body:
React 16 triggers componentDidMount() when going back in Safari, even tho the component never unmounted. How does react know when to mount?

class Foo extends React.Component {
  state = {
    loading: false
  }

  componentDidMount() {
    // when going back in safari
    // triggers in react 16, but not in 15.3 or preact
    console.log('mounted');
  }

  componentWillUnmount() {
    // will never trigger
    console.log('will unmount');
  }

  leave() {
    this.setState({
      loading: true
    });
    setTimeout(() => {
      window.location.href = 'https://github.com/';
    }, 2000);
  }

  render() {
    return this.state.loading ?
loading...
 : <button onClick={this.leave.bind(this)}>leave</button>;
  }
}

Background

Safari uses bfcache. If you go back it takes the last page from cache.

When using react 15.3 or libraries such as preact, leaving the page will not trigger componentWillUnmount and going back will not trigger componentDidMount.

This behaviour causes several issues - for example when you set your page state to loading before redirecting. If the user goes back, the state is still set to loading and you cannot even reset the state using componentDidMount, because it never triggers.

There is a solution, by using onpageshow, but since it only triggers one time, you have to reload the whole page using window.location.reload(). This is also the reason react cannot rely on this solution.

Body:
I do not know exactly how React 16 is calling the mount, but it is a completely different engine, so It may be on purpose or not.
One thing you can do to work around the issue is to schedule a state reset just before redirecting, like this:

<html>
  <head>
    <script
      crossorigin
      src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"
    ></script>
    <script
      crossorigin
      src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"
    ></script>
    <script src="https://unpkg.com/babel-standalone@6.26.0/babel.min.js"></script>
  </head>
  <body>
    <div id="app"></div>
    <script type="text/babel">
      class Foo extends React.Component {
        state = {
          loading: false
        };
        componentDidMount() {
          console.log("mounted");
        }
        leave() {
          this.setState({
            loading: true
          });
          setTimeout(() => {
            this.setupReset();
            window.location.href = "https://github.com";
          }, 2000);
        }

        setupReset() {
          let interval = setInterval(() => {
            if (
              !!window.performance &&
              window.performance.navigation.type === 2
            ) {
              clearInterval(interval);
              console.log('reseting');
              this.setState({ loading: false });
            }
          },500);
        }

        render() {
          return this.state.loading ? (
            <div>loading...</div>
          ) : (
            <button onClick={this.leave.bind(this)}>leave</button>
          );
        }
      }
      ReactDOM.render(<Foo />, document.getElementById("app"));
    </script>
  </body>
</html>

and then when you go back the execution resumes and it is possible to detect if its coming from history and reset the state.

you could actually setup this reset mechanism right on componentDidMount, the first time.


问:
Cannot access javascript variable inside symfony controller
On my symfony (v3.4) project, I need to pass some javascript variables from my view to my controller containing a form : I used Jquery and Ajax to send my variable to the right route but for some reason I cannot access it from my controller.

Here is the script part in my twig view:

$(".month").click(function() {

  var click = $(this);

  var month = click.val();
  var year = $("#years").val();

  var url = "{{ path('av_platform_saisie') }}";

  $.ajax(url, {
    type: 'POST',
    data: {
      'month': month,
      'year': year
    },
    success: function(data) {
      alert('OK');
    },
    error: function(jqXHR, textStatus, errorThrown) {}
  });

});
```

<p>And my controller: </p>

<pre class="lang-php prettyprint-override"><code>public function saisieAction(Request $request)
{

    $user = $this->getUser();
    $thisyear = date("Y");

    $em = $this->getDoctrine()->getManager();

    // Create the form
    $form = $this->get('form.factory')->createBuilder(FormType::class)
        ->add('ndf', CollectionType::class, array(
            'entry_type' => NoteDeFraisType::class,
            'label' => false,
            'allow_add' => true,
            'allow_delete' => true,
        ))
        ->getForm();

    // if the form has been submited
    if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {

        if($request->isXMLHttpRequest()){

            $month = $request->get('month');
            $year = $request->get('year');
            $sub_date = $month .'/' .$year;

        }

        $notesDeFrais = $form['ndf']->getData();

        foreach ($notesDeFrais as $ndf) {
            $ndf->setUser($user);
            $ndf->setMonth($sub_date);
            $em->persist($ndf);
        }

        $em->flush();

    }

    return $this->render('AvPlatformBundle:Platform:saisie.html.twig',
        array(
            'year' => $thisyear,  'form' => $form->createView()
        ));
}
</code>```

The weird thing is: I tried to send my js variables from a new Twig view that is not rendered by my controller and it's working just fine with exactly the same code so maybe it is a normal behavior ?

EDIT:
I did some debugging and actually and the code inside my if($request->isXMLHttpRequest()) is not executed

答:
Put your url inside the array passed to ajax with, like so:</p>

```<code> $(".month").click(function() {
     var click = $(this);
     var month = click.val();
     var year = $("#years").val();

     $.ajax({
         url: "{{ path('av_platform_saisie') }}",
         type: 'POST',
         data: { 'month': month,
                 'year': year
               },
         success: function (data) {
             alert('OK');
         },
         error : function(jqXHR, textStatus, errorThrown){}
     });
});
</code>```

Body:
On my symfony (v3.4) project, I need to pass some javascript variables from my view to my controller containing a form : I used Jquery and Ajax to send my variable to the right route but for some reason I cannot access it from my controller.

Here is the script part in my twig view:

$(".month").click(function() {

  var click = $(this);

  var month = click.val();
  var year = $("#years").val();

  var url = "{{ path('av_platform_saisie') }}";

  $.ajax(url, {
    type: 'POST',
    data: {
      'month': month,
      'year': year
    },
    success: function(data) {
      alert('OK');
    },
    error: function(jqXHR, textStatus, errorThrown) {}
  });

});

And my controller:

public function saisieAction(Request $request)
{

    $user = $this->getUser();
    $thisyear = date("Y");

    $em = $this->getDoctrine()->getManager();

    // Create the form
    $form = $this->get('form.factory')->createBuilder(FormType::class)
        ->add('ndf', CollectionType::class, array(
            'entry_type' => NoteDeFraisType::class,
            'label' => false,
            'allow_add' => true,
            'allow_delete' => true,
        ))
        ->getForm();

    // if the form has been submited
    if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {

        if($request->isXMLHttpRequest()){

            $month = $request->get('month');
            $year = $request->get('year');
            $sub_date = $month .'/' .$year;

        }

        $notesDeFrais = $form['ndf']->getData();

        foreach ($notesDeFrais as $ndf) {
            $ndf->setUser($user);
            $ndf->setMonth($sub_date);
            $em->persist($ndf);
        }

        $em->flush();

    }

    return $this->render('AvPlatformBundle:Platform:saisie.html.twig',
        array(
            'year' => $thisyear,  'form' => $form->createView()
        ));
}

The weird thing is: I tried to send my js variables from a new Twig view that is not rendered by my controller and it's working just fine with exactly the same code so maybe it is a normal behavior ?

EDIT:
I did some debugging and actually and the code inside my if($request->isXMLHttpRequest()) is not executed

Body:
Put your url inside the array passed to ajax with, like so:

 $(".month").click(function() {
     var click = $(this);
     var month = click.val();
     var year = $("#years").val();

     $.ajax({
         url: "{{ path('av_platform_saisie') }}",
         type: 'POST',
         data: { 'month': month,
                 'year': year
               },
         success: function (data) {
             alert('OK');
         },
         error : function(jqXHR, textStatus, errorThrown){}
     });
});


问:
Not contained in eaggregate function/ the GROUP BY AND max date does not show the latest date
I am stucked here and your help will be appreciated. Based on the code that you see below:
I have a sub query with some conditions. especifically, the following:

```<code>AND OwnedByTeamJ='C - O Review'
AND  OwnedByTeamJ is null
</code>```

I want to get the results from the subquery,
Do another select on them because all I want is the latest date listed the table. As you can see in the picture, I want to be able to extract row#3 which has the highest date and its own by the team which is null (I guess! since there is no value there).
Now the problems:
1-at first the code worked and I saw all the records! though, it didsn't pick the latest date

2- sudennly it stopped working and saw this error:
Column 'tt.IncidentID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

```<code>select
    distinct max(LastModifiedDateTimeJ),
    incidentID,
    EffecRequestStatus,
    OwnedByTeamJ
From (
    select
      EffecRequestStatus,
      IncidentID,
      LastModifiedDateTimeJ,
      OwnedByTeamJ,
      DetailsJ,
      Status,
      OwnedByTeam
    from IncidentView
       where
       CAST(CreatedDateTime as  DATE) >='05-01-2019'
       AND JournalTypeName like '%Journal - Note%'
       AND OwnedByTeamJ='C - O Review'
       AND  OwnedByTeamJ is null

    group by
        EffecRequestStatus,
        IncidentID,
        LastModifiedDateTimeJ,
        OwnedByTeamJ,
        DetailsJ,
        Status,
        OwnedByTeam
) as tt
where
    tt. RequestStatus not in ('Submission','P-C submission','C Review')
</code>```

A sample of data look like the following but my table has more columns than that is listed here:

答:
Try this, if you want to have a not empty result:</p>

```<code>AND (OwnedByTeamJ='C - O Review'
OR  OwnedByTeamJ is null)
</code>```

Body:
I am stucked here and your help will be appreciated. Based on the code that you see below:
I have a sub query with some conditions. especifically, the following:

AND OwnedByTeamJ='C - O Review'
AND  OwnedByTeamJ is null

I want to get the results from the subquery,
Do another select on them because all I want is the latest date listed the table. As you can see in the picture, I want to be able to extract row#3 which has the highest date and its own by the team which is null (I guess! since there is no value there).
Now the problems:
1-at first the code worked and I saw all the records! though, it didsn't pick the latest date

2- sudennly it stopped working and saw this error:
Column 'tt.IncidentID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

select
    distinct max(LastModifiedDateTimeJ),
    incidentID,
    EffecRequestStatus,
    OwnedByTeamJ
From (
    select
      EffecRequestStatus,
      IncidentID,
      LastModifiedDateTimeJ,
      OwnedByTeamJ,
      DetailsJ,
      Status,
      OwnedByTeam
    from IncidentView
       where
       CAST(CreatedDateTime as  DATE) >='05-01-2019'
       AND JournalTypeName like '%Journal - Note%'
       AND OwnedByTeamJ='C - O Review'
       AND  OwnedByTeamJ is null

    group by
        EffecRequestStatus,
        IncidentID,
        LastModifiedDateTimeJ,
        OwnedByTeamJ,
        DetailsJ,
        Status,
        OwnedByTeam
) as tt
where
    tt. RequestStatus not in ('Submission','P-C submission','C Review')

A sample of data look like the following but my table has more columns than that is listed here:

Body:
Try this, if you want to have a not empty result:

AND (OwnedByTeamJ='C - O Review'
OR  OwnedByTeamJ is null)


问:
How/Where to apply business rules to POCO objects?
Let's say I have a POCO with the following:

```<code>    [DataMember]
    public Nullable<int> MetricId
    {
        get { return _metricId; }
        set
        {
            if (_metricId != value)
            {
                _metricId = value;
                OnPropertyChanged("MetricId");
            }
        }
    }
    private Nullable<int> _metricId;
</code>```

I want to validate that the MetricId is strictly greater than 0

Obivously, if I put this rule as a data annotation in this class it will be overwritten the next time I regen the poco.  Where do I put this logic?

Thanks!

答: I seem to remember the suggestion being to utilize partial classes and roll a partial class that implemented the logic you didn't want to be overwritten.</p>

Body:
Let's say I have a POCO with the following:

    [DataMember]
    public Nullable<int> MetricId
    {
        get { return _metricId; }
        set
        {
            if (_metricId != value)
            {
                _metricId = value;
                OnPropertyChanged("MetricId");
            }
        }
    }
    private Nullable<int> _metricId;

I want to validate that the MetricId is strictly greater than 0

Obivously, if I put this rule as a data annotation in this class it will be overwritten the next time I regen the poco.  Where do I put this logic?

Thanks!


问:
React.js - how to pass event handlers to deeply nested component without props drilling?
I have the structure of components (nested) that seems like this:

Container

ComponentA

ComponentB

ComponentC(want to handle event here with state that lives on container)

Do I need to pass as props all the way from Container, ComponentA, ComponentB and finally ComponentC to have this handler? Or is there another way like using Context API?

I'm finding a bit hard to handle events with react.js vs vue.js/angular.js because of this.

答:
Context Api is your data center. You put all the data and click events that your application needs  here and then with "Consumer" method you fetch them in any component regardless of how nested it is. Here is a basic example:

```<code>context.js //in your src folder.

import React, { Component, createContext } from "react";
import { storeProducts } from "./data"; //imported the data from data.js
const ProductContext = createContext(); //created context object
class ProductProvider extends Component {
  state = {
    products: storeProducts,
    };
render() {
    return (
      <ProductContext.Provider
//we pass the data via value prop. anything here is accessible
        value={{
          ...this.state,
          addToCart: this.addToCart //I wont use this in the example because it would
 be very long code, I wanna show you that, we pass data and event handlers here!
        }}
      >
  // allows all the components access the data provided here
        {this.props.children},
      </ProductContext.Provider>
    );
  }
}
const ProductConsumer = ProductContext.Consumer;
export { ProductProvider, ProductConsumer };
</code>```

Now we set up our data center with .Consumer and .Provider methods so we can access
   here via "ProductConsumer" in our components. Let's say you want to display all your products in your home page.
   ProductList.js

```<code>import React, { Component } from "react";
import Product from "./Product";
import { ProductConsumer } from "../context";

class ProductList extends Component {
  render() {
    return (
<React.Fragment>
          <div className="container">
            <div className="row">
              <ProductConsumer>
       //we fetch data here, pass the value as an argument of the function
                {value => {
                  return value.products.map(product => {
                    return <Product key={product.id}  />;
                  });
                }}
              </ProductConsumer>
            </div>
          </div>
      </React.Fragment>
    );
  }
}
export default ProductList;
</code>```

This is the logic behind the Context Api. It sounds scary but if you know the logic it is very simple. Instead of creating your data and events handlers inside of each component and prop drilling which is a big headache, just put data and your event handlers here and orchestrate them.

I hope it helps.

Body:
Context Api is your data center. You put all the data and click events that your application needs  here and then with "Consumer" method you fetch them in any component regardless of how nested it is. Here is a basic example:

context.js //in your src folder.

import React, { Component, createContext } from "react";
import { storeProducts } from "./data"; //imported the data from data.js
const ProductContext = createContext(); //created context object
class ProductProvider extends Component {
  state = {
    products: storeProducts,
    };
render() {
    return (
      <ProductContext.Provider
//we pass the data via value prop. anything here is accessible
        value={{
          ...this.state,
          addToCart: this.addToCart //I wont use this in the example because it would
 be very long code, I wanna show you that, we pass data and event handlers here!
        }}
      >
  // allows all the components access the data provided here
        {this.props.children},
      </ProductContext.Provider>
    );
  }
}
const ProductConsumer = ProductContext.Consumer;
export { ProductProvider, ProductConsumer };

Now we set up our data center with .Consumer and .Provider methods so we can access
   here via "ProductConsumer" in our components. Let's say you want to display all your products in your home page.
   ProductList.js

import React, { Component } from "react";
import Product from "./Product";
import { ProductConsumer } from "../context";

class ProductList extends Component {
  render() {
    return (
<React.Fragment>
          <div className="container">
            <div className="row">
              <ProductConsumer>
       //we fetch data here, pass the value as an argument of the function
                {value => {
                  return value.products.map(product => {
                    return <Product key={product.id}  />;
                  });
                }}
              </ProductConsumer>
            </div>
          </div>
      </React.Fragment>
    );
  }
}
export default ProductList;

This is the logic behind the Context Api. It sounds scary but if you know the logic it is very simple. Instead of creating your data and events handlers inside of each component and prop drilling which is a big headache, just put data and your event handlers here and orchestrate them.

I hope it helps.


问:
Starting TypeScript program from Visual Studio Code: "Cannot launch program 'hw.ts' because corresponding JavaScript cannot be found."
I have hw.ts file with this content:

```<code>function greeter(x: string) {
    return "Hello" + x;
}

let u = "John";
document.body.innerHTML = greeter(u);
</code>```

I select Start without debugging and VSCode says:

```<code>Cannot launch program 'hw.ts' because corresponding JavaScript cannot be found.
</code>```

OK so I compile file from the commandline:

```<code>tsc hw.ts
</code>```

Now I do have hw.js in the same folder.

So again I select Start without debugging and VSCode again says Cannot launch program 'hw.ts' because corresponding JavaScript cannot be found..

Is there any way to compile & run TypeScript program from VSCode? What am I missing?

(I do have node in my PATH, it should be visible to VSCode)

答:
In your launch.json file replace

"outFiles": ["${workspaceFolder}/**/*.js"]

for

"outFiles": ["${fileDirname}/**/*.js"]

It worked for me.

Body:
I have hw.ts file with this content:

function greeter(x: string) {
    return "Hello" + x;
}

let u = "John";
document.body.innerHTML = greeter(u);

I select Start without debugging and VSCode says:

Cannot launch program 'hw.ts' because corresponding JavaScript cannot be found.

OK so I compile file from the commandline:

tsc hw.ts

Now I do have hw.js in the same folder.

So again I select Start without debugging and VSCode again says Cannot launch program 'hw.ts' because corresponding JavaScript cannot be found..

Is there any way to compile & run TypeScript program from VSCode? What am I missing?

(I do have node in my PATH, it should be visible to VSCode)


问:
AWS Lambda (in python) waiting for asynchronous event
I've got an AWS Lambda, written in python and behind API Gateway, which makes a network request out to a third party.

Shortly after that request, a separate request will be made by the third party to the URL of my choosing - I need to get a hold of the body of that request and return it in the response from my Lambda.

If perhaps I have the third party send to a second Lambda, how can I hold the first Lambda open, waiting for an event from the second Lambda?

答:
(In the hope that someone offers a better idea...)

What I'm currently intending to do is stand up a redis (Elasticache) cluster. Lambda A will send out a request with an X-Request-ID and then setup a redis pubsub().subscribe(X-Request-ID). Lambda B will receive the response and do a redis pubsub().publish(X-Request-ID, response). Lambda A will then return the response or, if not received in time, timeout.

Inelegant but I think it works.


问:
Using XMPP with iPhone SDK?
I am looking for an ebook or online tutorial for building a chat application iphone sdk / XMPP server. I am currently using the xmppframework.

Any guide or any help would be appreciated.

答: The xmppframework has a tutorial for iPhone: https://github.com/robbiehanson/XMPPFramework/wiki/GettingStarted_iOS</p>

Title: Using XMPP with iPhone SDK?


问:
Join list of sentences up to max character limit
I have a list in which each item is a sentence. I want to join the items as long as the new combined item does not go over a character limit.

You can join items in a list fairly easily.

x = ['Alice went to the market.', 'She bought an apple.', 'And she then went to the park.']
' '.join(x)
>>> 'Alice went to the market. She bought an apple. And she then went to the park.'
```

Now say I would like to sequentially join the items as long as the new combined item is not greater than 50 characters.

The result would be :

['Alice went to the market. She bought an apple.','And she then went to the park.']

You can maybe do a list comprehension like here.  Or I can maybe do a conditional iterator like here.   But I run into problems where the sentences get cut off.

Clarifications

The max character limit refers to the length of a single item in the list...not the length of the entire list. When the list items are combined, no single item in the new list can be over the limit.

The items that were not able to be combined are returned in the list as they were unchanged.

Combine sentences together as long as they do not exceed limit.  If they exceed limit, do not combine and keep as is. Only combine sentences that are sequentially next to each other in the list.

Please make sure your solution satisfies the output result as indicated previously above :
['Alice went to the market. She bought an apple.','And she then went to the park.']

答:
You can use accumulate from itertools to compute the size of the accumulated strings (+separators) and determine the maximum number of items that can be combined.

After than you can decide to combine them and you will also know what items could not fit.

```<code>s = ['Alice went to the market.', 'She bought an apple.', 'And she then went to the park.']

from itertools import accumulate
maxCount = sum( size+sep<=50 for sep,size in enumerate(accumulate(map(len,s))) )
combined = " ".join(s[:maxCount])
unused   = s[maxCount:]

print(combined,unused)
# Alice went to the market. She bought an apple. ['And she then went to the park.']
</code>```

You could also obtain maxCount in a more brutal (and inefficient) way, without using accumulate:

```<code>maxCount = sum(len(" ".join(s[:n+1]))<=50 for n in range(len(s)))
</code>```

Or you could do the whole thing in one line:

```<code>items = next(s[:n] for n in range(len(s),0,-1) if len(" ".join(s[:n]))<=50 )

# ['Alice went to the market.', 'She bought an apple.']

unused = s[len(items):]

# ['And she then went to the park.']
</code>```

If you need to perform multiple combinations from the list to produce a new list of combined sentences (as per your latest edit to the question), you can use this in a loop:

```<code>combined = []
s        = ['Alice went to the market.', 'She bought an apple.', 'And she then went to the park.']
while s:
    items = next((s[:n] for n in range(len(s),0,-1) if len(" ".join(s[:n]))<=50), s[:1])
    combined.append(" ".join(items))
    s = s[len(items):]

print(combined)
# ['Alice went to the market. She bought an apple.', 'And she then went to the park.']
</code>```

EDIT Changed call to the next() function to add a default. This will handle sentences that are already longer than 50 characters.

Body:
I have a list in which each item is a sentence. I want to join the items as long as the new combined item does not go over a character limit.

You can join items in a list fairly easily.

x = ['Alice went to the market.', 'She bought an apple.', 'And she then went to the park.']
' '.join(x)
>>> 'Alice went to the market. She bought an apple. And she then went to the park.'

Now say I would like to sequentially join the items as long as the new combined item is not greater than 50 characters.

The result would be :

['Alice went to the market. She bought an apple.','And she then went to the park.']

You can maybe do a list comprehension like here.  Or I can maybe do a conditional iterator like here.   But I run into problems where the sentences get cut off.

Clarifications

The max character limit refers to the length of a single item in the list...not the length of the entire list. When the list items are combined, no single item in the new list can be over the limit.

The items that were not able to be combined are returned in the list as they were unchanged.

Combine sentences together as long as they do not exceed limit.  If they exceed limit, do not combine and keep as is. Only combine sentences that are sequentially next to each other in the list.

Please make sure your solution satisfies the output result as indicated previously above :
['Alice went to the market. She bought an apple.','And she then went to the park.']

Body:
You can use accumulate from itertools to compute the size of the accumulated strings (+separators) and determine the maximum number of items that can be combined.

After than you can decide to combine them and you will also know what items could not fit.

s = ['Alice went to the market.', 'She bought an apple.', 'And she then went to the park.']

from itertools import accumulate
maxCount = sum( size+sep<=50 for sep,size in enumerate(accumulate(map(len,s))) )
combined = " ".join(s[:maxCount])
unused   = s[maxCount:]

print(combined,unused)
# Alice went to the market. She bought an apple. ['And she then went to the park.']

You could also obtain maxCount in a more brutal (and inefficient) way, without using accumulate:

maxCount = sum(len(" ".join(s[:n+1]))<=50 for n in range(len(s)))

Or you could do the whole thing in one line:

items = next(s[:n] for n in range(len(s),0,-1) if len(" ".join(s[:n]))<=50 )

# ['Alice went to the market.', 'She bought an apple.']

unused = s[len(items):]

# ['And she then went to the park.']

If you need to perform multiple combinations from the list to produce a new list of combined sentences (as per your latest edit to the question), you can use this in a loop:

combined = []
s        = ['Alice went to the market.', 'She bought an apple.', 'And she then went to the park.']
while s:
    items = next((s[:n] for n in range(len(s),0,-1) if len(" ".join(s[:n]))<=50), s[:1])
    combined.append(" ".join(items))
    s = s[len(items):]

print(combined)
# ['Alice went to the market. She bought an apple.', 'And she then went to the park.']

EDIT Changed call to the next() function to add a default. This will handle sentences that are already longer than 50 characters.


问:
External command s3-dist-cp execution in spark-scala through scala.sys.process API
when I run all these 3 commands in unix shell/terminal, they all work fine, returning the exit status as 0

```<code>unix_shell> ls -la
unix_shell> hadoop fs -ls /user/hadoop/temp
unix_shell> s3-dist-cp --src ./abc.txt --dest s3://bucket/folder/
</code>```

now I am trying to run these same commands through scala process api as an external process, the sample code is like below:

```<code>import scala.sys.process._

val cmd_1 = "ls -la"
val cmd_2 = "hadoop fs -ls /user/hadoop/temp/"
val cmd_3 = "/usr/bin/s3-dist-cp --src /tmp/sample.txt --dest s3://bucket/folder/"
val cmd_4 = "s3-dist-cp --src /tmp/sample.txt --dest s3://bucket/folder/"

val exitCode_1 = (stringToProcess(cmd_1)).! // works fine and produces result
val exitCode_2 = (stringToProcess(cmd_2)).! // works fine and produces result
val exitCode_3 = (stringToProcess(cmd_3)).! // **it just hangs, yielding nothing**
val exitCode_4 = (stringToProcess(cmd_4)).! // **it just hangs, yielding nothing**
</code>```

The difference between above cmd_3 and cmd_4 is just the absolute path.
And I am passing the relevant dependency explicitly in spark-submit script like below

```<code>--jars hdfs:///user/hadoop/s3-dist-cp.jar
</code>```

Your inputs/suggestion would be helpful. Thanks !

答:
Seems like what you have done is right.see here
https://github.com/gorros/spark-scala-tips/blob/master/README.md

```<code>import scala.sys.process._

def s3distCp(src: String, dest: String): Unit = {
    s"s3-dist-cp --src $src --dest $dest".!
}
</code>```

Please check this note... I wonder whether this is the case with you.

regarding your --jars /usr/lib/hadoop/client/*.jar

you can append jars related to s3-dist-cp using tr command like this. see my answer

```<code>--jars $(echo /dir_of_jars/*.jar | tr ' ' ',')
</code>```

Note: To be able to use this method, you need Hadoop application to be added and you need to run Spark in client or local mode since s3-dist-cp is not available on slave nodes. If you want to run in cluster mode, then copy s3-dist-cp command to slaves during bootstrap.

Body:
when I run all these 3 commands in unix shell/terminal, they all work fine, returning the exit status as 0

unix_shell> ls -la
unix_shell> hadoop fs -ls /user/hadoop/temp
unix_shell> s3-dist-cp --src ./abc.txt --dest s3://bucket/folder/

now I am trying to run these same commands through scala process api as an external process, the sample code is like below:

import scala.sys.process._

val cmd_1 = "ls -la"
val cmd_2 = "hadoop fs -ls /user/hadoop/temp/"
val cmd_3 = "/usr/bin/s3-dist-cp --src /tmp/sample.txt --dest s3://bucket/folder/"
val cmd_4 = "s3-dist-cp --src /tmp/sample.txt --dest s3://bucket/folder/"

val exitCode_1 = (stringToProcess(cmd_1)).! // works fine and produces result
val exitCode_2 = (stringToProcess(cmd_2)).! // works fine and produces result
val exitCode_3 = (stringToProcess(cmd_3)).! // **it just hangs, yielding nothing**
val exitCode_4 = (stringToProcess(cmd_4)).! // **it just hangs, yielding nothing**

The difference between above cmd_3 and cmd_4 is just the absolute path.
And I am passing the relevant dependency explicitly in spark-submit script like below

--jars hdfs:///user/hadoop/s3-dist-cp.jar

Your inputs/suggestion would be helpful. Thanks !

Body:
Seems like what you have done is right.see here
https://github.com/gorros/spark-scala-tips/blob/master/README.md

import scala.sys.process._

def s3distCp(src: String, dest: String): Unit = {
    s"s3-dist-cp --src $src --dest $dest".!
}

Please check this note... I wonder whether this is the case with you.

regarding your --jars /usr/lib/hadoop/client/*.jar

you can append jars related to s3-dist-cp using tr command like this. see my answer

--jars $(echo /dir_of_jars/*.jar | tr ' ' ',')

Note: To be able to use this method, you need Hadoop application to be added and you need to run Spark in client or local mode since s3-dist-cp is not available on slave nodes. If you want to run in cluster mode, then copy s3-dist-cp command to slaves during bootstrap.


问:
dataset validation policy minimumSizeMB for Azure Blob
If I set minimumSizeMB policy for an external dataset of type AzureBlob, does it mean that ADF is going to check total file size in FolderPath (I could have hundreds of files in a given FolderPath with varying size) or it is going to consider only those files in the FolderPath as input which qualify minimumSizeMB?</p>

答: I confirmed through an experiment that it's the total size of all the files</p>


问:
How big of a number will fit in this ASP code?
```<code>'   Now get a Location_ID
'
    Set RS = DB.Execute (AF.SQL("GenerateLocationID"))
    Location_ID = CInt (RS(0).Value)
    RS.Close
</code>```

This is being written to an Oracle database defined with Number(10), but is returning the following error:

Microsoft VBScript runtime error '800a0006'

Overflow: 'CInt'

I'm suspicious, because the largest value in the Oracle table now is 32767.  Is it a limit in the code that is creating the ID?

(The AF.SQL("GenerateLocationID") is 'Select Location_ID.NextVal from Dual', so it's just a standard Oracle select statement.

答:
This should answer your question:

The CInt function converts an
  expression to type Integer. Note: The
  value must be a number between -32768
  and 32767.

Based on the code it appears that Location_ID would have to be a short.

http://www.w3schools.com/VBScript/func_cint.asp

Body:
'   Now get a Location_ID
'
    Set RS = DB.Execute (AF.SQL("GenerateLocationID"))
    Location_ID = CInt (RS(0).Value)
    RS.Close

This is being written to an Oracle database defined with Number(10), but is returning the following error:

Microsoft VBScript runtime error '800a0006'

Overflow: 'CInt'

I'm suspicious, because the largest value in the Oracle table now is 32767.  Is it a limit in the code that is creating the ID?

(The AF.SQL("GenerateLocationID") is 'Select Location_ID.NextVal from Dual', so it's just a standard Oracle select statement.


答:
1) These conditions should not coexist:

```<code>AND OwnedByTeamJ='C - O Review'
AND  OwnedByTeamJ is null
</code>```

...because these two things are never true at the same time, and you will get an empty result-set. I guess what you want is
AND (OwnedByTeamJ='C - O Review' or OwnedByTeamJ is null)

2) The error you mention does not seem to agree with the query you've shown us. Did you try to make another group by externally?

3) It doesn't make sense to use distinct together with any aggregation function like max,sum, count etc.

4) As long as you have included EffecRequestStatus within the group by, you will get 3 rows, not 1, because all 3 rows have a different value for EffecRequestStatus. You will have to remove it from the group by, and therefore from the select as well, if you only want to see one row.

Title: Not contained in eaggregate function/ the GROUP BY AND max date does not show the latest date

Body:
1) These conditions should not coexist:

AND OwnedByTeamJ='C - O Review'
AND  OwnedByTeamJ is null

...because these two things are never true at the same time, and you will get an empty result-set. I guess what you want is
AND (OwnedByTeamJ='C - O Review' or OwnedByTeamJ is null)

2) The error you mention does not seem to agree with the query you've shown us. Did you try to make another group by externally?

3) It doesn't make sense to use distinct together with any aggregation function like max,sum, count etc.

4) As long as you have included EffecRequestStatus within the group by, you will get 3 rows, not 1, because all 3 rows have a different value for EffecRequestStatus. You will have to remove it from the group by, and therefore from the select as well, if you only want to see one row.


问:
How to generate a range of numbers between two numbers?
I have two numbers as input from the user, like for example  1000 and 1050.

How do I generate the numbers between these two numbers, using a sql query, in seperate rows? I want this:

```<code> 1000
 1001
 1002
 1003
 .
 .
 1050
</code>```

答:
The solution I've developed and used for quite some time now (riding some on the shared works of others) is slightly similar to at least one posted.  It doesn't reference any tables and returns an unsorted range of up to 1048576 values (2^20) and can include negatives if desired. You can of course sort the result if necessary. It runs pretty quickly, especially on smaller ranges.</p>

```<code>Select value from dbo.intRange(-500, 1500) order by value  -- returns 2001 values

create function dbo.intRange
(
    @Starting as int,
    @Ending as int
)
returns table
as
return (
    select value
    from (
        select @Starting +
            ( bit00.v | bit01.v | bit02.v | bit03.v
            | bit04.v | bit05.v | bit06.v | bit07.v
            | bit08.v | bit09.v | bit10.v | bit11.v
            | bit12.v | bit13.v | bit14.v | bit15.v
            | bit16.v | bit17.v | bit18.v | bit19.v
            ) as value
        from       (select 0 as v union ALL select 0x00001 as v) as bit00
        cross join (select 0 as v union ALL select 0x00002 as v) as bit01
        cross join (select 0 as v union ALL select 0x00004 as v) as bit02
        cross join (select 0 as v union ALL select 0x00008 as v) as bit03
        cross join (select 0 as v union ALL select 0x00010 as v) as bit04
        cross join (select 0 as v union ALL select 0x00020 as v) as bit05
        cross join (select 0 as v union ALL select 0x00040 as v) as bit06
        cross join (select 0 as v union ALL select 0x00080 as v) as bit07
        cross join (select 0 as v union ALL select 0x00100 as v) as bit08
        cross join (select 0 as v union ALL select 0x00200 as v) as bit09
        cross join (select 0 as v union ALL select 0x00400 as v) as bit10
        cross join (select 0 as v union ALL select 0x00800 as v) as bit11
        cross join (select 0 as v union ALL select 0x01000 as v) as bit12
        cross join (select 0 as v union ALL select 0x02000 as v) as bit13
        cross join (select 0 as v union ALL select 0x04000 as v) as bit14
        cross join (select 0 as v union ALL select 0x08000 as v) as bit15
        cross join (select 0 as v union ALL select 0x10000 as v) as bit16
        cross join (select 0 as v union ALL select 0x20000 as v) as bit17
        cross join (select 0 as v union ALL select 0x40000 as v) as bit18
        cross join (select 0 as v union ALL select 0x80000 as v) as bit19
    ) intList
    where @Ending - @Starting < 0x100000
        and intList.value between @Starting and @Ending
)
</code>```

Body:
I have two numbers as input from the user, like for example  1000 and 1050.

How do I generate the numbers between these two numbers, using a sql query, in seperate rows? I want this:

 1000
 1001
 1002
 1003
 .
 .
 1050

Body:
The solution I've developed and used for quite some time now (riding some on the shared works of others) is slightly similar to at least one posted.  It doesn't reference any tables and returns an unsorted range of up to 1048576 values (2^20) and can include negatives if desired. You can of course sort the result if necessary. It runs pretty quickly, especially on smaller ranges.

Select value from dbo.intRange(-500, 1500) order by value  -- returns 2001 values

create function dbo.intRange
(
    @Starting as int,
    @Ending as int
)
returns table
as
return (
    select value
    from (
        select @Starting +
            ( bit00.v | bit01.v | bit02.v | bit03.v
            | bit04.v | bit05.v | bit06.v | bit07.v
            | bit08.v | bit09.v | bit10.v | bit11.v
            | bit12.v | bit13.v | bit14.v | bit15.v
            | bit16.v | bit17.v | bit18.v | bit19.v
            ) as value
        from       (select 0 as v union ALL select 0x00001 as v) as bit00
        cross join (select 0 as v union ALL select 0x00002 as v) as bit01
        cross join (select 0 as v union ALL select 0x00004 as v) as bit02
        cross join (select 0 as v union ALL select 0x00008 as v) as bit03
        cross join (select 0 as v union ALL select 0x00010 as v) as bit04
        cross join (select 0 as v union ALL select 0x00020 as v) as bit05
        cross join (select 0 as v union ALL select 0x00040 as v) as bit06
        cross join (select 0 as v union ALL select 0x00080 as v) as bit07
        cross join (select 0 as v union ALL select 0x00100 as v) as bit08
        cross join (select 0 as v union ALL select 0x00200 as v) as bit09
        cross join (select 0 as v union ALL select 0x00400 as v) as bit10
        cross join (select 0 as v union ALL select 0x00800 as v) as bit11
        cross join (select 0 as v union ALL select 0x01000 as v) as bit12
        cross join (select 0 as v union ALL select 0x02000 as v) as bit13
        cross join (select 0 as v union ALL select 0x04000 as v) as bit14
        cross join (select 0 as v union ALL select 0x08000 as v) as bit15
        cross join (select 0 as v union ALL select 0x10000 as v) as bit16
        cross join (select 0 as v union ALL select 0x20000 as v) as bit17
        cross join (select 0 as v union ALL select 0x40000 as v) as bit18
        cross join (select 0 as v union ALL select 0x80000 as v) as bit19
    ) intList
    where @Ending - @Starting < 0x100000
        and intList.value between @Starting and @Ending
)


问:
Is it normal that one git repository can trigger multiple code pipeline?
Is it normal that one git repository can trigger multiple code pipeline?
Or should git repository and codepipeline be 1-1 mapping?</p>

答:
It is a quiet common scenario that one repo triggers multiple pipelines. Some use cases (non-exhaustive enumeration):

Different pipelines for master branch und feature branches

Depending on directory where files are committed different builds may be triggered (eg only build and create and publish a library)

Special case: empty pipeline. For instance if only in a directory with documentation something was changed.

Special build for Quality assurance which aso triggers integration tests, includes static code analysis, or whatever you may think of.


问:
what is the issue with encryption in c++ and decryption in php
Here, I have c++ program which encodes the string and I have to decrypt in php. I have verified that the key and the iv are same in both programs, still getting false in openssl_decrypt() command.

```<code>    int main(int argc, char** args)
    {
        unsigned char *salt = (unsigned char*)"12345678";
        unsigned char *data = (unsigned char*)"123456789123450";
        unsigned int count        = 5;
        int dlen                  = strlen((char*)data);
        unsigned int ksize        = 16;
        unsigned int vsize        = 12;
        unsigned char *key        = new unsigned char[ksize];
        unsigned char *iv         = new unsigned char[vsize];

        int ret = EVP_BytesToKey( EVP_aes_128_gcm() , EVP_sha1(), salt, data, dlen, count, key, iv);

        const EVP_CIPHER*     m_cipher = EVP_aes_128_gcm();
        EVP_CIPHER_CTX* m_encode;
        EVP_CIPHER_CTX* m_decode;
        if (!(m_encode = EVP_CIPHER_CTX_new()))
           cout << "ERROR :: In encode Initiallization"<< endl;

        EVP_EncryptInit_ex(m_encode, m_cipher, NULL, key, iv);

        if (!(m_decode = EVP_CIPHER_CTX_new()))
            cout << "ERROR :: In decode Initiallization"<< endl;
        EVP_DecryptInit_ex(m_decode, m_cipher, NULL, key, iv);
        unsigned char* plain = (unsigned char*)"My Name IS  DON !!!";
        int len  = strlen((char*)plain);
        unsigned char* encData = new unsigned char[len];

        int c_len = len;
        int f_len = 0;
        EVP_EncryptInit_ex(m_encode, NULL, NULL, NULL, NULL);
        EVP_EncryptUpdate(m_encode, encData, &c_len, plain, len);
        EVP_EncryptFinal_ex(m_encode, encData + c_len, &f_len);

        len = c_len + f_len;

        cout << string( encData, encData + len)<< endl;
    }
</code>```

And the following is decryption code in php. "./abc_enc.txt" contains encryption string of c++ code. As I mentioned above I am getting same key and iv for both programs but openssl_decrypt function returns false. Can someone figure out what is the mistake?

```<code>    <?
    function EVP_BytesToKey($salt, $password) {
        $ivlen = 12;
        $keylen = 16;
        $iterations = 5;
        $hash = "";
        $hdata = "";
        while(strlen($hash)<$ivlen+$keylen)
        {
            $hdata .= $password.$salt;
            $md_buf = openssl_digest($hdata, 'sha1');
            for ($i = 1; $i < $iterations; $i++) {
                $md_buf = openssl_digest ( hex2bin($md_buf),'sha1');
            }
            $hdata = hex2bin($md_buf);
            $hash.= $hdata;
         }
         return $hash;
    }
    function decrypt($ivHashCiphertext, $password) {
         $method = "aes-128-gcm";
         $salt = "12345678";
         $iterations = 5;
         $ivlen = openssl_cipher_iv_length($method);
         $ciphertext = $ivHashCiphertext;
         $genKeyData = EVP_BytesToKey($salt, $password);
         $keylen = 16;
         $key = substr($genKeyData,0,$keylen);
         $iv  = substr($genKeyData,$keylen,$ivlen);
         //var_dump($key);
         //var_dump($iv);
         $ret = openssl_decrypt($ciphertext, $method, $key, OPENSSL_RAW_DATA, $iv);
         var_dump($ret);
         return $ret;
    }
    $file = './abc_enc.txt';
    $fileData = (file_get_contents($file));
    $encrypted = $fileData;
    $decrypted = decrypt($encrypted, '123456789123450');
    ?>
</code>```

答:
The GCM-mode provides both, confidentiality and authenticity. To verify authenticity the GCM-mode uses an authentication tag and defines a length between incl. 12 and 16 Byte for the tag. The authentication strength depends on the length of the tag, i.e. the longer the tag, the more secure the proof of authenticity.

However, in the current C++-code the authentication tag is not determined! This means that one of the main functionalities of the GCM-mode, authentication, is not used.

While the decryption in C++ using EVP is independent from the authentication (this means that the decryption is also performed even if the authentication tags differ), the decryption in PHP using openssl_decrypt is only done if the authentication is successful, i.e. in PHP the authentication tag is mandatory for decryption. Therefore, the authentication tag must be determined in the C++-code. For this purpose, the following code must be added after the EVP_EncryptFinal_ex-call:

```<code>unsigned int tsize = 16;
unsigned char *tag = new unsigned char[tsize];
EVP_CIPHER_CTX_ctrl(m_encode, EVP_CTRL_GCM_GET_TAG, tsize, tag);
</code>```

Here a tagsize of 16 Byte is used. In addition, the authentication tag must be used in the PHP-code for decryption. This is done by passing the authentication tag as the 6th parameter of the openssl_decrypt-method:

```<code>$ret = openssl_decrypt($ciphertext, $method, $key, OPENSSL_RAW_DATA, $iv, $tag);
</code>```

Decryption can only be performed if the tag used for decryption matches the tag used for encryption.

For the data in the posted example the C++-code generates the following authentication tag (as hexadecimal string):

```<code>f7c18e8b99587f3063383d68230c0e35
</code>```

Finally, a more detailed explanation for AES-GCM with OpenSSL can be found here for encryption and decryption (including the consideration of the authentication tag).

Body:
Here, I have c++ program which encodes the string and I have to decrypt in php. I have verified that the key and the iv are same in both programs, still getting false in openssl_decrypt() command.

    int main(int argc, char** args)
    {
        unsigned char *salt = (unsigned char*)"12345678";
        unsigned char *data = (unsigned char*)"123456789123450";
        unsigned int count        = 5;
        int dlen                  = strlen((char*)data);
        unsigned int ksize        = 16;
        unsigned int vsize        = 12;
        unsigned char *key        = new unsigned char[ksize];
        unsigned char *iv         = new unsigned char[vsize];

        int ret = EVP_BytesToKey( EVP_aes_128_gcm() , EVP_sha1(), salt, data, dlen, count, key, iv);

        const EVP_CIPHER*     m_cipher = EVP_aes_128_gcm();
        EVP_CIPHER_CTX* m_encode;
        EVP_CIPHER_CTX* m_decode;
        if (!(m_encode = EVP_CIPHER_CTX_new()))
           cout << "ERROR :: In encode Initiallization"<< endl;

        EVP_EncryptInit_ex(m_encode, m_cipher, NULL, key, iv);

        if (!(m_decode = EVP_CIPHER_CTX_new()))
            cout << "ERROR :: In decode Initiallization"<< endl;
        EVP_DecryptInit_ex(m_decode, m_cipher, NULL, key, iv);
        unsigned char* plain = (unsigned char*)"My Name IS  DON !!!";
        int len  = strlen((char*)plain);
        unsigned char* encData = new unsigned char[len];

        int c_len = len;
        int f_len = 0;
        EVP_EncryptInit_ex(m_encode, NULL, NULL, NULL, NULL);
        EVP_EncryptUpdate(m_encode, encData, &c_len, plain, len);
        EVP_EncryptFinal_ex(m_encode, encData + c_len, &f_len);

        len = c_len + f_len;

        cout << string( encData, encData + len)<< endl;
    }

And the following is decryption code in php. "./abc_enc.txt" contains encryption string of c++ code. As I mentioned above I am getting same key and iv for both programs but openssl_decrypt function returns false. Can someone figure out what is the mistake?

    <?
    function EVP_BytesToKey($salt, $password) {
        $ivlen = 12;
        $keylen = 16;
        $iterations = 5;
        $hash = "";
        $hdata = "";
        while(strlen($hash)<$ivlen+$keylen)
        {
            $hdata .= $password.$salt;
            $md_buf = openssl_digest($hdata, 'sha1');
            for ($i = 1; $i < $iterations; $i++) {
                $md_buf = openssl_digest ( hex2bin($md_buf),'sha1');
            }
            $hdata = hex2bin($md_buf);
            $hash.= $hdata;
         }
         return $hash;
    }
    function decrypt($ivHashCiphertext, $password) {
         $method = "aes-128-gcm";
         $salt = "12345678";
         $iterations = 5;
         $ivlen = openssl_cipher_iv_length($method);
         $ciphertext = $ivHashCiphertext;
         $genKeyData = EVP_BytesToKey($salt, $password);
         $keylen = 16;
         $key = substr($genKeyData,0,$keylen);
         $iv  = substr($genKeyData,$keylen,$ivlen);
         //var_dump($key);
         //var_dump($iv);
         $ret = openssl_decrypt($ciphertext, $method, $key, OPENSSL_RAW_DATA, $iv);
         var_dump($ret);
         return $ret;
    }
    $file = './abc_enc.txt';
    $fileData = (file_get_contents($file));
    $encrypted = $fileData;
    $decrypted = decrypt($encrypted, '123456789123450');
    ?>

Body:
The GCM-mode provides both, confidentiality and authenticity. To verify authenticity the GCM-mode uses an authentication tag and defines a length between incl. 12 and 16 Byte for the tag. The authentication strength depends on the length of the tag, i.e. the longer the tag, the more secure the proof of authenticity.

However, in the current C++-code the authentication tag is not determined! This means that one of the main functionalities of the GCM-mode, authentication, is not used.

While the decryption in C++ using EVP is independent from the authentication (this means that the decryption is also performed even if the authentication tags differ), the decryption in PHP using openssl_decrypt is only done if the authentication is successful, i.e. in PHP the authentication tag is mandatory for decryption. Therefore, the authentication tag must be determined in the C++-code. For this purpose, the following code must be added after the EVP_EncryptFinal_ex-call:

unsigned int tsize = 16;
unsigned char *tag = new unsigned char[tsize];
EVP_CIPHER_CTX_ctrl(m_encode, EVP_CTRL_GCM_GET_TAG, tsize, tag);

Here a tagsize of 16 Byte is used. In addition, the authentication tag must be used in the PHP-code for decryption. This is done by passing the authentication tag as the 6th parameter of the openssl_decrypt-method:

$ret = openssl_decrypt($ciphertext, $method, $key, OPENSSL_RAW_DATA, $iv, $tag);

Decryption can only be performed if the tag used for decryption matches the tag used for encryption.

For the data in the posted example the C++-code generates the following authentication tag (as hexadecimal string):

f7c18e8b99587f3063383d68230c0e35

Finally, a more detailed explanation for AES-GCM with OpenSSL can be found here for encryption and decryption (including the consideration of the authentication tag).