问:
sinon stub a method that was executed in then call of promise
```<code>describe("/test" , ()=> {

    // separate class 2
    class2 = {

        // function that i wanna stub
    hi: function () {
        return "hi";
    }
    }

// separate class 1
    class1 = {

        // function that i have stubbed and tested
         method1: function() {
           return new Promise((resolve, reject) => {
               resolve(num);

            })
        }

    }

    // method that i will execute
    var parent= function (){

        class1.method1().then(()=>{

            class2.hi();

        })

    }

    // the test
    it("should stub hi method",()=>{

        var hiTest = sinon.stub(class2, 'hi').resolves(5);
        var method1Test = sinon.stub(class1 , 'method1').resolves(5);

     // this start the execution of the promise with then call
        parent();

        // this works fine and test pass
        expect(method1Test.calledOnce.should.be.true);

        // this doesn't work although i executed the function
        expect(hiTest.calledOnce.should.be.true);

    })

})
</code>```

what i wanna do is test the hi method correctly .. because when i test if the method is executed once or not

although i executed it in the then call of the promise it doesn't show that and it make the calledOnce test fail

答:
The problem here is that you are testing the code as if it is synchronous, when it is not (as you are using Promise).

To be able to test this properly we need to be able to hook onto the promise chain that is started with parentcalling class1.method1.

We can do this by returning the promise that calling class1.method1 returns.

In terms of the test itself, we need to make sure Mocha doesnt end the test while we are waiting for the promises, so we use the done callback parameter to tell Mocha when we think the test is finished.

```<code>describe("/test", ()=> {
  class2 = {
    hi: function () {
      return "hi";
    }
  }

  class1 = {
    method1: function() {
      return new Promise((resolve, reject) => {
        resolve(num);
      })
    }
  }

  var parent = function (){
    return class1.method1().then(()=>{
      class2.hi();
    })
  }

  it("should stub hi method", (done)=> {
    var hiTest = sinon.stub(class2, 'hi').returns(5);
    var method1Test = sinon.stub(class1 , 'method1').resolves(5);

    parent().then(() => {
      expect(method1Test.calledOnce.should.be.true);
      expect(hiTest.calledOnce.should.be.true);
      done();
    });
  })
})
</code>```

Body:
describe("/test" , ()=> {

    // separate class 2
    class2 = {

        // function that i wanna stub
    hi: function () {
        return "hi";
    }
    }

// separate class 1
    class1 = {

        // function that i have stubbed and tested
         method1: function() {
           return new Promise((resolve, reject) => {
               resolve(num);

            })
        }

    }

    // method that i will execute
    var parent= function (){

        class1.method1().then(()=>{

            class2.hi();

        })

    }

    // the test
    it("should stub hi method",()=>{

        var hiTest = sinon.stub(class2, 'hi').resolves(5);
        var method1Test = sinon.stub(class1 , 'method1').resolves(5);

     // this start the execution of the promise with then call
        parent();

        // this works fine and test pass
        expect(method1Test.calledOnce.should.be.true);

        // this doesn't work although i executed the function
        expect(hiTest.calledOnce.should.be.true);

    })

})

what i wanna do is test the hi method correctly .. because when i test if the method is executed once or not

although i executed it in the then call of the promise it doesn't show that and it make the calledOnce test fail

Body:
The problem here is that you are testing the code as if it is synchronous, when it is not (as you are using Promise).

To be able to test this properly we need to be able to hook onto the promise chain that is started with parentcalling class1.method1.

We can do this by returning the promise that calling class1.method1 returns.

In terms of the test itself, we need to make sure Mocha doesnt end the test while we are waiting for the promises, so we use the done callback parameter to tell Mocha when we think the test is finished.

describe("/test", ()=> {
  class2 = {
    hi: function () {
      return "hi";
    }
  }

  class1 = {
    method1: function() {
      return new Promise((resolve, reject) => {
        resolve(num);
      })
    }
  }

  var parent = function (){
    return class1.method1().then(()=>{
      class2.hi();
    })
  }

  it("should stub hi method", (done)=> {
    var hiTest = sinon.stub(class2, 'hi').returns(5);
    var method1Test = sinon.stub(class1 , 'method1').resolves(5);

    parent().then(() => {
      expect(method1Test.calledOnce.should.be.true);
      expect(hiTest.calledOnce.should.be.true);
      done();
    });
  })
})


来源: stackexchange

问:
how to deal with multiple tokens files?
I have a complicated grammar, with multiple pre-processors. Each pre-processor lives in its own package. Each one generates a tokens file. When i use a makefile to cd to the package directory and invoke antlr on the grammar it creates the tokens file in the current working directory and then carries on and process the grammar all is good.

When I use the gradle antlr4 plugin the tokens files gets put into generated-src/...packagedir... All good but antlr then cannot find the generated tokens file. I tried to use the -lib parameter but that only points to a single directory.

This is my project structure

src/..package../preproc1

preproc1.g4

preproc1Tokens.g4

src/..package../preproc2

preproc2.g4

preproc2Tokens.g4

When i run antlr on the g4 files I get
build/generated-src/antlr/main/..package../preproc1/preproc1.tokens

but the antlr process working directory is still
src/..package../preproc2 and so antlr cannot find this generated tokens file.

I tried to tell the antlr plugin to generate the output files in the src directory, as the makefile does. Not the way I would choose to do it but just wanted to keep moving forward. Unfortunately the antlr plugin does a delete on the outputdirectory using GFileUtils.cleanDirectory(outputDirectory); in the execute task. I can alter this to not do the delete if the outputDirectory is the same as the source directory, which would be ok I guess, though clean would never work properly.

I have resorted to doing a build with a makefile to get the tokens files, then copying these tokens files to a single directory and pointing -lib to that directory.

Does anyone have a better solution?

答:
I use Maven instead of Gradle. Whether this is a "better" solution I can't say,
but the ANTLR 4 API Page currently favors Maven over Gradle, as there is not a Gradle plugin link that I can see. Having said that, I would hope that the two are compatible enough that the ANTLR build directories should match.

ANTLR Instructions

When I follow the ANTLR source layout as suggested by their ANTLR 4 Maven plugin instructions, then it worked for me pretty much out of the box.

The ANTLR 4 Maven plugin instructions by default will build .g4 files contained in the project folder:

```<code><project>/src/main/antlr4/
</code>```

whereas you would copy any shared .g4 files which are to be used as an imports into the specific import sub-directory:

```<code><project>/src/main/antlr4/imports/
</code>```

My pom.xml file

The following ANTLR plugin configuration <plugin\> text is set in the <project><build><plugins\> section of my pom.xml file.

```<code>           <plugin>
            <groupId>org.antlr</groupId>
            <artifactId>antlr4-maven-plugin</artifactId>
            <version>4.5.3</version>
            <executions>
              <execution>
                <configuration>
                    <outputDirectory>target/generated-sources/java</outputDirectory>
                    <arguments>
                      <argument>-visitor</argument>
                    </arguments>

                  <libDirectory>src/main/antlr4/imports</libDirectory>

                </configuration>
                <id>antlr</id>
                <goals>
                  <goal>antlr4</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
</code>```

I found that I needed to be explicit with the <libDirectory\> entry, even though I thought that this would be the default setting.

My Project Structure

I'm working with three grammars in my ComojoProj project: Countables, Dater, and Sched. Sched imports the other two.
Each of the grammar files are in a separate sub-folder hanging off of src/main/antlr/, more or less aligning with the packages of the associated java implementations:

```<code>--- /ComojoProj/
    --- pom.xml
    --- .project
    --- ./src/main/antlr/
        --- ./com/wapitia/common/Countables.g4
        --- ./com/wapitia/dates/Dater.g4
        --- ./com/wapitia/sched/Sched.g4
    --- ./src/main/antlr/imports/
        --- Countables.g4
        --- Dater.g4
    --- ./src/main/java/
        --- ./com/wapitia/
            --- ./common/parse/antlr/CountablesProducer.java
            --- ./dates/parse/antlr/DaterProducer.java
            --- ./dates/parse/nodes/
                --- DayOfWeekNode.java ...
            --- ./sched/parse/antlr/SchedProducer.java
            --- ./sched/parse/nodes/
                --- MonthlyNode.java, EndDateNode.java, ...
</code>```

The Sched.g4 grammar file starts like this:

```<code>grammar Sched;

import Countables, Dater;

schedule    : dailySched | weeklySched ...
</code>```

The two Countables.g4, Dater.g4 grammar files are found during the Sched.g4 build, because we copied them into the /src/main/antlr/imports/ directory.

When the ANTLR plugin runs it generates the following code

```<code>--- /ComojoProj/target/generated-sources/java/
    --- com.wapitia.common/
        --- CountablesBaseListener.java
        --- CountablesBaseVisitor.java
            ...
    --- com.wapitia.dates/ ...
    --- com.wapitia.sched/ ...
    --- Countables.tokens
    --- CountablesLexer.tokens
        ...
    --- SchedLexer.tokens
</code>```

So the .tokens files are generated into the "top" package of some java
source directory, and so wind up in the top of the generated jar file.

I hope this helps!

ContentLicense: CC BY-SA 3.0

Title: how to deal with multiple tokens files?

Body:
I use Maven instead of Gradle. Whether this is a "better" solution I can't say,
but the ANTLR 4 API Page currently favors Maven over Gradle, as there is not a Gradle plugin link that I can see. Having said that, I would hope that the two are compatible enough that the ANTLR build directories should match.

ANTLR Instructions

When I follow the ANTLR source layout as suggested by their ANTLR 4 Maven plugin instructions, then it worked for me pretty much out of the box.

The ANTLR 4 Maven plugin instructions by default will build .g4 files contained in the project folder:

<project>/src/main/antlr4/

whereas you would copy any shared .g4 files which are to be used as an imports into the specific import sub-directory:

<project>/src/main/antlr4/imports/

My pom.xml file

The following ANTLR plugin configuration <plugin\> text is set in the <project><build><plugins\> section of my pom.xml file.

           <plugin>
            <groupId>org.antlr</groupId>
            <artifactId>antlr4-maven-plugin</artifactId>
            <version>4.5.3</version>
            <executions>
              <execution>
                <configuration>
                    <outputDirectory>target/generated-sources/java</outputDirectory>
                    <arguments>
                      <argument>-visitor</argument>
                    </arguments>

                  <libDirectory>src/main/antlr4/imports</libDirectory>

                </configuration>
                <id>antlr</id>
                <goals>
                  <goal>antlr4</goal>
                </goals>
              </execution>
            </executions>
          </plugin>

I found that I needed to be explicit with the <libDirectory\> entry, even though I thought that this would be the default setting.

My Project Structure

I'm working with three grammars in my ComojoProj project: Countables, Dater, and Sched. Sched imports the other two.
Each of the grammar files are in a separate sub-folder hanging off of src/main/antlr/, more or less aligning with the packages of the associated java implementations:

--- /ComojoProj/
    --- pom.xml
    --- .project
    --- ./src/main/antlr/
        --- ./com/wapitia/common/Countables.g4
        --- ./com/wapitia/dates/Dater.g4
        --- ./com/wapitia/sched/Sched.g4
    --- ./src/main/antlr/imports/
        --- Countables.g4
        --- Dater.g4
    --- ./src/main/java/
        --- ./com/wapitia/
            --- ./common/parse/antlr/CountablesProducer.java
            --- ./dates/parse/antlr/DaterProducer.java
            --- ./dates/parse/nodes/
                --- DayOfWeekNode.java ...
            --- ./sched/parse/antlr/SchedProducer.java
            --- ./sched/parse/nodes/
                --- MonthlyNode.java, EndDateNode.java, ...

The Sched.g4 grammar file starts like this:

grammar Sched;

import Countables, Dater;

schedule    : dailySched | weeklySched ...

The two Countables.g4, Dater.g4 grammar files are found during the Sched.g4 build, because we copied them into the /src/main/antlr/imports/ directory.

When the ANTLR plugin runs it generates the following code

--- /ComojoProj/target/generated-sources/java/
    --- com.wapitia.common/
        --- CountablesBaseListener.java
        --- CountablesBaseVisitor.java
            ...
    --- com.wapitia.dates/ ...
    --- com.wapitia.sched/ ...
    --- Countables.tokens
    --- CountablesLexer.tokens
        ...
    --- SchedLexer.tokens

So the .tokens files are generated into the "top" package of some java
source directory, and so wind up in the top of the generated jar file.

I hope this helps!


问:
Logging into website programmatically with C# and WebRequest class
I'm trying to login to a website using C# and the WebRequest class. This is the code I wrote up last night to send POST data to a web page:

```<code>public string login(string URL, string postData)
{
    Stream webpageStream;
    WebResponse webpageResponse;
    StreamReader webpageReader;
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);

    _webRequest = WebRequest.Create(URL);
    _webRequest.Method = "POST";
    _webRequest.ContentType = "application/x-www-form-urlencoded";
    _webRequest.ContentLength = byteArray.Length;

    webpageStream = _webRequest.GetRequestStream();
    webpageStream.Write(byteArray, 0, byteArray.Length);

    webpageResponse = _webRequest.GetResponse();

    webpageStream = webpageResponse.GetResponseStream();

    webpageReader = new StreamReader(webpageStream);

    string responseFromServer = webpageReader.ReadToEnd();

    webpageReader.Close();
    webpageStream.Close();
    webpageResponse.Close();

    return responseFromServer;
}
</code>```

and it works fine, but I have no idea how I can modify it to send POST data to a login script and then save a cookie(?) and log in.

I have looked at my network transfers using Firebug on the websites login page and it is sending POST data to a URL that looks like this:

```<code>accountName=myemail%40gmail.com&password=mypassword&persistLogin=on&app=com-sc2
</code>```

As far as I'm aware, to be able to use my account with this website in my C# app I need to save the cookie that the web server sends, and then use it on every request? Is this right? Or can I get away with no cookie at all?

Any help is greatly apprecated, thanks! :)

答:
The login process depends on the concrete web site. If it uses cookies, you need to use them.
I recommend to use Firefox with some http-headers watching plugin to look inside headers how they are sent to your particular web site, and then implement it the same way in C#. I answered very similar question the day before yesterday, including example with cookies. Look here.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to login to a website using C# and the WebRequest class. This is the code I wrote up last night to send POST data to a web page:

public string login(string URL, string postData)
{
    Stream webpageStream;
    WebResponse webpageResponse;
    StreamReader webpageReader;
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);

    _webRequest = WebRequest.Create(URL);
    _webRequest.Method = "POST";
    _webRequest.ContentType = "application/x-www-form-urlencoded";
    _webRequest.ContentLength = byteArray.Length;

    webpageStream = _webRequest.GetRequestStream();
    webpageStream.Write(byteArray, 0, byteArray.Length);

    webpageResponse = _webRequest.GetResponse();

    webpageStream = webpageResponse.GetResponseStream();

    webpageReader = new StreamReader(webpageStream);

    string responseFromServer = webpageReader.ReadToEnd();

    webpageReader.Close();
    webpageStream.Close();
    webpageResponse.Close();

    return responseFromServer;
}

and it works fine, but I have no idea how I can modify it to send POST data to a login script and then save a cookie(?) and log in.

I have looked at my network transfers using Firebug on the websites login page and it is sending POST data to a URL that looks like this:

accountName=myemail%40gmail.com&password=mypassword&persistLogin=on&app=com-sc2

As far as I'm aware, to be able to use my account with this website in my C# app I need to save the cookie that the web server sends, and then use it on every request? Is this right? Or can I get away with no cookie at all?

Any help is greatly apprecated, thanks! :)


问:
Introjs on load
I'm trying to implement an introduction tour for my site and came across Introjs.

All the examples show the tour launching upon button click, but I'm wondering if there's a way to launch the tour once the page loads without a button click.  Additionally, is it possible to have it launch only for the first time visiting?

I'm using angularjs to build my site, but am very much a novice.  Any suggestions are greatly appreciated!

答:
Call introJs().start() on document ready event.

```<code>document.addEventListener("DOMContentLoaded", function() {
  introJs().start();
});
</code>```

The example on https://introjs.com/docs/getting-started/start uses the function call introJs().start()

You only have to call the function whether on button click or document ready event.

Coming to the second part of your question, the easiest solution would be to use localStorage.

Something like this, should do the trick.

```<code>document.addEventListener("DOMContentLoaded", function() {

    var hadTour = localStorage.getItem('hadTour');

    if(!hadTour){
            introJs().oncomplete(function() {
            localStorage.setItem('hadTour', true);
            }).onexit(function(){
            localStorage.setItem('hadTour', true);
            }).start();
    }

});
</code>```

Title: Introjs on load

Body:
Call introJs().start() on document ready event.

document.addEventListener("DOMContentLoaded", function() {
  introJs().start();
});

The example on https://introjs.com/docs/getting-started/start uses the function call introJs().start()

You only have to call the function whether on button click or document ready event.

Coming to the second part of your question, the easiest solution would be to use localStorage.

Something like this, should do the trick.

document.addEventListener("DOMContentLoaded", function() {

    var hadTour = localStorage.getItem('hadTour');

    if(!hadTour){
            introJs().oncomplete(function() {
            localStorage.setItem('hadTour', true);
            }).onexit(function(){
            localStorage.setItem('hadTour', true);
            }).start();
    }

});


问:
Swift understanding self[key] and casting
Please consider following code:

```<code>extension Dictionary {
    public func msArray(_ key: Key) -> [Dictionary<String, Any>] {
        return (self[key] as? Array<[String : Int]> ?? [])
    }
}

let dict = ["Warlock" : ["Hp" : 100],  "Rogue" : ["Hp" : 150], "Warrior" : ["Hp" : 250]]
</code>```

Following produce []:

```<code>print(dict.msArray("Warlock"))
</code>```

Why? Isn't it suppose to print ["Hp" : 100]?

答:
It's problem with the return type.For The result you want, need to add return type as Dictionary From the extension, not an array.  </p>

<p>Please check this code. </p>

```<code>extension Dictionary {
    public func msArray(_ key: Key) -> [String : Any] {
        return self[key] as? [String : Any] ?? [:]
    }
}

let dict = ["Warlock" : ["Hp" : 100],  "Rogue" : ["Hp" : 150], "Warrior" : ["Hp" : 250]]
print(dict.msArray("Warlock"))
</code>```

Body:
Please consider following code:

extension Dictionary {
    public func msArray(_ key: Key) -> [Dictionary<String, Any>] {
        return (self[key] as? Array<[String : Int]> ?? [])
    }
}

let dict = ["Warlock" : ["Hp" : 100],  "Rogue" : ["Hp" : 150], "Warrior" : ["Hp" : 250]]

Following produce []:

print(dict.msArray("Warlock"))

Why? Isn't it suppose to print ["Hp" : 100]?

Body:
It's problem with the return type.For The result you want, need to add return type as Dictionary From the extension, not an array.

Please check this code.

extension Dictionary {
    public func msArray(_ key: Key) -> [String : Any] {
        return self[key] as? [String : Any] ?? [:]
    }
}

let dict = ["Warlock" : ["Hp" : 100],  "Rogue" : ["Hp" : 150], "Warrior" : ["Hp" : 250]]
print(dict.msArray("Warlock"))


问:
How do I pass a date in the Java Date format to cURL (PHP)?
There is an Android application, it sends to the server through Parse.com one of the parameters in the format Date:

```<code>HashMap<String, Object> p = new HashMap();
p.put("created", Calendar.getInstance().getTime());
ParseCloud.callFunctionInBackground(f, p, v);
</code>```

How can I pass a parameter in the same format, but only through cURL in PHP? I tried to pass a string value to the array, the server does not accept the request:

```<code>array('created'=>'Sun Nov 12 2017 02:58:09 GMT+0300')
</code>```

As I understand, it is necessary to pass the parameter in the form of the Date object itself, but the question is how it will look in the raw text form?

I tried to pass the Date as an array, but this server does not want to accept either:

```<code>array('__type'=>'Date','iso'=>'2017-11-11T12:35:39.273Z')
</code>```

答:
You can pass a date to parse-server in ISO 8601 format (with millisecond precision), as mentioned in the REST docs.

```<code>{
    "__type": "Date",
    "iso": "2011-08-21T18:02:52.249Z"
}
</code>```

You can see an example of how this is done in the php sdk.

Body:
There is an Android application, it sends to the server through Parse.com one of the parameters in the format Date:

HashMap<String, Object> p = new HashMap();
p.put("created", Calendar.getInstance().getTime());
ParseCloud.callFunctionInBackground(f, p, v);

How can I pass a parameter in the same format, but only through cURL in PHP? I tried to pass a string value to the array, the server does not accept the request:

array('created'=>'Sun Nov 12 2017 02:58:09 GMT+0300')

As I understand, it is necessary to pass the parameter in the form of the Date object itself, but the question is how it will look in the raw text form?

I tried to pass the Date as an array, but this server does not want to accept either:

array('__type'=>'Date','iso'=>'2017-11-11T12:35:39.273Z')

Body:
You can pass a date to parse-server in ISO 8601 format (with millisecond precision), as mentioned in the REST docs.

{
    "__type": "Date",
    "iso": "2011-08-21T18:02:52.249Z"
}

You can see an example of how this is done in the php sdk.


问:
What python concept causes this result?
So I was studying for an exam and i made a simple function to review 'sequential processing' and then I made this function(s) that turn a string input of whitespaced numbers into a list and scan to find the highest, but my conditional seems to think 8 is greater than 20 and 23. Can someone tell my why this is?

```<code>def findMax(numberlist):
maxval = numberlist[0]
for i in numberlist[1:]:
    print("The value now is:\t",i,"\nThe max value is currently\t",maxval,"\n")
    if(i > maxval):
        maxval = i
print(maxval)
return maxval

def makeList(stringput):
    print(stringput)
    stringput = stringput.split(" ")
    for i in stringput[0:]:
        print("Value is:\t",i)
    return stringput

findMax(makeList(input("\nWhat test are to be sorted\n")))
</code>```

This returned the result 8 from the input "1 20 8 21"

Edit:Sorry, new user
.

答:
So, you basically need to cast each string representation of integers to an integer by using int().  So, '20' < '8' because 2 comes before 8 in ASCII order.  When checking for which string is greater, each character is compared to see which is larger, it doesn't acknowledge the context of the '0' behind the '2'. But int('20') < int('8') because of how the number line works (over simplified).

You can do this all via a list comprehension:

```<code>stringput = [int(val) for val in stringput]
</code>```

Result:

```<code>def findMax(numberlist):
    maxval = numberlist[0]
    for i in numberlist[1:]:
        print("The value now is:\t",i,"\nThe max value is currently\t",maxval,"\n")
        if(i > maxval):
            maxval = i
    print(maxval)
    return maxval

def makeList(stringput):
    print(stringput)
    stringput = stringput.split(" ")
    stringput = [int(val) for val in stringput] #new line
    for i in stringput[0:]:
        print("Value is:\t",i)
    return stringput

findMax(makeList(input("\nWhat test are to be sorted\n")))
</code>```

Title: What python concept causes this result?

Body:
So I was studying for an exam and i made a simple function to review 'sequential processing' and then I made this function(s) that turn a string input of whitespaced numbers into a list and scan to find the highest, but my conditional seems to think 8 is greater than 20 and 23. Can someone tell my why this is?

def findMax(numberlist):
maxval = numberlist[0]
for i in numberlist[1:]:
    print("The value now is:\t",i,"\nThe max value is currently\t",maxval,"\n")
    if(i > maxval):
        maxval = i
print(maxval)
return maxval

def makeList(stringput):
    print(stringput)
    stringput = stringput.split(" ")
    for i in stringput[0:]:
        print("Value is:\t",i)
    return stringput

findMax(makeList(input("\nWhat test are to be sorted\n")))

This returned the result 8 from the input "1 20 8 21"

Edit:Sorry, new user
.

Body:
So, you basically need to cast each string representation of integers to an integer by using int().  So, '20' < '8' because 2 comes before 8 in ASCII order.  When checking for which string is greater, each character is compared to see which is larger, it doesn't acknowledge the context of the '0' behind the '2'. But int('20') < int('8') because of how the number line works (over simplified).

You can do this all via a list comprehension:

stringput = [int(val) for val in stringput]

Result:

def findMax(numberlist):
    maxval = numberlist[0]
    for i in numberlist[1:]:
        print("The value now is:\t",i,"\nThe max value is currently\t",maxval,"\n")
        if(i > maxval):
            maxval = i
    print(maxval)
    return maxval

def makeList(stringput):
    print(stringput)
    stringput = stringput.split(" ")
    stringput = [int(val) for val in stringput] #new line
    for i in stringput[0:]:
        print("Value is:\t",i)
    return stringput

findMax(makeList(input("\nWhat test are to be sorted\n")))


问:
How to style path in leaflet?
I have line geometry that I've styled using the dashArray option. I'm trying to add a black outline to distinguish the gaps on lighter basemaps.

I tried adding a black path underneath with a heavier weight to create the outline but it seems that the gaps are transparent.

Applying the following style to the respective layers creates a white line with a black outline:

```<code>path = {
    color: '#ffffff',
    weight: 3,
    opacity: 1
}

outline = {
    color: '#000000',
    weight: 5,
    opacity: 1
}
</code>```

When I apply dashArray the bottom layer shows through:

```<code>path = {
    color: '#000000',
    weight: 3,
    opacity: 1,
    dashArray: '5,10'
}

outline = {
    color: '#000000',
    weight: 5,
    opacity: 1
}
</code>```

Is there a simple way to achieve this?

Leaflet path style options here.

EDIT: Top path is dashArray by itself. Second is when I overlay the dashArray on the wider black line (outline). Third is what I'm trying to achieve.

答:
You could achieve the same effect with just 2 paths:

Background, continuous and wider.

Foreground, dashed and narrower. The background is visible through the gaps.

It is not exactly the same result, since if you want round caps, it is the white dashes that get them. But if you want actually square caps, as shown below, then you get the same effect:

var map = L.map("map").setView([0.4, 0], 8);
var coords = [
  [0, -1],
  [0, 1],
  [1, 1]
];

// Background continuous black stroke, wider than dashed line.
L.polyline(coords, {
  weight: 10,
  lineCap: 'square', // Optional, just to avoid round borders.
  color: 'black'
}).addTo(map);

// Foreground dashed white stroke, narrower than background.
L.polyline(coords, {
  weight: 6,
  dashArray: '5, 10',
  lineCap: 'square', // Optional, just to avoid round borders.
  color: 'white'
}).addTo(map);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css">
<script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet-src.js"></script>
<div id="map" style="height: 200px"></div></code>```

Title: How to style path in leaflet?

Body:
I have line geometry that I've styled using the dashArray option. I'm trying to add a black outline to distinguish the gaps on lighter basemaps.

I tried adding a black path underneath with a heavier weight to create the outline but it seems that the gaps are transparent.

Applying the following style to the respective layers creates a white line with a black outline:

path = {
    color: '#ffffff',
    weight: 3,
    opacity: 1
}

outline = {
    color: '#000000',
    weight: 5,
    opacity: 1
}

When I apply dashArray the bottom layer shows through:

path = {
    color: '#000000',
    weight: 3,
    opacity: 1,
    dashArray: '5,10'
}

outline = {
    color: '#000000',
    weight: 5,
    opacity: 1
}

Is there a simple way to achieve this?

Leaflet path style options here.

EDIT: Top path is dashArray by itself. Second is when I overlay the dashArray on the wider black line (outline). Third is what I'm trying to achieve.

Body:
You could achieve the same effect with just 2 paths:

Background, continuous and wider.

Foreground, dashed and narrower. The background is visible through the gaps.

It is not exactly the same result, since if you want round caps, it is the white dashes that get them. But if you want actually square caps, as shown below, then you get the same effect:

var map = L.map("map").setView([0.4, 0], 8);
var coords = [
  [0, -1],
  [0, 1],
  [1, 1]
];

// Background continuous black stroke, wider than dashed line.
L.polyline(coords, {
  weight: 10,
  lineCap: 'square', // Optional, just to avoid round borders.
  color: 'black'
}).addTo(map);

// Foreground dashed white stroke, narrower than background.
L.polyline(coords, {
  weight: 6,
  dashArray: '5, 10',
  lineCap: 'square', // Optional, just to avoid round borders.
  color: 'white'
}).addTo(map);

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css">
<script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet-src.js"></script>
<div id="map" style="height: 200px"></div>


答:
You're entering strings into python. That means that all sorting is happening alphabetically - not numerically.

For example, if you sorted the following two word alphabetically, which would you put first?

Apple

Bee

Apple right? Because A comes before B. Lets try again

8

23

It's going to be 23 - 8 is later in the 'alphabet'.

If you want to sort these properly, cast them all to ints first. Or use a library such as natsorted.

Title: What python concept causes this result?


问:
map function is returning elements of u type
I ran the following pyspark script to do word count:

```<code>import re
inputRDD=sc.textFile("concatfile")
cleanRDD=inputRDD.map(lambda x:re.sub('[^0-9a-zA-Z ]+',"",x.upper())).flatMap(lambda x: x.split()).map(lambda x:(x,1))
reduceRDD=cleanRDD.reduceByKey(lambda x,y:x+y)
reverseKVRDD=reduceRDD.map(lambda x:(x[1],x[0]))
sortRDD=reverseKVRDD.sortByKey(ascending=False)
</code>```

When I dumped cleanRDD, I observed that the key-value pair is coming in the below format:

[(u'THIS', 1), (u'IS', 1), (u'LINE', 1), (u'1', 1), (u'THIS', 1), (u'IS', 1), (u'LINE', 1), (u'2', 1), (u'THIS', 1), (u'IS', 1), (u'LINE', 1), (u'3', 1)]

What is meant by this u'' type? Can I convert it to a normal string type?

答:
In python 'u' means unicode. All the values returned by your program is in unicode format.

You can convert unicode to normal string using encode method.

```<code>text = u'sample text'
print type(text)

# Output
unicode

text = text.encode('utf-8')
print type(text)

# Output
str
</code>```

Body:
I ran the following pyspark script to do word count:

import re
inputRDD=sc.textFile("concatfile")
cleanRDD=inputRDD.map(lambda x:re.sub('[^0-9a-zA-Z ]+',"",x.upper())).flatMap(lambda x: x.split()).map(lambda x:(x,1))
reduceRDD=cleanRDD.reduceByKey(lambda x,y:x+y)
reverseKVRDD=reduceRDD.map(lambda x:(x[1],x[0]))
sortRDD=reverseKVRDD.sortByKey(ascending=False)

When I dumped cleanRDD, I observed that the key-value pair is coming in the below format:

[(u'THIS', 1), (u'IS', 1), (u'LINE', 1), (u'1', 1), (u'THIS', 1), (u'IS', 1), (u'LINE', 1), (u'2', 1), (u'THIS', 1), (u'IS', 1), (u'LINE', 1), (u'3', 1)]

What is meant by this u'' type? Can I convert it to a normal string type?

Body:
In python 'u' means unicode. All the values returned by your program is in unicode format.

You can convert unicode to normal string using encode method.

text = u'sample text'
print type(text)

# Output
unicode

text = text.encode('utf-8')
print type(text)

# Output
str


答:
["Hp" : 100] is a [String : Int] not Array<[String : Int]>. Thats why your msArray function is returning [].  Change your extension to:

```<code>extension Dictionary {
   public func msArray(_ key: Key) -> [String:Int]{
     return self[key] as? [String : Int] ?? [:]
   }
}
</code>```

Title: Swift understanding self[key] and casting

Body:
["Hp" : 100] is a [String : Int] not Array<[String : Int]>. Thats why your msArray function is returning [].  Change your extension to:

extension Dictionary {
   public func msArray(_ key: Key) -> [String:Int]{
     return self[key] as? [String : Int] ?? [:]
   }
}


问:
Difference between Module and Class in Python
Can I assign value to a variable in the module? If yes, what is the difference between a class and module?

PS: I'm a Java guy (in case it helps in the way of explaining). Thanks.

答:
Can I assign value to a variable in the module?

In short yes.

The concept of module refers to a single Python file which can be imported (by importing, you have the access to the variables/methods/classes defined in that module).

It is commonly discussed together with the concept package, which is a folder with __init__.py. A package can contain sub-packages or modules, and at the same time, similar to modules, can define variables/methods/classes to be imported inside its __init__.py.

The purpose of having modules/packages in Python is kind of similar to having packages in Java: to contain and categorize reusable codes, to resolve naming confliction and so on.

Besides, Python also has a builtin class named module, just like list, tuple, dict (note that Python builtin classes do not follow the CapWords naming convention due to legacy reasons). A module instance represents the module/package imported.

When you use the import statement to import a module (single Python file) or a package (folder with __init__.py), typically

1. a new instance of module class will be created

2. the classes/methods/variables you defined in that imported Python file will be added as the attributes of this module instance (if it is a package, it will be the classes/methods/variables defined in __init__.py that are added).

Therefore, since it is just an instance of module class, you can assign a value to the attribute of that instance and other class instance operations.

```<code>import math

print(type([1,2,3]))
print(type(math))
print(dir([1,2,3]))
print(dir(math))
</code>```

console:

```<code><class 'list'>
<class 'module'>
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Can I assign value to a variable in the module?

In short yes.

The concept of module refers to a single Python file which can be imported (by importing, you have the access to the variables/methods/classes defined in that module).

It is commonly discussed together with the concept package, which is a folder with __init__.py. A package can contain sub-packages or modules, and at the same time, similar to modules, can define variables/methods/classes to be imported inside its __init__.py.

The purpose of having modules/packages in Python is kind of similar to having packages in Java: to contain and categorize reusable codes, to resolve naming confliction and so on.

Besides, Python also has a builtin class named module, just like list, tuple, dict (note that Python builtin classes do not follow the CapWords naming convention due to legacy reasons). A module instance represents the module/package imported.

When you use the import statement to import a module (single Python file) or a package (folder with __init__.py), typically

1. a new instance of module class will be created

2. the classes/methods/variables you defined in that imported Python file will be added as the attributes of this module instance (if it is a package, it will be the classes/methods/variables defined in __init__.py that are added).

Therefore, since it is just an instance of module class, you can assign a value to the attribute of that instance and other class instance operations.

import math

print(type([1,2,3]))
print(type(math))
print(dir([1,2,3]))
print(dir(math))

console:

<class 'list'>
<class 'module'>
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']


问:
How to carry on build execution in jenkins ignoring the passed steps after fixing a failed step
As a part of CI/CD activity, I am migrating a project from Build Forge to Jenkins. Since I am new to jenkins, I am confused as to how to continue execution in Jenkins from a failed step, ignoring the previously passed steps. Or is it that all the steps should rerun from the beginning? Appreciating any ideas are welcome.</p>

答:
I think the only way to do this is with the Cloudbees Checkpoints plugin, which is not open source. You would have to use the Cloudbees version of Jenkins:

https://go.cloudbees.com/docs/cloudbees-documentation/cje-user-guide/index.html?q=checkpoints#workflow


问:
SVG layer not rescale width map layer
Im using leaflet, which have map layer and svg layer.But when im zooming, the svg layer not scale with the map layer size. Which make the svg layer size wrong, and not display my svg content

this is my code

```<code>MapLeaflet.prototype.init = function (map) {
  let $$ = this;
  $$.dom = map;
  this.map = L.map(map).setView([-6.175239, 106.827204], 13);
  L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png').addTo($$.map);

  this.svg = d3.select($$.map.getPanes().overlayPane).append("svg")
    .attr('style', 'display: flex; flex: 1 1 auto; min-height: 100vh; min-width: 100vw; position: relative; flex-grow: 1')
    .append("g").attr("class", "leaflet-zoom-hide");
}
</code>```

答:
i should not manualy add the SVG layer. Leaflet have its own function for adding svg layer

this is my final code

```<code>MapLeaflet.prototype.init = function (map) {
  let $$ = this;
  $$.dom = map;
  this.map = L.map(map).setView([-6.175239, 106.827204], 13);
  L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png').addTo($$.map);

  var svgLayer = L.svg();
  svgLayer.addTo(this.map);
  this.svg = d3.select('svg g');
}
</code>```

Title: SVG layer not rescale width map layer

Body:
Im using leaflet, which have map layer and svg layer.But when im zooming, the svg layer not scale with the map layer size. Which make the svg layer size wrong, and not display my svg content

this is my code

MapLeaflet.prototype.init = function (map) {
  let $$ = this;
  $$.dom = map;
  this.map = L.map(map).setView([-6.175239, 106.827204], 13);
  L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png').addTo($$.map);

  this.svg = d3.select($$.map.getPanes().overlayPane).append("svg")
    .attr('style', 'display: flex; flex: 1 1 auto; min-height: 100vh; min-width: 100vw; position: relative; flex-grow: 1')
    .append("g").attr("class", "leaflet-zoom-hide");
}

Body:
i should not manualy add the SVG layer. Leaflet have its own function for adding svg layer

this is my final code

MapLeaflet.prototype.init = function (map) {
  let $$ = this;
  $$.dom = map;
  this.map = L.map(map).setView([-6.175239, 106.827204], 13);
  L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png').addTo($$.map);

  var svgLayer = L.svg();
  svgLayer.addTo(this.map);
  this.svg = d3.select('svg g');
}


问:
odoo interface display incorrectly
I have starting to learn odoo recently and using odoo:10.0. but I have a problem with odoo interface where it display almost nothing at all. Here are my screenshots :

My odoo before sign in:

My odoo after sign in:

答:
Try these steps:

```<code>sudo apt-get install -y npm
sudo ln -s /usr/bin/nodejs /usr/bin/node
sudo npm install -g less less-plugin-clean-css
</code>```

Then restart odoo server try again.

Note: Experience same problem, try on incognito browser.

Hope it will help you.

Title: odoo interface display incorrectly

Body:
Try these steps:

sudo apt-get install -y npm
sudo ln -s /usr/bin/nodejs /usr/bin/node
sudo npm install -g less less-plugin-clean-css

Then restart odoo server try again.

Note: Experience same problem, try on incognito browser.

Hope it will help you.


问:
Binding a Combobox control to a separate source within a DataGrid
Im attempting to use a ComboBox within a DataGrid which will allow the user to select a value coming from a different table. Im using a ViewModel class as the DataContext and this contains an ObservableCollection for Terminals and another for TerminalTypes.

The binding on the grid is fine, all the rows are populated and the DataGridTextColumns all show the correct data, my ComboBox however is empty.

I know that the ObservableCollection Im attempting to bind to has been populated and if I move the ComboBox outside of the DataGrid it works as expected.

```<code><my:DataGrid Name="MenuDetailGrid" AutoGenerateColumns="False" ItemsSource="{Binding Terminals}">
    <my:DataGrid.Columns>
        <my:DataGridTextColumn Header="Terminal Type ID" Binding="{Binding TERMINAL_TYPE_ID}" IsReadOnly="True" />
        <my:DataGridTemplateColumn Header="Terminal Type">
            <my:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ComboBox DisplayMemberPath="TTYPE_NAME" SelectedValuePath="TERMINAL_TYPE"
                              SelectedValue="{Binding TERMINAL_TYPE_ID}"
                              ItemsSource="{Binding TerminalTypes}" />

                </DataTemplate>
            </my:DataGridTemplateColumn.CellTemplate>
        </my:DataGridTemplateColumn>
</code>```

Obviously the binding behaviour is different on the ComboBox when part of the DataGrid but Im a bit stumped as to why?

Can someone please help me understand what I am doing wrong?

答:
The binding behaviour is the same. However is the DataContext in a DataTemplate set by the ItemsControl to current item and this is in your case a member of the Terminals-collection. Therefore, the TerminalTypes-collection could not be found (unless you  implement it also on your item).

What you can do is to use a relative source in your Binding. With this, you can navigate to the DataGrid's DataContext and then access your TerminalTypes-Collection:

```<code><ComboBox DisplayMemberPath="TTYPE_NAME"
    SelectedValuePath="TERMINAL_TYPE"
    SelectedValue="{Binding TERMINAL_TYPE_ID}"
    ItemsSource="{Binding DataContext.TerminalTypes,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}" />
</code>```

Hope this helped. Make a comment if not.

Body:
Im attempting to use a ComboBox within a DataGrid which will allow the user to select a value coming from a different table. Im using a ViewModel class as the DataContext and this contains an ObservableCollection for Terminals and another for TerminalTypes.

The binding on the grid is fine, all the rows are populated and the DataGridTextColumns all show the correct data, my ComboBox however is empty.

I know that the ObservableCollection Im attempting to bind to has been populated and if I move the ComboBox outside of the DataGrid it works as expected.

<my:DataGrid Name="MenuDetailGrid" AutoGenerateColumns="False" ItemsSource="{Binding Terminals}">
    <my:DataGrid.Columns>
        <my:DataGridTextColumn Header="Terminal Type ID" Binding="{Binding TERMINAL_TYPE_ID}" IsReadOnly="True" />
        <my:DataGridTemplateColumn Header="Terminal Type">
            <my:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ComboBox DisplayMemberPath="TTYPE_NAME" SelectedValuePath="TERMINAL_TYPE"
                              SelectedValue="{Binding TERMINAL_TYPE_ID}"
                              ItemsSource="{Binding TerminalTypes}" />

                </DataTemplate>
            </my:DataGridTemplateColumn.CellTemplate>
        </my:DataGridTemplateColumn>

Obviously the binding behaviour is different on the ComboBox when part of the DataGrid but Im a bit stumped as to why?

Can someone please help me understand what I am doing wrong?

Body:
The binding behaviour is the same. However is the DataContext in a DataTemplate set by the ItemsControl to current item and this is in your case a member of the Terminals-collection. Therefore, the TerminalTypes-collection could not be found (unless you  implement it also on your item).

What you can do is to use a relative source in your Binding. With this, you can navigate to the DataGrid's DataContext and then access your TerminalTypes-Collection:

<ComboBox DisplayMemberPath="TTYPE_NAME"
    SelectedValuePath="TERMINAL_TYPE"
    SelectedValue="{Binding TERMINAL_TYPE_ID}"
    ItemsSource="{Binding DataContext.TerminalTypes,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}" />

Hope this helped. Make a comment if not.


问:
How can i generate token in php using developer key , application id and username?
Anyone can describe how i generate token in php using developer key, application id and username.  Videyo provide only html js, they haven't any support for php.  Please  hint me. The token length is 200 plus.</p>

答:
You can use below code to generate token:

```
<code>

    class secureToken{
       private static $secretKey = 'Your Desired key(Hash)';
       private static $secretIv = 'www.domain.com';
       private static $encryptMethod = "AES-256-CBC";
       public static function tokenencrypt($data) {
          $key = hash('sha256', self::$secretKey);
          $iv = substr(hash('sha256', self::$secretIv), 0, 16);
          $result = openssl_encrypt($data, self::$encryptMethod, $key, 0, $iv);
          return $result= base64_encode($result);
       }
       public static function tokendecrypt($data) {
          $key = hash('sha256', self::$secretKey);
          $iv = substr(hash('sha256', self::$secretIv), 0, 16);
          $result = openssl_decrypt(base64_decode($data), self::$encryptMethod, $key, 0, $iv);
          return $result;
       }
    }

</code>
```

method to use :

```<code>

    $tokenencrypt = secureToken::tokenencrypt(Your APP ID and Userid);
    $tokendecrypt = secureToken::tokendecrypt($tokenencrypt);

</code>
```

Body:
You can use below code to generate token:

    class secureToken{
       private static $secretKey = 'Your Desired key(Hash)';
       private static $secretIv = 'www.domain.com';
       private static $encryptMethod = "AES-256-CBC";
       public static function tokenencrypt($data) {
          $key = hash('sha256', self::$secretKey);
          $iv = substr(hash('sha256', self::$secretIv), 0, 16);
          $result = openssl_encrypt($data, self::$encryptMethod, $key, 0, $iv);
          return $result= base64_encode($result);
       }
       public static function tokendecrypt($data) {
          $key = hash('sha256', self::$secretKey);
          $iv = substr(hash('sha256', self::$secretIv), 0, 16);
          $result = openssl_decrypt(base64_decode($data), self::$encryptMethod, $key, 0, $iv);
          return $result;
       }
    }

method to use :

    $tokenencrypt = secureToken::tokenencrypt(Your APP ID and Userid);
    $tokendecrypt = secureToken::tokendecrypt($tokenencrypt);


问:
remove pipe from value column and new 6 column in same table with single separated value in sql
The table detail shown below:</p>

```<code>REPORT_ID                  ATTR          VALUE
INV_2017-08-29T06:00:00  /s-1/          /s-1/|7500|25|LPG|3610.94870820629|3526.84971279216|3523.3882574674
</code>```

答:
One method is XML node method if you are working with SQL Server

```<code>select distinct REPORT_ID, ATTR,
     a.value ('/A[1]', 'VARCHAR(MAX)') [Value1],
     a.value ('/A[2]', 'VARCHAR(MAX)') [Value2],
     a.value ('/A[3]', 'VARCHAR(MAX)') [Value3],
     a.value ('/A[4]', 'VARCHAR(MAX)') [Value4],
     a.value ('/A[5]', 'VARCHAR(MAX)') [Value5],
     a.value ('/A[6]', 'VARCHAR(MAX)') [Value6],
     a.value ('/A[7]', 'VARCHAR(MAX)') [Value7]

      from
(
    SELECT REPORT_ID, ATTR, CAST('<A>'+REPLACE(Value,'|', '</A><A>')+'</A>' AS XML) AS Value
    FROM [AmmDb].[dbo].[IP_REPORT]
) A CROSS APPLY Value.nodes ('/A') as split(a)
</code>```

Result :

```<code>REPORT_ID                ATTR   Value1  Value2  Value3  Value4  Value5  .....       Value7
INV_2017-08-29T06:00:00 /s-1/   /s-1/   7500    25      LPG  3610.94870820629       3523.3882574674
</code>```

Body:
The table detail shown below:

REPORT_ID                  ATTR          VALUE
INV_2017-08-29T06:00:00  /s-1/          /s-1/|7500|25|LPG|3610.94870820629|3526.84971279216|3523.3882574674

Body:
One method is XML node method if you are working with SQL Server

select distinct REPORT_ID, ATTR,
     a.value ('/A[1]', 'VARCHAR(MAX)') [Value1],
     a.value ('/A[2]', 'VARCHAR(MAX)') [Value2],
     a.value ('/A[3]', 'VARCHAR(MAX)') [Value3],
     a.value ('/A[4]', 'VARCHAR(MAX)') [Value4],
     a.value ('/A[5]', 'VARCHAR(MAX)') [Value5],
     a.value ('/A[6]', 'VARCHAR(MAX)') [Value6],
     a.value ('/A[7]', 'VARCHAR(MAX)') [Value7]

      from
(
    SELECT REPORT_ID, ATTR, CAST('<A>'+REPLACE(Value,'|', '</A><A>')+'</A>' AS XML) AS Value
    FROM [AmmDb].[dbo].[IP_REPORT]
) A CROSS APPLY Value.nodes ('/A') as split(a)

Result :

REPORT_ID                ATTR   Value1  Value2  Value3  Value4  Value5  .....       Value7
INV_2017-08-29T06:00:00 /s-1/   /s-1/   7500    25      LPG  3610.94870820629       3523.3882574674


问:
Express redirect firebase can't set headers after they are sent
I am using nodejs express and firebase for my database. So what I am trying to do is upon user's post request, update firebase data and redirect user to another page. But I keep getting Error: Can't set headers after they are sent.

Here is my code in controller.js file:

```<code>app.post('/carpark', urlencodedParser, function(req,res){
    req.session.carpark = req.body.carpark;
lotsRef.orderByChild('CarparkName').equalTo(req.session.carpark).on('value', function(snapshot){
        for (var key in snapshot.val()) {
            if (snapshot.val()[key]['Availability'] == true) {
                firebase.database().ref('Lots/'+ key).update({'Availability': false });
                res.redirect('checkin');
                break;
            }
        }
    });
</code>```

EDITED:

```<code>app.post('/carpark', urlencodedParser, function(req,res){
    req.session.carpark = req.body.carpark;
    lotsRef.orderByChild('CarparkName').equalTo(req.session.carpark).on('value', function(snapshot){
        for (var key in snapshot.val()) {
            var allocatedtime = new Date().getHours() + ':' + (new Date().getMinutes() <10 ? '0' : '') + new Date().getMinutes() + ':' + (new Date().getSeconds() <10 ?'0' : '') + new Date().getSeconds();
                req.session.key = key;
                req.session.LotID = snapshot.val()[key]['LotID'];
                req.session.AllocatedTime = allocatedtime;
                req.session.SerialNum = snapshot.val()[key]['SerialNumber'];
                var date = new Date().getFullYear() + "-" + (new Date().getMonth()+1) + "-" + new Date().getDate();
                req.session.DateAllocated = date;
                console.log(req.session);
                firebase.database().ref('Lots/'+ req.session.key).update({'Availability': false });
                break;
            }
        }
        res.redirect('checkin');
    });
</code>```

答:
The redirect should be moved outside For loop:

```<code>app.post('/carpark', urlencodedParser, function(req,res){
    req.session.carpark = req.body.carpark;
lotsRef.orderByChild('CarparkName').equalTo(req.session.carpark).on('value', function(snapshot){
        for (var key in snapshot.val()) {
            if (snapshot.val()[key]['Availability'] == true) {
                firebase.database().ref('Lots/'+ key).update({'Availability': false });
                break;
            }
        }
        res.redirect('checkin');
    });
</code>```

But this will redirect to 'checkin' irrespective of your if clause, so that depends on your scenario whether you want to redirect to some other page when the if clause is not true even once.

Body:
I am using nodejs express and firebase for my database. So what I am trying to do is upon user's post request, update firebase data and redirect user to another page. But I keep getting Error: Can't set headers after they are sent.

Here is my code in controller.js file:

app.post('/carpark', urlencodedParser, function(req,res){
    req.session.carpark = req.body.carpark;
lotsRef.orderByChild('CarparkName').equalTo(req.session.carpark).on('value', function(snapshot){
        for (var key in snapshot.val()) {
            if (snapshot.val()[key]['Availability'] == true) {
                firebase.database().ref('Lots/'+ key).update({'Availability': false });
                res.redirect('checkin');
                break;
            }
        }
    });

EDITED:

app.post('/carpark', urlencodedParser, function(req,res){
    req.session.carpark = req.body.carpark;
    lotsRef.orderByChild('CarparkName').equalTo(req.session.carpark).on('value', function(snapshot){
        for (var key in snapshot.val()) {
            var allocatedtime = new Date().getHours() + ':' + (new Date().getMinutes() <10 ? '0' : '') + new Date().getMinutes() + ':' + (new Date().getSeconds() <10 ?'0' : '') + new Date().getSeconds();
                req.session.key = key;
                req.session.LotID = snapshot.val()[key]['LotID'];
                req.session.AllocatedTime = allocatedtime;
                req.session.SerialNum = snapshot.val()[key]['SerialNumber'];
                var date = new Date().getFullYear() + "-" + (new Date().getMonth()+1) + "-" + new Date().getDate();
                req.session.DateAllocated = date;
                console.log(req.session);
                firebase.database().ref('Lots/'+ req.session.key).update({'Availability': false });
                break;
            }
        }
        res.redirect('checkin');
    });

Body:
The redirect should be moved outside For loop:

app.post('/carpark', urlencodedParser, function(req,res){
    req.session.carpark = req.body.carpark;
lotsRef.orderByChild('CarparkName').equalTo(req.session.carpark).on('value', function(snapshot){
        for (var key in snapshot.val()) {
            if (snapshot.val()[key]['Availability'] == true) {
                firebase.database().ref('Lots/'+ key).update({'Availability': false });
                break;
            }
        }
        res.redirect('checkin');
    });

But this will redirect to 'checkin' irrespective of your if clause, so that depends on your scenario whether you want to redirect to some other page when the if clause is not true even once.


问:
Invoking OpenShift Service Catalog REST resources
In the context of the OpenShift 3.7 Service Catalog, what would it look like if I wanted to create Service Instances outside of the OpenShift Console UI?

I.e. from a terminal on my local machine, if I wanted to create an instance of a Service Class available in the Service Catalog (e.g. run and an APB available via the Ansible Service Broker) what would the REST resource call look like (assuming there is a REST API available)?

An example using curl would be appreciated.

The assumption is that there is a REST API available for Service Catalog related resources. If this is not true, what is another integration pattern that would satisfy the requirement above? Does the oc CLI tool support Service Catalog commands?

答:
The best examples I can point you to are the ones from the incubator repo walkthrough.  You'll probably be most interested in the example ServiceInstance and example ServiceBinding.

The service-catalog has a normal Kubernetes API server and the resources work like the other resources you're familiar with do.  For example, you could make a new instance of a service in the openshift console and poke around in the API server using:

```<code>$ kubectl get serviceinstances
</code>```

Note, oc get serviceinstances is another valid form of command to use.

The CLI experience isn't fantastic for kubectl get for these resources yet, but describe works very well.  In a future release of service-catalog the CLI experience for kubectl get will be improved.

Body:
The best examples I can point you to are the ones from the incubator repo walkthrough.  You'll probably be most interested in the example ServiceInstance and example ServiceBinding.

The service-catalog has a normal Kubernetes API server and the resources work like the other resources you're familiar with do.  For example, you could make a new instance of a service in the openshift console and poke around in the API server using:

$ kubectl get serviceinstances

Note, oc get serviceinstances is another valid form of command to use.

The CLI experience isn't fantastic for kubectl get for these resources yet, but describe works very well.  In a future release of service-catalog the CLI experience for kubectl get will be improved.


问:
How can I choose randomly a drawable resource (picture) and set it as a background of a button?
I'm new with Android and StackOverflow. I accept all kind of recommendations while learning how to post correctly. My native language is not English, so please be patient if I don't write well.

I am making a game and what I have to do is to set bakcground in a specific moment of the game; 6 ramdom picture from drawable resources should be picked to set to 12 buttons I have in the UI (each one of the 6 ramdom pictures should be set to two different buttons).

What I don't know to do is how to set the images ramdonly and how to know in which button they were set. Being honest, I don't know how to start with it.

Thanks

答:
```<code>List<Integer> drawables = Arrays.asList(R.drawable.pic1, R.drawable.pic2,
      R.drawable.pic3, R.drawable.pic4, R.drawable.pic5, R.drawable.pic6);

List<Integer> buttons = Arrays.asList(R.id.btn1, R.id.btn2, R.id.btn3,
    R.id.btn4, R.id.btn5, R.id.bt6, R.id.btn7, R.id.btn8, R.id.btn9,
    R.id.btn10, R.id.btn11, R.id.btn12);

private void setRandomBackground() {
    Collections.shuffle(drawables);
    Collections.shuffle(buttons);

    for (int i = 0, j = 0; i < drawables.size(); i++, j+=2) {
        findViewById(buttons.get(j))
                .setBackgroundResource(drawables.get(i));
        findViewById(buttons.get(j+1))
                .setBackgroundResource(drawables.get(i));
    }

}
</code>```


答:
You can use twilo php to generate your token with given parameters.

twilo docs

Title: How can i generate token in php using developer key , application id and username?

Body: Anyone can describe how i generate token in php using developer key, application id and username.  Videyo provide only html js, they haven't any support for php.  Please  hint me. The token length is 200 plus.


问:
Microsoft SQL xp_cmdshell doesn't like filenames with spaces. Can I replace the space with something else?
I have this TSQL code that dumps data from tables using BCP.  It looks complicated, but it simply creates a @command string to be executed once for each table, then BCP dump the table records to disk.  It's a nice way to backup all the table data quickly.  Below I show the resolved version which is a little easier to read.

```<code>set @command =
  'if (''?'' <> ''[dbo].[sysdiagrams]'')
   BEGIN;
       create table #result (result nvarchar(2048) null );
       declare @temp nvarchar(1000);
       set @temp = ''' +  @bcpPath + ' ' + @database + '.dbo.'' +
           substring( ''?'', 8, len(''?'')- 8) +
           '' out "' + @driveLetter + @drivePath +
           '\'' + substring( ''?'', 8, len(''?'')- 8) +
           ''.out" -c -x -t"|" -Uuser -Ppassword'';
       insert into #result (result)
       exec xp_cmdshell @temp;
       drop table #result;
   END;'
   exec sp_msforeachtable @command
</code>```

the @bcppath is C:\Program Files\Microsoft SQL Server\90\Tools\Binn\bcp.exe which has a space.

Without using double quotes around the path "", it gives an error of 'C:\Program' is not recognized...  With using double quotes, it gives the same error.  With using double double quotes "" "", it says The filename, directory name, or volume label syntax is incorrect.

@command resolves to this when printed:

```<code>if ('?' <> '[dbo].[sysdiagrams]')
BEGIN;
    create table #result (result nvarchar(2048) null );
    declare @temp nvarchar(1000);
    set @temp = '"C:\Program Files\Microsoft SQL Server\90\Tools\Binn\bcp.exe"
        myDB.dbo.' +
        substring( '?', 8, len('?')- 8) +
        ' out "E:\DataExports\' +
        substring( '?', 8, len('?')- 8) + '.out" -c -x -t"|" -Uuser -Ppassword';
    insert into #result (result)
    exec xp_cmdshell @temp;
    drop table #result;
END;
</code>```

EDIT:

Oddly, I put an ECHO ? && in front of the "path" and it worked (surrounded by double quotes.)  .... Why?

答:
This weird construction also working:</p>

```<code>exec xp_cmdshell '""%ProgramFiles%\WinRAR\"rar.exe a -v20M "C:\test\test.rar" "C:\test\data\""'
</code>```

Body:
I have this TSQL code that dumps data from tables using BCP.  It looks complicated, but it simply creates a @command string to be executed once for each table, then BCP dump the table records to disk.  It's a nice way to backup all the table data quickly.  Below I show the resolved version which is a little easier to read.

set @command =
  'if (''?'' <> ''[dbo].[sysdiagrams]'')
   BEGIN;
       create table #result (result nvarchar(2048) null );
       declare @temp nvarchar(1000);
       set @temp = ''' +  @bcpPath + ' ' + @database + '.dbo.'' +
           substring( ''?'', 8, len(''?'')- 8) +
           '' out "' + @driveLetter + @drivePath +
           '\'' + substring( ''?'', 8, len(''?'')- 8) +
           ''.out" -c -x -t"|" -Uuser -Ppassword'';
       insert into #result (result)
       exec xp_cmdshell @temp;
       drop table #result;
   END;'
   exec sp_msforeachtable @command

the @bcppath is C:\Program Files\Microsoft SQL Server\90\Tools\Binn\bcp.exe which has a space.

Without using double quotes around the path "", it gives an error of 'C:\Program' is not recognized...  With using double quotes, it gives the same error.  With using double double quotes "" "", it says The filename, directory name, or volume label syntax is incorrect.

@command resolves to this when printed:

if ('?' <> '[dbo].[sysdiagrams]')
BEGIN;
    create table #result (result nvarchar(2048) null );
    declare @temp nvarchar(1000);
    set @temp = '"C:\Program Files\Microsoft SQL Server\90\Tools\Binn\bcp.exe"
        myDB.dbo.' +
        substring( '?', 8, len('?')- 8) +
        ' out "E:\DataExports\' +
        substring( '?', 8, len('?')- 8) + '.out" -c -x -t"|" -Uuser -Ppassword';
    insert into #result (result)
    exec xp_cmdshell @temp;
    drop table #result;
END;

EDIT:

Oddly, I put an ECHO ? && in front of the "path" and it worked (surrounded by double quotes.)  .... Why?

Body:
This weird construction also working:

exec xp_cmdshell '""%ProgramFiles%\WinRAR\"rar.exe a -v20M "C:\test\test.rar" "C:\test\data\""'


问:
Ionic 2 Calendar Event
I want to ask about calendar event in ionic 2.

I have a script like this :
myscript

This script for getting data event from my storage. But, I got this in my console log :
myconsolelog

And event also displays in my browser:
mydisplay

My question is, why my console logs in addschedule.ts 46 not showing data? Because when I am trying in a real device, I cant retrieve my event from local.

答: Line number 46 will be executed first before line number 44 because storage.get() will return promise in future (asynchronous operation). For not retrieving data from real device, we have to see the other part of the code. Also please post the code directly without images</p>

Title: Ionic 2 Calendar Event


问:
How to get the Node's server IP behind a load balancer in Java
I have a webpage behind a load balancer, and I want to display the user (for troubleshooting purposes) the IP of the actual node that the user is connected to (will be the same for a while due to sticky session)

I'm sure it's a very trivial question, but I want to be sure, what Java API should be used for that? will all APIs return me the request host? or will it be server dependent?

答:
InetAddress.getLocalHost().getHostName() will give you the name of the server you are on.
InetAddress.getLocalHost().getHostAddress() will give the IP Address of the server you are on.


问:
How to enable AWS-S3-security policy for files uploaded in S3
I am working on application in which we upload customers' videos, pdfs and other confidential documents on S3 bucket.

Currently, a customer can play these videos in videogular component(Angular component) and PDF files can be read in PDF component.(Angular Component)

My concern is about its security.

I want that customers can play/read only their video/pdf.
No one can download/play/read these things.

1.) How can I achieve that?

2.) Which are the things which I have to enable/disable on my S3 bucket. (S3 Bucket policy)

3.) We do not have IAM roles configured. Do we need it?

I have no clue about this...
It would be great if some one can guide/provide some useful links.

Thanks in advance.

答:
Finally, I got the answer.

Answer of First Question:
What @Cyrus has mentioned in his answer is absolutely correct. Addition to that answer I want to add few more points in it.

as he has rightly mentioned...

when you show the files to your users, the url in the browser must be
  changed so they cannot see the real path to the file.

which gives me hint about CDN(Content Delivery Network) server.

Finally, we would go for CDN-S3 combination.

It means Client would only exposed to CDN url(s). (Not S3 url(s)) And those would be Pre signed URL (Secure as well as temporary url.)

One can read more about from here: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-signed-urls.html

Answer of (2) and (3): as @Cyrus mentioned.


问:
Why is "std::is_pointer<std::nullptr_t>::value" equal to false?
I read about std::is_pointer in C++.

Then I wrote the program and check whether T is a pointer type or not using std::is_pointer.

```<code>#include <iostream>

int main()
{
    std::cout<<std::boolalpha;
    std::cout<<"char : " <<std::is_pointer<char>::value<<std::endl; // OK
    std::cout<<"char * : "<<std::is_pointer<char *>::value<<std::endl; // OK
    std::cout<<"char ** : "<<std::is_pointer<char **>::value<<std::endl; // OK
    std::cout<<"char *** : "<<std::is_pointer<char ***>::value<<std::endl; // OK
    std::cout<<"std::nullptr_t : "<<std::is_pointer<std::nullptr_t>::value<<std::endl;  // Not ok, Why false??
}
</code>```

Output : [Wandbox Demo]

```<code>char : false
char * : true
char ** : true
char *** : true
std::nullptr_t : false
</code>```

Why is std::is_pointer<std::nullptr_t>::value equal to false?

答:
Because std::nullptr_t is not a pointer type itself, but the type of the null pointer literal nullptr.

std::nullptr_t is the type of the null pointer literal, nullptr. It is a distinct type that is not itself a pointer type or a pointer to member type.

From the standard, 21.2.3 Null pointers [support.types.nullptr]

The type nullptr_t is a synonym for the type of a nullptr expression, and it has the characteristics described in [basic.fundamental] and [conv.ptr].

Body:
I read about std::is_pointer in C++.

Then I wrote the program and check whether T is a pointer type or not using std::is_pointer.

#include <iostream>

int main()
{
    std::cout<<std::boolalpha;
    std::cout<<"char : " <<std::is_pointer<char>::value<<std::endl; // OK
    std::cout<<"char * : "<<std::is_pointer<char *>::value<<std::endl; // OK
    std::cout<<"char ** : "<<std::is_pointer<char **>::value<<std::endl; // OK
    std::cout<<"char *** : "<<std::is_pointer<char ***>::value<<std::endl; // OK
    std::cout<<"std::nullptr_t : "<<std::is_pointer<std::nullptr_t>::value<<std::endl;  // Not ok, Why false??
}

Output : [Wandbox Demo]

char : false
char * : true
char ** : true
char *** : true
std::nullptr_t : false

Why is std::is_pointer<std::nullptr_t>::value equal to false?


问:
REST API / DELETE METHOD / Slim Framework v3
I am currently in the process of learning how to buid my own REST API using the Slim Framework v3 for PHP. I found several tutorials and was able to build multiple routes to send GET and POST requests to my MySQL database.
Next up for me is a delete request, but it doesn’t work.

This is my code:

```<code>$app->delete('/usuario/[{correo}]', function ($request, $response, $args) {
  $sth = $this->db->prepare("DELETE FROM usuarios WHERE email=:correo");
  $sth->bindParam("correo", $args['correo']);
  $sth->execute();
  $todos = $sth->fetchAll();
  return $this->response->withJson($todos);
});
</code>```

I’m testing it in Postman and I always have the same problem: 404 Not found.
I can’t understand it because I think the url is correct (http://localhost:8080/usuario/bbb@bbb.es).

Postman view

Can anyone help me?

答:
I think the problem was in the parameter you sent to the route

You can not send dots as a character in your route URL
IF you test

I guess if you test http://localhost:8080/usuario/bbb@bbbdotes
It will work fine

You can send the email address in the body not in the url

```<code>{"email":"bbb@bbbdotes"}
</code>```

And then you can deal with it like POST route to fetch the email address

Body:
I am currently in the process of learning how to buid my own REST API using the Slim Framework v3 for PHP. I found several tutorials and was able to build multiple routes to send GET and POST requests to my MySQL database.
Next up for me is a delete request, but it doesn’t work.

This is my code:

$app->delete('/usuario/[{correo}]', function ($request, $response, $args) {
  $sth = $this->db->prepare("DELETE FROM usuarios WHERE email=:correo");
  $sth->bindParam("correo", $args['correo']);
  $sth->execute();
  $todos = $sth->fetchAll();
  return $this->response->withJson($todos);
});

I’m testing it in Postman and I always have the same problem: 404 Not found.
I can’t understand it because I think the url is correct (http://localhost:8080/usuario/bbb@bbb.es).

Postman view

Can anyone help me?

Body:
I think the problem was in the parameter you sent to the route

You can not send dots as a character in your route URL
IF you test

I guess if you test http://localhost:8080/usuario/bbb@bbbdotes
It will work fine

You can send the email address in the body not in the url

{"email":"bbb@bbbdotes"}

And then you can deal with it like POST route to fetch the email address


问:
How to count distinct values that all satisfy a condition in MySQL?
I'm trying to write a query to find distinct values in a particular field, count the number of occurrences of that value where for all instances of that particular value another column value is satisfied, and then display the results as follows (more explanation to follow):

Example db:

```<code>RowId    Status       MemberIdentifier
-----    ------       ----------------
1       In Progress   111111111
2       Complete      123456789
3       Not Started   146782452
4       Complete      111111111
5       Complete      123456789
6       Not Started   146782452
7       Complete      111111111
</code>```

Desired Result:

```<code>Status         MemberIdentifierCount
------         ----------------------
Not Started    1
In Progress    1
Complete       1
</code>```

In the above query, the number of distinct MemberIdentifiers with a given Status are counted and displayed. If a MemberIdentifier has two rows with Status 'Complete' but one with Status 'In Progress,' it is grouped and counted as in progress (i.e., MemberIdentifier= 111111111). For a MemberIdentifier to be grouped and counted as complete, all of its rows must have a Status of 'Complete' (i.e., MemberIdentifier= 123456789). Any insight would be appreciated (MySQL newbie).

答:
use the following code to get the status of MemberIdentifier

```<code>select MemberIdentifier
,case
when total = cn then 'Complete'
when total < cn then 'In Progress'
when total is null then 'Not Started' END as Fstatus
 from
(
select sum(stat) total,MemberIdentifier,(select count(MemberIdentifier) as cnt from tbldata t1
     where t1.MemberIdentifier = C.MemberIdentifier
     group by MemberIdentifier) as cn
from (
select MemberIdentifier,case status when 'In Progress' then -1
                                    when 'Complete' Then 1
                                    when 'Not Started' then null End as Stat from tbldata
 ) C
 group by MemberIdentifier

 ) as f1
</code>```

use the following code to get the count of MemberIdentifiers in particular status.

```<code>Select count(fstatus) counts,fstatus from (
select MemberIdentifier
,case when total = cn then 'Complete'
      when total < cn then 'In Progress'
      when total is null then 'Not Started' END as Fstatus
 from
(
select sum(stat) total,MemberIdentifier,(select count(MemberIdentifier) as cnt from tbldata t1
     where t1.MemberIdentifier = C.MemberIdentifier
     group by MemberIdentifier) as cn
from (
select MemberIdentifier
,case status when 'In Progress' then -1 when 'Complete' Then 1 when 'Not Started' then null End as Stat from tbldata
 ) C
 group by MemberIdentifier

 ) as f1

 ) f2 group by fstatus
</code>```

output :

```<code>counts  fstatus
1       Complete
1       In Progress
1       Not Started
</code>```

Body:
I'm trying to write a query to find distinct values in a particular field, count the number of occurrences of that value where for all instances of that particular value another column value is satisfied, and then display the results as follows (more explanation to follow):

Example db:

RowId    Status       MemberIdentifier
-----    ------       ----------------
1       In Progress   111111111
2       Complete      123456789
3       Not Started   146782452
4       Complete      111111111
5       Complete      123456789
6       Not Started   146782452
7       Complete      111111111

Desired Result:

Status         MemberIdentifierCount
------         ----------------------
Not Started    1
In Progress    1
Complete       1

In the above query, the number of distinct MemberIdentifiers with a given Status are counted and displayed. If a MemberIdentifier has two rows with Status 'Complete' but one with Status 'In Progress,' it is grouped and counted as in progress (i.e., MemberIdentifier= 111111111). For a MemberIdentifier to be grouped and counted as complete, all of its rows must have a Status of 'Complete' (i.e., MemberIdentifier= 123456789). Any insight would be appreciated (MySQL newbie).

Body:
use the following code to get the status of MemberIdentifier

select MemberIdentifier
,case
when total = cn then 'Complete'
when total < cn then 'In Progress'
when total is null then 'Not Started' END as Fstatus
 from
(
select sum(stat) total,MemberIdentifier,(select count(MemberIdentifier) as cnt from tbldata t1
     where t1.MemberIdentifier = C.MemberIdentifier
     group by MemberIdentifier) as cn
from (
select MemberIdentifier,case status when 'In Progress' then -1
                                    when 'Complete' Then 1
                                    when 'Not Started' then null End as Stat from tbldata
 ) C
 group by MemberIdentifier

 ) as f1

use the following code to get the count of MemberIdentifiers in particular status.

Select count(fstatus) counts,fstatus from (
select MemberIdentifier
,case when total = cn then 'Complete'
      when total < cn then 'In Progress'
      when total is null then 'Not Started' END as Fstatus
 from
(
select sum(stat) total,MemberIdentifier,(select count(MemberIdentifier) as cnt from tbldata t1
     where t1.MemberIdentifier = C.MemberIdentifier
     group by MemberIdentifier) as cn
from (
select MemberIdentifier
,case status when 'In Progress' then -1 when 'Complete' Then 1 when 'Not Started' then null End as Stat from tbldata
 ) C
 group by MemberIdentifier

 ) as f1

 ) f2 group by fstatus

output :

counts  fstatus
1       Complete
1       In Progress
1       Not Started


问:
Jersey 2 client for StreamingOutput
I have a Jersey service that output binary data as StreamingOutput,  MediaType.APPLICATION_OCTET_STREAM.

How to implement a client using Jersey 2 for handling the response from such service?

答:
Below is one way of implementing Jersey 2 client for downloading a file from a REST service which is returning binary data as StreamingOutput with MediaType.APPLICATION_OCTET_STREAM -

```<code>    Client client = ClientBuilder.newClient();
    // change SERVER_URL, API_PATH and PATH as per REST API details
    WebTarget webTarget = client.target(SERVER_URL).path(API_PATH).path(PATH);

    Invocation.Builder invocationBuilder = webTarget.request();
    Response response = invocationBuilder.get();

    String contentDispositionHeader = response.getHeaderString("Content-Disposition");
    String fileName = contentDispositionHeader
            .substring(contentDispositionHeader.indexOf("filename=") + "filename=".length()).replace("\"", "");

    InputStream responseStream = response.readEntity(InputStream.class);

    // Set location here where you want to store downloaded file.
    // It will replace the file if already exist in that location with same name.
    Files.copy(responseStream, Paths.get("H:/"+ fileName), StandardCopyOption.REPLACE_EXISTING);

    System.out.println("File is downloaded");
</code>```

Title: Jersey 2 client for StreamingOutput

Body:
Below is one way of implementing Jersey 2 client for downloading a file from a REST service which is returning binary data as StreamingOutput with MediaType.APPLICATION_OCTET_STREAM -

    Client client = ClientBuilder.newClient();
    // change SERVER_URL, API_PATH and PATH as per REST API details
    WebTarget webTarget = client.target(SERVER_URL).path(API_PATH).path(PATH);

    Invocation.Builder invocationBuilder = webTarget.request();
    Response response = invocationBuilder.get();

    String contentDispositionHeader = response.getHeaderString("Content-Disposition");
    String fileName = contentDispositionHeader
            .substring(contentDispositionHeader.indexOf("filename=") + "filename=".length()).replace("\"", "");

    InputStream responseStream = response.readEntity(InputStream.class);

    // Set location here where you want to store downloaded file.
    // It will replace the file if already exist in that location with same name.
    Files.copy(responseStream, Paths.get("H:/"+ fileName), StandardCopyOption.REPLACE_EXISTING);

    System.out.println("File is downloaded");


问:
BotFramework: Create Suggested Actions without text attribute
I'm creating a bot in DirectLine. I'm trying to use SuggestedActions to display a suggested action and I don't want to include the text attribute for that. When I try to run my code without the text attribute, I see a blank message being displayed. How can I avoid that?

My code

```<code>var msg = new builder.Message(session)
            .suggestedActions(
               builder.SuggestedActions.create(
                    session, [
                         builder.CardAction.imBack(session, "disconnect", "Disconnect"),
                     ]
             ));
session.send(msg);
</code>```

The Output i'm getting:

答:
Per my understanding, you want a button which is shown absoluted at bottom and always display to remind your agent that he can disconnect conversation any time.

However, per me testing and understanding, in my opinion, there 2 points that it's maybe not a good idea to achieve this feature:

SuggestedAction is based on Messasge in Bot framework. And basically Bot application is for conversation. So every message between user and bot renderred in different channels should always be contained in a textbox, shown like in your capture. We cannot bypass this feature.

Per your requirements, I think you want this button should be always display unless the agent click it. But I didn't find any feature like this in Bot framework, and you may need to send this meesage additionally beside every message from bot, which is not graceful and will raise unpredictable risk.

My suggestion is that you can create a triggerAction to handle global disconnect requests. Refer https://learn.microsoft.com/en-us/bot-framework/nodejs/bot-builder-nodejs-dialog-actions for more info.

Body:
I'm creating a bot in DirectLine. I'm trying to use SuggestedActions to display a suggested action and I don't want to include the text attribute for that. When I try to run my code without the text attribute, I see a blank message being displayed. How can I avoid that?

My code

var msg = new builder.Message(session)
            .suggestedActions(
               builder.SuggestedActions.create(
                    session, [
                         builder.CardAction.imBack(session, "disconnect", "Disconnect"),
                     ]
             ));
session.send(msg);

The Output i'm getting:


答:
Because it's not a pointer type. It's a distinct type that is implicitly convertible to any pointer type.

As the note in [lex.nullptr] summarizes:

The pointer literal is the keyword nullptr. It is a prvalue of type
  std::nullptr_t. [ Note: std::nullptr_t is a distinct type that
  is neither a pointer type nor a pointer to member type; rather, a
  prvalue of this type is a null pointer constant and can be converted
  to a null pointer value or null member pointer value. See [conv.ptr]
  and [conv.mem].  — end note ]

Title: Why is "std::is_pointer<std::nullptr_t>::value" equal to false?


问:
Swift understanding self[key] and casting
Please consider following code:

```<code>extension Dictionary {
    public func msArray(_ key: Key) -> [Dictionary<String, Any>] {
        return (self[key] as? Array<[String : Int]> ?? [])
    }
}

let dict = ["Warlock" : ["Hp" : 100],  "Rogue" : ["Hp" : 150], "Warrior" : ["Hp" : 250]]
</code>```

Following produce []:

```<code>print(dict.msArray("Warlock"))
</code>```

Why? Isn't it suppose to print ["Hp" : 100]?

答:
```<code>return (self[key] as? Array<[String : Int]> ?? [])
</code>```

Here you are casting self[key] as an array, when it's actually a Dictionary, this is why it fails and the default value [] is returned.

You can fix it this way:

```<code>extension Dictionary {
    public func msArray(_ key: Key) -> [Dictionary<String, Any>] {
        return ([self[key]] as? Array<[String : Any]> ?? [])
    }
}
</code>```

Body:
Please consider following code:

extension Dictionary {
    public func msArray(_ key: Key) -> [Dictionary<String, Any>] {
        return (self[key] as? Array<[String : Int]> ?? [])
    }
}

let dict = ["Warlock" : ["Hp" : 100],  "Rogue" : ["Hp" : 150], "Warrior" : ["Hp" : 250]]

Following produce []:

print(dict.msArray("Warlock"))

Why? Isn't it suppose to print ["Hp" : 100]?

Body:
return (self[key] as? Array<[String : Int]> ?? [])

Here you are casting self[key] as an array, when it's actually a Dictionary, this is why it fails and the default value [] is returned.

You can fix it this way:

extension Dictionary {
    public func msArray(_ key: Key) -> [Dictionary<String, Any>] {
        return ([self[key]] as? Array<[String : Any]> ?? [])
    }
}


答:
Because std::nullptr_t is not a pointer type. And is_pointer only evaluates to true for pointer types.

nullptr_t is convertible to a pointer, but it isn't a pointer. Indeed, nullptr_t is not a class type, integral, floating-point, enumerator, or any kind of type other than is_null_pointer type. It has its own unique classification in the categorization of types.


问:
Django ORM: Tried to do inner join with foreign key but causes FieldError
I am new to django orm.
I've tables look like this.

```<code>class Product(models.Model):
   id = models.UUIDField(primary_key=True, default=uuid.uuid4)
   name = models.CharField(max_length=60)

class ProductOption(models.Model):
   id = models.UUIDField(primary_key=True, default=uuid.uuid4)
   product_id = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True)
</code>```

I would like to query productoption id that related to product. I made query like this to do inner join.

```<code>Query = Product.select_related(‘product_id’).filter(name='a')
</code>```

And it gaves me error message saying

```<code>django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'product_id'. Choices are: (none)
</code>```

I want to know if there is something wrong in models or query.

答:
Use prefetch_related</p>

```<code>Product.objects.filter(name='a').prefetch_related('productoption_set')
</code>```

Body:
I am new to django orm.
I've tables look like this.

class Product(models.Model):
   id = models.UUIDField(primary_key=True, default=uuid.uuid4)
   name = models.CharField(max_length=60)

class ProductOption(models.Model):
   id = models.UUIDField(primary_key=True, default=uuid.uuid4)
   product_id = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True)

I would like to query productoption id that related to product. I made query like this to do inner join.

Query = Product.select_related(‘product_id’).filter(name='a')

And it gaves me error message saying

django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'product_id'. Choices are: (none)

I want to know if there is something wrong in models or query.

Body:
Use prefetch_related

Product.objects.filter(name='a').prefetch_related('productoption_set')


问:
What is the meaning of the word logits in TensorFlow?
In the following TensorFlow function, we must feed the activation of artificial neurons in the final layer. That I understand. But I don't understand why it is called logits? Isn't that a mathematical function? </p>

```<code>loss_function = tf.nn.softmax_cross_entropy_with_logits(
     logits = last_layer,
     labels = target_output
)
</code>```

答:
They are basically the fullest learned model you can get from the network, before it's been squashed down to apply to only the number of classes we are interested in.  Check out how some researchers use them to train a shallow neural net based on what a deep network has learned:  https://arxiv.org/pdf/1312.6184.pdf

It's kind of like how when learning a subject in detail, you will learn a great many minor points, but then when teaching a student, you will try to compress it to the simplest case.  If the student now tried to teach, it'd be quite difficult, but would be able to describe it just well enough to use the language.

Body:
In the following TensorFlow function, we must feed the activation of artificial neurons in the final layer. That I understand. But I don't understand why it is called logits? Isn't that a mathematical function?

loss_function = tf.nn.softmax_cross_entropy_with_logits(
     logits = last_layer,
     labels = target_output
)


问:
Where i should store a UI configuration for each user
i developed the aspnet mvc app with knockoutjs and i make the grid with data. that grid have the configuration like: which column should be visible and it size also grid can generate filters on json which handle on server and making remoting sorting\filtering\ordering and users can make the own presets of filters and settings. question, where the store it? i store it in cookies and on mssql but
i heard that is bad practice. how to be

P.S trying to avoid a lot of requests to the server.

答:
You can use local or session storage, described here.

localStorage usage example:

```<code>// Store localStorage.setItem("lastname", "Smith"); // Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
</code>```

sessionStorage usage example:

```<code>if (sessionStorage.clickcount) {
    sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
    sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";
</code>```

Body:
You can use local or session storage, described here.

localStorage usage example:

// Store localStorage.setItem("lastname", "Smith"); // Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");

sessionStorage usage example:

if (sessionStorage.clickcount) {
    sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
    sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";


问:
Swift 4 - Editing label frame.size.height with negative number
So I have a label that I've made in Xcode's storyboard which I want to later edit in my code. I want it to simulate something like a vertical bar so I am editing its height by doing:

```<code>answerE.frame.size.height = -200
</code>```

The problem comes from the negative number, I want the label to "grow" up so the height has to be negative from its original position... I have the line in code in a simple action on button press, but each time the line is executed the label moves "up" and eventually after 3-4 clicks is out of the screen.
I just want to edit its height, what is the correct way and what am I doing wrong?

My exact line in code is:

```<code>label.frame.size.height = -CGFloat(Double(x)/Double(y) * (200))
</code>```

答:
If you have added the label in storyboard, why not you use constraints to get the result.

Add leading, trailing , bottom and fixed height constraint and connect IBOutlet to height constraint. Change the constant value of height constraint at the event which you want to perform.

Body:
So I have a label that I've made in Xcode's storyboard which I want to later edit in my code. I want it to simulate something like a vertical bar so I am editing its height by doing:

answerE.frame.size.height = -200

The problem comes from the negative number, I want the label to "grow" up so the height has to be negative from its original position... I have the line in code in a simple action on button press, but each time the line is executed the label moves "up" and eventually after 3-4 clicks is out of the screen.
I just want to edit its height, what is the correct way and what am I doing wrong?

My exact line in code is:

label.frame.size.height = -CGFloat(Double(x)/Double(y) * (200))


问:
How to merge 2 xpath in one
Html

```<code><li class="wdappchrome-ai" data-automation-id="searchInputAutoCompleteResult" tabindex="-2" aria-posinset="1" aria-setsize="3">
<span data-automation-id="searchInputAutoCompleteResultFullText">
    <span style="font-weight:500">
        <span data-automation-id="searchInputAutoCompleteResultToken" style="font-weight:400">mike</span>
        <span data-automation-id="searchInputAutoCompleteResultToken" style="font-weight:400">diana</span>
    </span>
</span>
</li>
</code>```

I am getting user full name divided into spans so I want to build xpath which returns me combine text of both/multiple span from single list.

For now I am using 2 or more xpath based on name of user divided into span.

I use : //li[.//span[text()='mike']]  //li[.//span[text()='diana']]

Then I do gettext() for above both xpath and merge using java grammatically. So I am looking for solution which give me full text of all span within particular li tag from above.

答:
Try below XPath to match element by one of the spans:

```<code>//li[.//span='diana' or .//span='mike']
</code>```

or by both spans:

```<code>//li[.//span='diana' and .//span='mike']
</code>```

Title: How to merge 2 xpath in one

Body:
Html

        mike
        diana

I am getting user full name divided into spans so I want to build xpath which returns me combine text of both/multiple span from single list.

For now I am using 2 or more xpath based on name of user divided into span.

I use : //li[.//span[text()='mike']]  //li[.//span[text()='diana']]

Then I do gettext() for above both xpath and merge using java grammatically. So I am looking for solution which give me full text of all span within particular li tag from above.

Body:
Try below XPath to match element by one of the spans:

//li[.//span='diana' or .//span='mike']

or by both spans:

//li[.//span='diana' and .//span='mike']