问:
SAML Java Sping Boot - PKIX path construction failed for untrusted credential
Running into this issue setting up SAML 2.0 in Java Spring Boot using latest libraries.

I followed this guide:
https://www.programcreek.com/java-api-examples/?code=choonchernlim%2Fspring-security-adfs-saml2%2Fspring-security-adfs-saml2-master

Here's some relevant code, but let me know if anything else will help:

```<code>    @Bean
    public KeyManager keyManager()
    {
        return new JKSKeyManager(keyStoreResource, keystorePassword, ImmutableMap.of(keystoreKeyAlias, keystorePrivateKeyPassword), keystoreKeyAlias);
    }

    @Bean
    public SAMLDiscovery samlIDPDiscovery()
    {
        return new SAMLDiscovery();
    }

    @Bean
    public MetadataDisplayFilter metadataDisplayFilter()
    {
        return new MetadataDisplayFilter();
    }

    @Bean
    public TLSProtocolConfigurer tlsProtocolConfigurer()
    {
        TLSProtocolConfigurer t = new TLSProtocolConfigurer();
        //t.setSslHostnameVerification("allowAll");
        return t;
    }

    // Configure TLSProtocolConfigurer
    @Bean
    public ProtocolSocketFactory protocolSocketFactory()
    {
        //return new TLSProtocolSocketFactory(keyManager(), null, "defaultAndLocalhost");
        return new TLSProtocolSocketFactory(keyManager(), null, "default");
    }

    @Bean
    public Protocol protocol()
    {
        return new Protocol("https", protocolSocketFactory(), 443);
    }

    @Bean
    public MethodInvokingFactoryBean socketFactoryInitialization()
    {
        MethodInvokingFactoryBean methodInvokingFactoryBean = new MethodInvokingFactoryBean();
        methodInvokingFactoryBean.setTargetClass(Protocol.class);
        methodInvokingFactoryBean.setTargetMethod("registerProtocol");
        methodInvokingFactoryBean.setArguments(new Object[] { "https", protocol() });
        return methodInvokingFactoryBean;
    }

    @Bean
    public CachingMetadataManager metadata() throws MetadataProviderException
    {
        HTTPMetadataProvider httpMetadataProvider = new HTTPMetadataProvider(new Timer(true), httpClient(), idpUrl);
        httpMetadataProvider.setParserPool(parserPool());

        //ExtendedMetadata em = new ExtendedMetadata(); //Attempt to explicitly add cert alias to extended metadata
        //em.setAlias(keystoreCertAlias);
        //em.setSigningKey("*.product.company.com");

        ExtendedMetadataDelegate extendedMetadataDelegate = new ExtendedMetadataDelegate(httpMetadataProvider);//, em);

        extendedMetadataDelegate.setMetadataTrustCheck(false);

        return new CachingMetadataManager(ImmutableList.<MetadataProvider>of(extendedMetadataDelegate));
    }
</code>```

Here's the error:

```<code>2020-05-27 17:02:27.552 ERROR 41402 --- [           main] o.s.s.s.t.MetadataCredentialResolver     : PKIX path construction failed for untrusted credential: [subjectName='CN=*.product.company.com,O=Company,L=Location,ST=state,C=US']: unable to find valid certification path to requested target
2020-05-27 17:02:27.556  INFO 41402 --- [           main] o.a.c.httpclient.HttpMethodDirector      : I/O exception (javax.net.ssl.SSLPeerUnverifiedException) caught when processing request: SSL peer failed hostname validation for name: null
2020-05-27 17:02:27.557  INFO 41402 --- [           main] o.a.c.httpclient.HttpMethodDirector      : Retrying request
...

javax.net.ssl.SSLPeerUnverifiedException: SSL peer failed hostname validation for name: null
    at org.opensaml.ws.soap.client.http.TLSProtocolSocketFactory.verifyHostname(TLSProtocolSocketFactory.java:233) ~[openws-1.5.4.jar:na]
    at org.opensaml.ws.soap.client.http.TLSProtocolSocketFactory.createSocket(TLSProtocolSocketFactory.java:186) ~[openws-1.5.4.jar:na]
    at org.springframework.security.saml.trust.httpclient.TLSProtocolSocketFactory.createSocket(TLSProtocolSocketFactory.java:97) ~[spring-security-saml2-core-1.0.10.RELEASE.jar:1.0.10.RELEASE]
    at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707) ~[commons-httpclient-3.1.jar:na]
    at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1361) ~[commons-httpclient-3.1.jar:na]
    at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387) ~[commons-httpclient-3.1.jar:na]
    at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) ~[commons-httpclient-3.1.jar:na]
    at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) ~[commons-httpclient-3.1.jar:na]
    at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323) ~[commons-httpclient-3.1.jar:na]
    at org.opensaml.saml2.metadata.provider.HTTPMetadataProvider.fetchMetadata(HTTPMetadataProvider.java:250) ~[opensaml-2.6.4.jar:na]
    at org.opensaml.saml2.metadata.provider.AbstractReloadingMetadataProvider.refresh(AbstractReloadingMetadataProvider.java:255) [opensaml-2.6.4.jar:na]
    at org.opensaml.saml2.metadata.provider.AbstractReloadingMetadataProvider.doInitialization(AbstractReloadingMetadataProvider.java:236) [opensaml-2.6.4.jar:na]
    at org.opensaml.saml2.metadata.provider.AbstractMetadataProvider.initialize(AbstractMetadataProvider.java:407) [opensaml-2.6.4.jar:na]
    at org.springframework.security.saml.metadata.ExtendedMetadataDelegate.initialize(ExtendedMetadataDelegate.java:167) [spring-security-saml2-core-1.0.10.RELEASE.jar:1.0.10.RELEASE]
    at com.company.product.ProductApplication.main(ProductApplication.java:10) ~[classes/:na]
</code>```

Creating the JKS keystore like so (with an attached key):

```<code>keytool -genkeypair \
 -v \
 -keystore product.jks \
 -storepass hidden \
 -alias product \
 -dname 'CN=localhost, OU=Company, O=Org, L=Loc, ST=State, C=US' \
 -keypass hidden \
 -keyalg RSA \
 -keysize 2048 \
 -sigalg SHA256withRSA
</code>```

I included the cert as well:
Signature trust establishment failed for SAML metadata entry
The certificate provided by my IDP is contained within my keystore:

```<code>keytool -importcert \
  -file cert.pem \
  -keystore product.jks \
  -alias idp-server \
  -storepass hidden
</code>```

I tried all the following tickets already:

SSL peer failed hostname validation in Spring SAML
Tried to add the cert included in the passwords in KeyManager (I set the cert password to be the keystore password since the cert does not have one)

Spring Security SAML + HTTPS to another page
Tried allowAll in TLSProtocolConfigurer.setSslHostnameVerification and defaultAndLocalhost in TLSProtocolSocketFactory constructor.

Spring Security SAML IdP Metadata Certificate and Signature
Trust check is already disabled:
extendedMetadataDelegate.setMetadataTrustCheck(false);

Signature trust establishment failed for SAML metadata entry
Tried setting the alias of the cert inside the ExtendedMetadata attached to the delegate:

```<code>ExtendedMetadata em = new ExtendedMetadata();
em.setAlias(keystoreCertAlias);
em.setSigningKey("*.product.company.com"); //This is obfuscated
ExtendedMetadataDelegate extendedMetadataDelegate = new ExtendedMetadataDelegate(httpMetadataProvider, em);
</code>```

My inclination is that I'm setting up the keystore incorrectly with the cert. I tried converted the PEM to crt and cer to see if it would make any difference, it did not. I can assure you this is the IDP cert and not the domain cert (FYI this is purposefully not using cacerts, but containing the cert inside the keystore to use HTTPS).

Any ideas/help is much appreciated!
Thanks.

答:
To fix this, I dropped the tlsProtocolConfigurer bean and all beans associated to it. I'm not entirely sure why the sample included this as it works perfectly fine with HTTPS (and localhost) without it.

Note:
I'm assuming the actual issue was that the tlsProtocolConfigurer wasn't finding the certificate in the keystore, but for my app, the entire bean is not necessary so it became a moot point.

Body:
Running into this issue setting up SAML 2.0 in Java Spring Boot using latest libraries.

I followed this guide:
https://www.programcreek.com/java-api-examples/?code=choonchernlim%2Fspring-security-adfs-saml2%2Fspring-security-adfs-saml2-master

Here's some relevant code, but let me know if anything else will help:

    @Bean
    public KeyManager keyManager()
    {
        return new JKSKeyManager(keyStoreResource, keystorePassword, ImmutableMap.of(keystoreKeyAlias, keystorePrivateKeyPassword), keystoreKeyAlias);
    }

    @Bean
    public SAMLDiscovery samlIDPDiscovery()
    {
        return new SAMLDiscovery();
    }

    @Bean
    public MetadataDisplayFilter metadataDisplayFilter()
    {
        return new MetadataDisplayFilter();
    }

    @Bean
    public TLSProtocolConfigurer tlsProtocolConfigurer()
    {
        TLSProtocolConfigurer t = new TLSProtocolConfigurer();
        //t.setSslHostnameVerification("allowAll");
        return t;
    }

    // Configure TLSProtocolConfigurer
    @Bean
    public ProtocolSocketFactory protocolSocketFactory()
    {
        //return new TLSProtocolSocketFactory(keyManager(), null, "defaultAndLocalhost");
        return new TLSProtocolSocketFactory(keyManager(), null, "default");
    }

    @Bean
    public Protocol protocol()
    {
        return new Protocol("https", protocolSocketFactory(), 443);
    }

    @Bean
    public MethodInvokingFactoryBean socketFactoryInitialization()
    {
        MethodInvokingFactoryBean methodInvokingFactoryBean = new MethodInvokingFactoryBean();
        methodInvokingFactoryBean.setTargetClass(Protocol.class);
        methodInvokingFactoryBean.setTargetMethod("registerProtocol");
        methodInvokingFactoryBean.setArguments(new Object[] { "https", protocol() });
        return methodInvokingFactoryBean;
    }

    @Bean
    public CachingMetadataManager metadata() throws MetadataProviderException
    {
        HTTPMetadataProvider httpMetadataProvider = new HTTPMetadataProvider(new Timer(true), httpClient(), idpUrl);
        httpMetadataProvider.setParserPool(parserPool());

        //ExtendedMetadata em = new ExtendedMetadata(); //Attempt to explicitly add cert alias to extended metadata
        //em.setAlias(keystoreCertAlias);
        //em.setSigningKey("*.product.company.com");

        ExtendedMetadataDelegate extendedMetadataDelegate = new ExtendedMetadataDelegate(httpMetadataProvider);//, em);

        extendedMetadataDelegate.setMetadataTrustCheck(false);

        return new CachingMetadataManager(ImmutableList.<MetadataProvider>of(extendedMetadataDelegate));
    }

Here's the error:

2020-05-27 17:02:27.552 ERROR 41402 --- [           main] o.s.s.s.t.MetadataCredentialResolver     : PKIX path construction failed for untrusted credential: [subjectName='CN=*.product.company.com,O=Company,L=Location,ST=state,C=US']: unable to find valid certification path to requested target
2020-05-27 17:02:27.556  INFO 41402 --- [           main] o.a.c.httpclient.HttpMethodDirector      : I/O exception (javax.net.ssl.SSLPeerUnverifiedException) caught when processing request: SSL peer failed hostname validation for name: null
2020-05-27 17:02:27.557  INFO 41402 --- [           main] o.a.c.httpclient.HttpMethodDirector      : Retrying request
...

javax.net.ssl.SSLPeerUnverifiedException: SSL peer failed hostname validation for name: null
    at org.opensaml.ws.soap.client.http.TLSProtocolSocketFactory.verifyHostname(TLSProtocolSocketFactory.java:233) ~[openws-1.5.4.jar:na]
    at org.opensaml.ws.soap.client.http.TLSProtocolSocketFactory.createSocket(TLSProtocolSocketFactory.java:186) ~[openws-1.5.4.jar:na]
    at org.springframework.security.saml.trust.httpclient.TLSProtocolSocketFactory.createSocket(TLSProtocolSocketFactory.java:97) ~[spring-security-saml2-core-1.0.10.RELEASE.jar:1.0.10.RELEASE]
    at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707) ~[commons-httpclient-3.1.jar:na]
    at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1361) ~[commons-httpclient-3.1.jar:na]
    at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387) ~[commons-httpclient-3.1.jar:na]
    at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) ~[commons-httpclient-3.1.jar:na]
    at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) ~[commons-httpclient-3.1.jar:na]
    at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323) ~[commons-httpclient-3.1.jar:na]
    at org.opensaml.saml2.metadata.provider.HTTPMetadataProvider.fetchMetadata(HTTPMetadataProvider.java:250) ~[opensaml-2.6.4.jar:na]
    at org.opensaml.saml2.metadata.provider.AbstractReloadingMetadataProvider.refresh(AbstractReloadingMetadataProvider.java:255) [opensaml-2.6.4.jar:na]
    at org.opensaml.saml2.metadata.provider.AbstractReloadingMetadataProvider.doInitialization(AbstractReloadingMetadataProvider.java:236) [opensaml-2.6.4.jar:na]
    at org.opensaml.saml2.metadata.provider.AbstractMetadataProvider.initialize(AbstractMetadataProvider.java:407) [opensaml-2.6.4.jar:na]
    at org.springframework.security.saml.metadata.ExtendedMetadataDelegate.initialize(ExtendedMetadataDelegate.java:167) [spring-security-saml2-core-1.0.10.RELEASE.jar:1.0.10.RELEASE]
    at com.company.product.ProductApplication.main(ProductApplication.java:10) ~[classes/:na]

Creating the JKS keystore like so (with an attached key):

keytool -genkeypair \
 -v \
 -keystore product.jks \
 -storepass hidden \
 -alias product \
 -dname 'CN=localhost, OU=Company, O=Org, L=Loc, ST=State, C=US' \
 -keypass hidden \
 -keyalg RSA \
 -keysize 2048 \
 -sigalg SHA256withRSA

I included the cert as well:
Signature trust establishment failed for SAML metadata entry
The certificate provided by my IDP is contained within my keystore:

keytool -importcert \
  -file cert.pem \
  -keystore product.jks \
  -alias idp-server \
  -storepass hidden

I tried all the following tickets already:

SSL peer failed hostname validation in Spring SAML
Tried to add the cert included in the passwords in KeyManager (I set the cert password to be the keystore password since the cert does not have one)

Spring Security SAML + HTTPS to another page
Tried allowAll in TLSProtocolConfigurer.setSslHostnameVerification and defaultAndLocalhost in TLSProtocolSocketFactory constructor.

Spring Security SAML IdP Metadata Certificate and Signature
Trust check is already disabled:
extendedMetadataDelegate.setMetadataTrustCheck(false);

Signature trust establishment failed for SAML metadata entry
Tried setting the alias of the cert inside the ExtendedMetadata attached to the delegate:

ExtendedMetadata em = new ExtendedMetadata();
em.setAlias(keystoreCertAlias);
em.setSigningKey("*.product.company.com"); //This is obfuscated
ExtendedMetadataDelegate extendedMetadataDelegate = new ExtendedMetadataDelegate(httpMetadataProvider, em);

My inclination is that I'm setting up the keystore incorrectly with the cert. I tried converted the PEM to crt and cer to see if it would make any difference, it did not. I can assure you this is the IDP cert and not the domain cert (FYI this is purposefully not using cacerts, but containing the cert inside the keystore to use HTTPS).

Any ideas/help is much appreciated!
Thanks.


来源: stackexchange

问:
Why isn't button changing from x to y in react?
I am trying to make a button that toggles between x and y. However, the following code isn't working. Why isn't this working? Sorry if it is an easy solution, I am new to react.

Right now, all that is appearing is a button that says X, and when I try to click it, nothing changes.

```<code>  constructor(props) {
    super(props);
    this.myValue = 2
  }

  buttonIsClicked() {
    this.myValue+=1
    this.render()
  }

  render() {
    switch(this.myValue%2) {
      case 0:
        return(
        <button className = "myButton" onClick={() => this.buttonIsClicked()}>X</button>
        );
      case 1:
        return(
        <button className = "myButton" onClick={() => this.buttonIsClicked()}>Y</button>
        );
    }
  }
</code>```

答:
React uses state to determine changes in its components. Check the official documentation to learn more about the lifecycle and state management: https://reactjs.org/docs/state-and-lifecycle.html</p>

```<code> constructor(props) {
   super(props);
   // init the state
   this.state = { myValue: 2 };
 }

 buttonIsClicked() {
   // accessing state
   const lastValue = this.state.myValue;
   // updating state which will trigger rendering
   this.setState({ myValue: lastValue + 1 });
 }

 render() {
   switch(this.state.myValue%2) {
     case 0:
       return(
       <button className = "myButton" onClick={() => this.buttonIsClicked()}>X</button>
       );
     case 1:
       return(
       <button className = "myButton" onClick={() => this.buttonIsClicked()}>Y</button>
       );
   }
 }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to make a button that toggles between x and y. However, the following code isn't working. Why isn't this working? Sorry if it is an easy solution, I am new to react.

Right now, all that is appearing is a button that says X, and when I try to click it, nothing changes.

  constructor(props) {
    super(props);
    this.myValue = 2
  }

  buttonIsClicked() {
    this.myValue+=1
    this.render()
  }

  render() {
    switch(this.myValue%2) {
      case 0:
        return(
        <button className = "myButton" onClick={() => this.buttonIsClicked()}>X</button>
        );
      case 1:
        return(
        <button className = "myButton" onClick={() => this.buttonIsClicked()}>Y</button>
        );
    }
  }

Body:
React uses state to determine changes in its components. Check the official documentation to learn more about the lifecycle and state management: https://reactjs.org/docs/state-and-lifecycle.html

 constructor(props) {
   super(props);
   // init the state
   this.state = { myValue: 2 };
 }

 buttonIsClicked() {
   // accessing state
   const lastValue = this.state.myValue;
   // updating state which will trigger rendering
   this.setState({ myValue: lastValue + 1 });
 }

 render() {
   switch(this.state.myValue%2) {
     case 0:
       return(
       <button className = "myButton" onClick={() => this.buttonIsClicked()}>X</button>
       );
     case 1:
       return(
       <button className = "myButton" onClick={() => this.buttonIsClicked()}>Y</button>
       );
   }
 }


问:
If you can decode JWT, how are they secure?
If I get a JWT and I can decode the payload, how is that secure? Couldn't I just grab the token out of the header, decode and change the user information in the payload, and send it back with the same correct encoded secret?

I know they must be secure, but I just would really like to understand the technologies. What am I missing?

答:
Let's discuss from the very beginning:

JWT is a very modern, simple and secure approach which extends for Json Web Tokens. Json Web Tokens are a stateless solution for authentication. So there is no need to store any session state on the server, which of course is perfect for restful APIs.
Restful APIs should always be stateless, and the most widely used alternative to authentication with JWTs is to just store the user's log-in state on the server using sessions. But then of course does not follow the principle that says that restful APIs should be stateless and that's why solutions like JWT became popular and effective.

So now let's know how authentication actually works with Json Web Tokens. Assuming we already have a registered user in our database. So the user's client starts by making a post request with the username and the password, the application then checks if the user exists and if the password is correct, then the application will generate a unique Json Web Token for only that user.

The token is created using a secret string that is stored on a server. Next, the server then sends that JWT back to the client which will store it either in a cookie or in local storage.

Just like this, the user is authenticated and basically logged into our application without leaving any state on the server.

So the server does in fact not know which user is actually logged in, but of course, the user knows that he's logged in because he has a valid Json Web Token which is a bit like a passport to access protected parts of the application.

So again, just to make sure you got the idea. A user is logged in as soon as he gets back his unique valid Json Web Token which is not saved anywhere on the server. And so this process is therefore completely stateless.

Then, each time a user wants to access a protected route like his user profile data, for example. He sends his Json Web Token along with a request, so it's a bit like showing his passport to get access to that route.

Once the request hits the server, our app will then verify if the Json Web Token is actually valid and if the user is really who he says he is, well then the requested data will be sent to the client and if not, then there will be an error telling the user that he's not allowed to access that resource.

All this communication must happen over https, so secure encrypted Http in order to prevent that anyone can get access to passwords or Json Web Tokens. Only then we have a really secure system.

So a Json Web Token looks like left part of this screenshot which was taken from the JWT debugger at jwt.io. So essentially, it's an encoding string made up of three parts. The header, the payload and the signature Now the header is just some metadata about the token itself and the payload is the data that we can encode into the token, any data really that we want. So the more data we want to encode here the bigger the JWT. Anyway, these two parts are just plain text that will get encoded, but not encrypted.

So anyone will be able to decode them and to read them, we cannot store any sensitive data in here. But that's not a problem at all because in the third part, so in the signature, is where things really get interesting. The signature is created using the header, the payload, and the secret that is saved on the server.

And this whole process is then called signing the Json Web Token. The signing algorithm takes the header, the payload, and the secret to create a unique signature. So only this data plus the secret can create this signature, all right?
Then together with the header and the payload, these signature forms the JWT,
which then gets sent to the client.

Once the server receives a JWT to grant access to a protected route, it needs to verify it in order to determine if the user really is who he claims to be. In other words, it will verify if no one changed the header and the payload data of the token. So again, this verification step will check if no third party actually altered either the header or the payload of the Json Web Token.

So, how does this verification actually work? Well, it is actually quite straightforward. Once the JWT is received, the verification will take its header and payload, and together with the secret that is still saved on the server, basically create a test signature.

But the original signature that was generated when the JWT was first created is still in the token, right? And that's the key to this verification. Because now all we have to do is to compare the test signature with the original signature.
And if the test signature is the same as the original signature, then it means that the payload and the header have not been modified.

Because if they had been modified, then the test signature would have to be different. Therefore in this case where there has been no alteration of the data, we can then authenticate the user. And of course, if the two signatures
are actually different, well, then it means that someone tampered with the data.
Usually by trying to change the payload. But that third party manipulating the payload does of course not have access to the secret, so they cannot sign the JWT.
So the original signature will never correspond to the manipulated data.
And therefore, the verification will always fail in this case. And that's the key to making this whole system work. It's the magic that makes JWT so simple,
but also extremely powerful.


问:
Write Dataframe + Dynamic Filename to CSV with Output Path
i know that the answer is simple and out there somewhere but i cannot seem to find it. As my title suggests, I am trying to write a pandas DF with a dynamic filename in .csv format to an output directory given a path. Here below is my error code below. Thank you for any suggestions and I'm open to doing this a different or pythonic way if possible.

```<code>runfile('C:/Users/U321103/.spyder-py3/Read_VORTEX_test_files.py', wdir='C:/Users/U321103/.spyder-
py3')
klondikeii.Vortex_WIND.csv
Traceback (most recent call last):
File "C:\Users\U321103\.spyder-py3\Read_VORTEX_test_files.py", line 29, in <module>
c.to_csv(Path(p + filename ), index=False)
TypeError: unsupported operand type(s) for +: 'WindowsPath' and 'str'
</code>```

My code looks like this:

```<code>from sys import exit
import pandas as pd
from pathlib import Path

# Create a dataframe from csv
df = pd.read_csv("\\\porfiler03\\gtdshare\\VORTEX\\VALIDATION\\vortex_links.txt", delimiter=',')
# User list comprehension to create a list of lists from Dataframe rows
list_of_rows = [list(row) for row in df.values]
# Print list of lists i.e. rows
#print(list_of_rows)

var = df.variable.to_frame() #extract wind or power from df 'variable' column
#Find farm_data = farm_vortex cases
#for k in range(0,len(df)):
for k in range(0,1):
  if (( df.farm_data[k] == df.farm_vortex[k]) and var.variable[k] == 'wind'):
    #print('chinook = vortex data')
    c = pd.read_csv(df.link[k])#dataframe with vortex wind data
    filename = df.farm_data[k] + '.' + 'Vortex_WIND' + '.csv'
    print(filename)
    #save the data to a csv_file.
    p = Path('///porfiler03//gtdshare//')
    c.to_csv(Path(p + filename ), index=False)
exit()
</code>```

答:
Remove Path() from '///porfiler03//gtdshare//'.

In p + filename you are trying to concatenate to create the full path. You can do so for two strings but not for a string and a path, and this is what the error is telling you.
Try:

```<code>p = '///porfiler03//gtdshare//'
c.to_csv(Path(p + filename ), index=False)
</code>```

Body:
i know that the answer is simple and out there somewhere but i cannot seem to find it. As my title suggests, I am trying to write a pandas DF with a dynamic filename in .csv format to an output directory given a path. Here below is my error code below. Thank you for any suggestions and I'm open to doing this a different or pythonic way if possible.

runfile('C:/Users/U321103/.spyder-py3/Read_VORTEX_test_files.py', wdir='C:/Users/U321103/.spyder-
py3')
klondikeii.Vortex_WIND.csv
Traceback (most recent call last):
File "C:\Users\U321103\.spyder-py3\Read_VORTEX_test_files.py", line 29, in <module>
c.to_csv(Path(p + filename ), index=False)
TypeError: unsupported operand type(s) for +: 'WindowsPath' and 'str'

My code looks like this:

from sys import exit
import pandas as pd
from pathlib import Path

# Create a dataframe from csv
df = pd.read_csv("\\\porfiler03\\gtdshare\\VORTEX\\VALIDATION\\vortex_links.txt", delimiter=',')
# User list comprehension to create a list of lists from Dataframe rows
list_of_rows = [list(row) for row in df.values]
# Print list of lists i.e. rows
#print(list_of_rows)

var = df.variable.to_frame() #extract wind or power from df 'variable' column
#Find farm_data = farm_vortex cases
#for k in range(0,len(df)):
for k in range(0,1):
  if (( df.farm_data[k] == df.farm_vortex[k]) and var.variable[k] == 'wind'):
    #print('chinook = vortex data')
    c = pd.read_csv(df.link[k])#dataframe with vortex wind data
    filename = df.farm_data[k] + '.' + 'Vortex_WIND' + '.csv'
    print(filename)
    #save the data to a csv_file.
    p = Path('///porfiler03//gtdshare//')
    c.to_csv(Path(p + filename ), index=False)
exit()

Body:
Remove Path() from '///porfiler03//gtdshare//'.

In p + filename you are trying to concatenate to create the full path. You can do so for two strings but not for a string and a path, and this is what the error is telling you.
Try:

p = '///porfiler03//gtdshare//'
c.to_csv(Path(p + filename ), index=False)


问:
Can not parse query in deno
I started learning deno few days ago and i'm trying to parse query.

```<code>export const getBookQuery = async ({ request, response }) => {
  let kw = request.url.searchParams.get('keyword');
  // ...
};
</code>```

It works that way but, i need to parse whole query and don't want to get values one by one.

P.S i use oak

答:
You can use Object.fromEntries

```<code>const query = Object.fromEntries(request.url.searchParams);
console.log(query);
console.log(query.keyword);
</code>```

Title: Can not parse query in deno

Body:
I started learning deno few days ago and i'm trying to parse query.

export const getBookQuery = async ({ request, response }) => {
  let kw = request.url.searchParams.get('keyword');
  // ...
};

It works that way but, i need to parse whole query and don't want to get values one by one.

P.S i use oak

Body:
You can use Object.fromEntries

const query = Object.fromEntries(request.url.searchParams);
console.log(query);
console.log(query.keyword);


问:
Facebook Oembed returns unsupported browser page for HttpRequestMessage with UserAgent and Referrer
From my ASP.Net Core MVC app, I am trying to fetch OEmbed JSON from Facebook using server-side request from my local machine, but I'm still getting an unsupported browser page. What else do I need to pass?

oEmbedUrl is "https://www.facebook.com/plugins/post/oembed.json/?url=" + a post URL.

```<code>            var request = new HttpRequestMessage(HttpMethod.Get, oEmbedUrl);
            request.Headers.AcceptLanguage.TryParseAdd("en");
            request.Headers.UserAgent.TryParseAdd("Mozilla / 5.0(Windows; U; WindowsNT 5.1; en - US; rv1.8.1.6) Gecko / 20070725 Firefox / 2.0.0.6");
            request.Headers.Referrer = new Uri("http://www.google.com");
            request.Headers.TransferEncoding.TryParseAdd("gzip");
            request.Headers.TransferEncoding.TryParseAdd("deflate");

            var client = _clientFactory.CreateClient();

            var response = await client.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }
</code>```

答:
I did a simple test and it seems to work. Make sure the post is public and all parameters are URL encoded.</p>

```<code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://www.facebook.com/plugins/video/oembed.json/?url=https%3A%2F%2Fwww.facebook.com%2Ffacebook%2Fvideos%2F10153231379946729%2F");
        request.UserAgent = "Mozilla / 5.0(Windows; U; WindowsNT 5.1; en - US; rv1.8.1.6) Gecko / 20070725 Firefox / 2.0.0.6";
        request.Referer = "http://www.google.com";
        request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        using (Stream stream = response.GetResponseStream())
        using (StreamReader reader = new StreamReader(stream))
        {
            string json = reader.ReadToEnd();

        }
</code>```

Body:
From my ASP.Net Core MVC app, I am trying to fetch OEmbed JSON from Facebook using server-side request from my local machine, but I'm still getting an unsupported browser page. What else do I need to pass?

oEmbedUrl is "https://www.facebook.com/plugins/post/oembed.json/?url=" + a post URL.

            var request = new HttpRequestMessage(HttpMethod.Get, oEmbedUrl);
            request.Headers.AcceptLanguage.TryParseAdd("en");
            request.Headers.UserAgent.TryParseAdd("Mozilla / 5.0(Windows; U; WindowsNT 5.1; en - US; rv1.8.1.6) Gecko / 20070725 Firefox / 2.0.0.6");
            request.Headers.Referrer = new Uri("http://www.google.com");
            request.Headers.TransferEncoding.TryParseAdd("gzip");
            request.Headers.TransferEncoding.TryParseAdd("deflate");

            var client = _clientFactory.CreateClient();

            var response = await client.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }

Body:
I did a simple test and it seems to work. Make sure the post is public and all parameters are URL encoded.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://www.facebook.com/plugins/video/oembed.json/?url=https%3A%2F%2Fwww.facebook.com%2Ffacebook%2Fvideos%2F10153231379946729%2F");
        request.UserAgent = "Mozilla / 5.0(Windows; U; WindowsNT 5.1; en - US; rv1.8.1.6) Gecko / 20070725 Firefox / 2.0.0.6";
        request.Referer = "http://www.google.com";
        request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        using (Stream stream = response.GetResponseStream())
        using (StreamReader reader = new StreamReader(stream))
        {
            string json = reader.ReadToEnd();

        }


问:
Python pocketsphinx 0.1.15 configuration versus pocketsphinx_continuous.exe configuration
I have a solution (jsgf, dict, hmm), that works well with:

pocketsphinx_continuous -hmm zero_ru.cd_cont_4000 -dict vocabular.dict -jsgf calc.jsgf -inmic yes

Now I am trying to port it to Python pocketsphinx 0.1.15 (https://pypi.org/project/pocketsphinx/) and I see, in verbose output, that config of Python pocketsphinx is not the same as pocketsphinx_continuous config.

As a result Python pocketsphinx makes a lot of wrong phantom detections.

My Python script is very simple:

```<code>speech = LiveSpeech(
    verbose=True,
    hmm='c:/Projects/pocketsphinx-5prealpha-win32/pocketsphinx/bin/Release/x64/zero_ru.cd_cont_4000',
    lm=False,
    jsgf='c:/Projects/pocketsphinx-5prealpha-win32/pocketsphinx/bin/Release/x64/calc.jsgf',
    dic='c:/Projects/pocketsphinx-5prealpha-win32/pocketsphinx/bin/Release/x64/vocabular.dict',
    allphone_ci=False,
    vad_threshold=2.0,
    kws_threshold=1.0,
)

for phrase in speech:
    print(phrase)
</code>```

By comparing text files with outputs I see, that pocketsphinx_continuous has in output:

```<code>INFO: fe_interface.c(325): Using -1 as the seed.
INFO: feat.c(715): Initializing feature stream to type: '1s_c_d_dd', ceplen=13, CMN='current', VARNORM='no', AGC='none'
INFO: cmn.c(143): mean[0]= 12.00, mean[1..12]= 0.0
INFO: acmod.c(154): Reading linear feature transformation from zero_ru.cd_cont_4000/feature_transform
INFO: mdef.c(518): Reading model definition: zero_ru.cd_cont_4000/mdef
INFO: bin_mdef.c(181): Allocating 145321 * 8 bytes (1135 KiB) for CD tree
</code>```

but Python pocketsphinx has:

```<code>INFO: fe_interface.c(324): Using -1 as the seed.
INFO: feat.c(715): Initializing feature stream to type: '1s_c_d_dd', ceplen=13, CMN='batch', VARNORM='no', AGC='none'
INFO: acmod.c(152): Reading linear feature transformation from c:/Projects/pocketsphinx-5prealpha-win32/pocketsphinx/bin/Release/x64/zero_ru.cd_cont_4000/feature_transform
INFO: mdef.c(518): Reading model definition: c:/Projects/pocketsphinx-5prealpha-win32/pocketsphinx/bin/Release/x64/zero_ru.cd_cont_4000/mdef
</code>```

Now I am trying to make Python pocketsphinx to make (or, to config) the same as pocketsphinx_continuous.

How to make Python pocketsphinx use CMN='current' instead of CMN='batch'?
I. e. how to make Python pocketsphinx show in the output:

```<code>INFO: feat.c(715): Initializing feature stream to type: '1s_c_d_dd', ceplen=13, CMN='current', VARNORM='no', AGC='none'
INFO: cmn.c(143): mean[0]= 12.00, mean[1..12]= 0.0
INFO: acmod.c(154): Reading linear feature transformation from zero_ru.cd_cont_4000/feature_transform
INFO: mdef.c(518): Reading model definition: zero_ru.cd_cont_4000/mdef
</code>```

instead of:

```<code>INFO: feat.c(715): Initializing feature stream to type: '1s_c_d_dd', ceplen=13, CMN='batch', VARNORM='no', AGC='none'
INFO: acmod.c(152): Reading linear feature transformation from c:/Projects/pocketsphinx-5prealpha-win32/pocketsphinx/bin/Release/x64/zero_ru.cd_cont_4000/feature_transform
INFO: mdef.c(518): Reading model definition: c:/Projects/pocketsphinx-5prealpha-win32/pocketsphinx/bin/Release/x64/zero_ru.cd_cont_4000/mdef
</code>```

答:
Batch and current are the same mode. It was just renamed during some point of the time and it simply depends on the version.

Phantom detections are probably a result of very small vocabulary in your jsgf, not the cmn.

Body:
I have a solution (jsgf, dict, hmm), that works well with:

pocketsphinx_continuous -hmm zero_ru.cd_cont_4000 -dict vocabular.dict -jsgf calc.jsgf -inmic yes

Now I am trying to port it to Python pocketsphinx 0.1.15 (https://pypi.org/project/pocketsphinx/) and I see, in verbose output, that config of Python pocketsphinx is not the same as pocketsphinx_continuous config.

As a result Python pocketsphinx makes a lot of wrong phantom detections.

My Python script is very simple:

speech = LiveSpeech(
    verbose=True,
    hmm='c:/Projects/pocketsphinx-5prealpha-win32/pocketsphinx/bin/Release/x64/zero_ru.cd_cont_4000',
    lm=False,
    jsgf='c:/Projects/pocketsphinx-5prealpha-win32/pocketsphinx/bin/Release/x64/calc.jsgf',
    dic='c:/Projects/pocketsphinx-5prealpha-win32/pocketsphinx/bin/Release/x64/vocabular.dict',
    allphone_ci=False,
    vad_threshold=2.0,
    kws_threshold=1.0,
)

for phrase in speech:
    print(phrase)

By comparing text files with outputs I see, that pocketsphinx_continuous has in output:

INFO: fe_interface.c(325): Using -1 as the seed.
INFO: feat.c(715): Initializing feature stream to type: '1s_c_d_dd', ceplen=13, CMN='current', VARNORM='no', AGC='none'
INFO: cmn.c(143): mean[0]= 12.00, mean[1..12]= 0.0
INFO: acmod.c(154): Reading linear feature transformation from zero_ru.cd_cont_4000/feature_transform
INFO: mdef.c(518): Reading model definition: zero_ru.cd_cont_4000/mdef
INFO: bin_mdef.c(181): Allocating 145321 * 8 bytes (1135 KiB) for CD tree

but Python pocketsphinx has:

INFO: fe_interface.c(324): Using -1 as the seed.
INFO: feat.c(715): Initializing feature stream to type: '1s_c_d_dd', ceplen=13, CMN='batch', VARNORM='no', AGC='none'
INFO: acmod.c(152): Reading linear feature transformation from c:/Projects/pocketsphinx-5prealpha-win32/pocketsphinx/bin/Release/x64/zero_ru.cd_cont_4000/feature_transform
INFO: mdef.c(518): Reading model definition: c:/Projects/pocketsphinx-5prealpha-win32/pocketsphinx/bin/Release/x64/zero_ru.cd_cont_4000/mdef

Now I am trying to make Python pocketsphinx to make (or, to config) the same as pocketsphinx_continuous.

How to make Python pocketsphinx use CMN='current' instead of CMN='batch'?
I. e. how to make Python pocketsphinx show in the output:

INFO: feat.c(715): Initializing feature stream to type: '1s_c_d_dd', ceplen=13, CMN='current', VARNORM='no', AGC='none'
INFO: cmn.c(143): mean[0]= 12.00, mean[1..12]= 0.0
INFO: acmod.c(154): Reading linear feature transformation from zero_ru.cd_cont_4000/feature_transform
INFO: mdef.c(518): Reading model definition: zero_ru.cd_cont_4000/mdef

instead of:

INFO: feat.c(715): Initializing feature stream to type: '1s_c_d_dd', ceplen=13, CMN='batch', VARNORM='no', AGC='none'
INFO: acmod.c(152): Reading linear feature transformation from c:/Projects/pocketsphinx-5prealpha-win32/pocketsphinx/bin/Release/x64/zero_ru.cd_cont_4000/feature_transform
INFO: mdef.c(518): Reading model definition: c:/Projects/pocketsphinx-5prealpha-win32/pocketsphinx/bin/Release/x64/zero_ru.cd_cont_4000/mdef


问:
WebDriverIO: browser.pause does not working
I have used browser.sleep in protractor to hold the execution for a particular amount of time. In similar way I have tried the browser.pause in WebDriverIO. But it is not pausing for the given amount of time.

Even for browser pause I referred the WebDriverIO official documentation, there also the same thing is given

Step Definition Code:

```<code>Given(/^Verify the title of Salesforce web page$/,function(){
    browser.url('https://login.salesforce.com/');
    browser.pause(10000);
});
</code>```

I use async mode in the configuration

WebDriverIO Version: ^5.22.4

wdio.config.js

```<code>exports.config = {
    //
    // ====================
    // Runner Configuration
    // ====================
    //
    // WebdriverIO allows it to run your tests in arbitrary locations (e.g. locally or
    // on a remote machine).
    runner: 'local',
    //
    // Override default path ('/wd/hub') for chromedriver service.
    path: '/',
    //
    // ==================
    // Specify Test Files
    // ==================
    // Define which test specs should run. The pattern is relative to the directory
    // from which `wdio` was called. Notice that, if you are calling `wdio` from an
    // NPM script (see https://docs.npmjs.com/cli/run-script) then the current working
    // directory is where your package.json resides, so `wdio` will be called from there.
    //
    specs: [
        './test/features/*.feature'
    ],
    // Patterns to exclude.
    exclude: [
        // 'path/to/excluded/files'
    ],
    //
    // ============
    // Capabilities
    // ============
    // Define your capabilities here. WebdriverIO can run multiple capabilities at the same
    // time. Depending on the number of capabilities, WebdriverIO launches several test
    // sessions. Within your capabilities you can overwrite the spec and exclude options in
    // order to group specific specs to a specific capability.
    //
    // First, you can define how many instances should be started at the same time. Let's
    // say you have 3 different capabilities (Chrome, Firefox, and Safari) and you have
    // set maxInstances to 1; wdio will spawn 3 processes. Therefore, if you have 10 spec
    // files and you set maxInstances to 10, all spec files will get tested at the same time
    // and 30 processes will get spawned. The property handles how many capabilities
    // from the same test should run tests.
    //
    maxInstances: 10,
    //
    // If you have trouble getting all important capabilities together, check out the
    // Sauce Labs platform configurator - a great tool to configure your capabilities:
    // https://docs.saucelabs.com/reference/platforms-configurator
    //
    capabilities: [{

        // maxInstances can get overwritten per capability. So if you have an in-house Selenium
        // grid with only 5 firefox instances available you can make sure that not more than
        // 5 instances get started at a time.
        maxInstances: 5,
        //
        browserName: 'chrome',
        // If outputDir is provided WebdriverIO can capture driver session logs
        // it is possible to configure which logTypes to include/exclude.
        // excludeDriverLogs: ['*'], // pass '*' to exclude all driver session logs
        // excludeDriverLogs: ['bugreport', 'server'],
    }],
    //
    // ===================
    // Test Configurations
    // ===================
    // Define all options that are relevant for the WebdriverIO instance here
    //
    // Level of logging verbosity: trace | debug | info | warn | error | silent
    logLevel: 'info',
    //
    // Set specific log levels per logger
    // loggers:
    // - webdriver, webdriverio
    // - @wdio/applitools-service, @wdio/browserstack-service, @wdio/devtools-service, @wdio/sauce-service
    // - @wdio/mocha-framework, @wdio/jasmine-framework
    // - @wdio/local-runner, @wdio/lambda-runner
    // - @wdio/sumologic-reporter
    // - @wdio/cli, @wdio/config, @wdio/sync, @wdio/utils
    // Level of logging verbosity: trace | debug | info | warn | error | silent
    // logLevels: {
    //     webdriver: 'info',
    //     '@wdio/applitools-service': 'info'
    // },
    //
    // If you only want to run your tests until a specific amount of tests have failed use
    // bail (default is 0 - don't bail, run all tests).
    bail: 0,
    //
    // Set a base URL in order to shorten url command calls. If your `url` parameter starts
    // with `/`, the base url gets prepended, not including the path portion of your baseUrl.
    // If your `url` parameter starts without a scheme or `/` (like `some/path`), the base url
    // gets prepended directly.
    baseUrl: 'https://login.salesforce.com/',
    //
    // Default timeout for all waitFor* commands.
    waitforTimeout: 10000,
    //
    // Default timeout in milliseconds for request
    // if browser driver or grid doesn't send response
    connectionRetryTimeout: 90000,
    //
    // Default request retries count
    connectionRetryCount: 0,
    //
    // Test runner services
    // Services take over a specific job you don't want to take care of. They enhance
    // your test setup with almost no effort. Unlike plugins, they don't add new
    // commands. Instead, they hook themselves up into the test process.
    services: ['chromedriver','firefox-profile'],

    // Framework you want to run your specs with.
    // The following are supported: Mocha, Jasmine, and Cucumber
    // see also: https://webdriver.io/docs/frameworks.html
    //
    // Make sure you have the wdio adapter package for the specific framework installed
    // before running any tests.
    framework: 'cucumber',
    //
    // The number of times to retry the entire specfile when it fails as a whole
    // specFileRetries: 1,
    //
    // Test reporter for stdout.
    // The only one supported by default is 'dot'
    // see also: https://webdriver.io/docs/dot-reporter.html
    reporters: ['spec',['allure', {
        outputDir: 'allure-results',
        disableWebdriverStepsReporting: true,
        disableWebdriverScreenshotsReporting: false,
        useCucumberStepReporter:true
    }]],
    // If you are using Cucumber you need to specify the location of your step definitions.
    cucumberOpts: {
        require: ['./built/**/*.js'],        // <string[]> (file/dir) require files before executing features
        backtrace: false,   // <boolean> show full backtrace for errors
        requireModule: [],  // <string[]> ("extension:module") require files with the given EXTENSION after requiring MODULE (repeatable)
        dryRun: false,      // <boolean> invoke formatters without executing steps
        failFast: false,    // <boolean> abort the run on first failure
        format: ['pretty'], // <string[]> (type[:path]) specify the output format, optionally supply PATH to redirect formatter output (repeatable)
        colors: true,       // <boolean> disable colors in formatter output
        snippets: true,     // <boolean> hide step definition snippets for pending steps
        source: true,       // <boolean> hide source uris
        profile: [],        // <string[]> (name) specify the profile to use
        strict: false,      // <boolean> fail if there are any undefined or pending steps
        tagExpression: '',  // <string> (expression) only execute the features or scenarios with tags matching the expression
        timeout: 60000,     // <number> timeout for step definitions
        ignoreUndefinedDefinitions: false, // <boolean> Enable this config to treat undefined definitions as warnings.
    },

    //
    // =====
    // Hooks
    // =====
    // WebdriverIO provides several hooks you can use to interfere with the test process in order to enhance
    // it and to build services around it. You can either apply a single function or an array of
    // methods to it. If one of them returns with a promise, WebdriverIO will wait until that promise got
    // resolved to continue.
    /**
     * Gets executed once before all workers get launched.
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     */
    // onPrepare: function (config, capabilities) {
    // },
    /**
     * Gets executed just before initialising the webdriver session and test framework. It allows you
     * to manipulate configurations depending on the capability or spec.
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that are to be run
     */
    // beforeSession: function (config, capabilities, specs) {
    // },
    /**
     * Gets executed before test execution begins. At this point you can access to all global
     * variables like `browser`. It is the perfect place to define custom commands.
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that are to be run
     */
    before: function (_capabilities) {
           // =================
        // Assertion Library
        // =================
        const chai    = require('chai');
        global.expect = chai.expect;
        global.assert = chai.assert;
        global.should = chai.should();
        require('ts-node').register({ files: true });
    },
    /**
     * Runs before a WebdriverIO command gets executed.
     * @param {String} commandName hook command name
     * @param {Array} args arguments that command would receive
     */
    // beforeCommand: function (commandName, args) {
    // },
    /**
     * Runs before a Cucumber feature
     */
    beforeFeature: function (uri, feature, scenarios) {
        scenarioCounter = 0;
    },
    /**
     * Runs before a Cucumber scenario
     */
    // beforeScenario: function (uri, feature, scenario, sourceLocation) {
    // },
    /**
     * Runs before a Cucumber step
     */
    // beforeStep: function (uri, feature, stepData, context) {
    // },
    /**
     * Runs after a Cucumber step
     */
    afterStep: function (uri, feature, { error, result, duration, passed }, stepData, context) {
        if (error !== undefined) {
            browser.takeScreenshot();
        }
    },
    /**
     * Runs after a Cucumber scenario
     */
    afterScenario: function (uri, feature, scenario, result, sourceLocation) {
        scenarioCounter += 1;
        addArgument('Scenario #', scenarioCounter);
    },
    /**
     * Runs after a Cucumber feature
     */
    // afterFeature: function (uri, feature, scenarios) {
    // },

    /**
     * Runs after a WebdriverIO command gets executed
     * @param {String} commandName hook command name
     * @param {Array} args arguments that command would receive
     * @param {Number} result 0 - command success, 1 - command error
     * @param {Object} error error object if any
     */
    // afterCommand: function (commandName, args, result, error) {
    // },
    /**
     * Gets executed after all tests are done. You still have access to all global variables from
     * the test.
     * @param {Number} result 0 - test pass, 1 - test fail
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that ran
     */
    // after: function (result, capabilities, specs) {
    // },
    /**
     * Gets executed right after terminating the webdriver session.
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that ran
     */
    // afterSession: function (config, capabilities, specs) {
    // },
    /**
     * Gets executed after all workers got shut down and the process is about to exit. An error
     * thrown in the onComplete hook will result in the test run failing.
     * @param {Object} exitCode 0 - success, 1 - fail
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {<Object>} results object containing test results
     */
    // onComplete: function(exitCode, config, capabilities, results) {
    // },
    /**
    * Gets executed when a refresh happens.
    * @param {String} oldSessionId session ID of the old session
    * @param {String} newSessionId session ID of the new session
    */
    //onReload: function(oldSessionId, newSessionId) {
    //}
}
</code>```

答:
Might be worthy trying async/await as below:

```<code>Given(/^Verify the title of Salesforce web page$/, async function(){
    await browser.url('https://login.salesforce.com/');
    await browser.pause(10000);
});
</code>```

I hope it helps

Body:
I have used browser.sleep in protractor to hold the execution for a particular amount of time. In similar way I have tried the browser.pause in WebDriverIO. But it is not pausing for the given amount of time.

Even for browser pause I referred the WebDriverIO official documentation, there also the same thing is given

Step Definition Code:

Given(/^Verify the title of Salesforce web page$/,function(){
    browser.url('https://login.salesforce.com/');
    browser.pause(10000);
});

I use async mode in the configuration

WebDriverIO Version: ^5.22.4

wdio.config.js

exports.config = {
    //
    // ====================
    // Runner Configuration
    // ====================
    //
    // WebdriverIO allows it to run your tests in arbitrary locations (e.g. locally or
    // on a remote machine).
    runner: 'local',
    //
    // Override default path ('/wd/hub') for chromedriver service.
    path: '/',
    //
    // ==================
    // Specify Test Files
    // ==================
    // Define which test specs should run. The pattern is relative to the directory
    // from which `wdio` was called. Notice that, if you are calling `wdio` from an
    // NPM script (see https://docs.npmjs.com/cli/run-script) then the current working
    // directory is where your package.json resides, so `wdio` will be called from there.
    //
    specs: [
        './test/features/*.feature'
    ],
    // Patterns to exclude.
    exclude: [
        // 'path/to/excluded/files'
    ],
    //
    // ============
    // Capabilities
    // ============
    // Define your capabilities here. WebdriverIO can run multiple capabilities at the same
    // time. Depending on the number of capabilities, WebdriverIO launches several test
    // sessions. Within your capabilities you can overwrite the spec and exclude options in
    // order to group specific specs to a specific capability.
    //
    // First, you can define how many instances should be started at the same time. Let's
    // say you have 3 different capabilities (Chrome, Firefox, and Safari) and you have
    // set maxInstances to 1; wdio will spawn 3 processes. Therefore, if you have 10 spec
    // files and you set maxInstances to 10, all spec files will get tested at the same time
    // and 30 processes will get spawned. The property handles how many capabilities
    // from the same test should run tests.
    //
    maxInstances: 10,
    //
    // If you have trouble getting all important capabilities together, check out the
    // Sauce Labs platform configurator - a great tool to configure your capabilities:
    // https://docs.saucelabs.com/reference/platforms-configurator
    //
    capabilities: [{

        // maxInstances can get overwritten per capability. So if you have an in-house Selenium
        // grid with only 5 firefox instances available you can make sure that not more than
        // 5 instances get started at a time.
        maxInstances: 5,
        //
        browserName: 'chrome',
        // If outputDir is provided WebdriverIO can capture driver session logs
        // it is possible to configure which logTypes to include/exclude.
        // excludeDriverLogs: ['*'], // pass '*' to exclude all driver session logs
        // excludeDriverLogs: ['bugreport', 'server'],
    }],
    //
    // ===================
    // Test Configurations
    // ===================
    // Define all options that are relevant for the WebdriverIO instance here
    //
    // Level of logging verbosity: trace | debug | info | warn | error | silent
    logLevel: 'info',
    //
    // Set specific log levels per logger
    // loggers:
    // - webdriver, webdriverio
    // - @wdio/applitools-service, @wdio/browserstack-service, @wdio/devtools-service, @wdio/sauce-service
    // - @wdio/mocha-framework, @wdio/jasmine-framework
    // - @wdio/local-runner, @wdio/lambda-runner
    // - @wdio/sumologic-reporter
    // - @wdio/cli, @wdio/config, @wdio/sync, @wdio/utils
    // Level of logging verbosity: trace | debug | info | warn | error | silent
    // logLevels: {
    //     webdriver: 'info',
    //     '@wdio/applitools-service': 'info'
    // },
    //
    // If you only want to run your tests until a specific amount of tests have failed use
    // bail (default is 0 - don't bail, run all tests).
    bail: 0,
    //
    // Set a base URL in order to shorten url command calls. If your `url` parameter starts
    // with `/`, the base url gets prepended, not including the path portion of your baseUrl.
    // If your `url` parameter starts without a scheme or `/` (like `some/path`), the base url
    // gets prepended directly.
    baseUrl: 'https://login.salesforce.com/',
    //
    // Default timeout for all waitFor* commands.
    waitforTimeout: 10000,
    //
    // Default timeout in milliseconds for request
    // if browser driver or grid doesn't send response
    connectionRetryTimeout: 90000,
    //
    // Default request retries count
    connectionRetryCount: 0,
    //
    // Test runner services
    // Services take over a specific job you don't want to take care of. They enhance
    // your test setup with almost no effort. Unlike plugins, they don't add new
    // commands. Instead, they hook themselves up into the test process.
    services: ['chromedriver','firefox-profile'],

    // Framework you want to run your specs with.
    // The following are supported: Mocha, Jasmine, and Cucumber
    // see also: https://webdriver.io/docs/frameworks.html
    //
    // Make sure you have the wdio adapter package for the specific framework installed
    // before running any tests.
    framework: 'cucumber',
    //
    // The number of times to retry the entire specfile when it fails as a whole
    // specFileRetries: 1,
    //
    // Test reporter for stdout.
    // The only one supported by default is 'dot'
    // see also: https://webdriver.io/docs/dot-reporter.html
    reporters: ['spec',['allure', {
        outputDir: 'allure-results',
        disableWebdriverStepsReporting: true,
        disableWebdriverScreenshotsReporting: false,
        useCucumberStepReporter:true
    }]],
    // If you are using Cucumber you need to specify the location of your step definitions.
    cucumberOpts: {
        require: ['./built/**/*.js'],        // <string[]> (file/dir) require files before executing features
        backtrace: false,   // <boolean> show full backtrace for errors
        requireModule: [],  // <string[]> ("extension:module") require files with the given EXTENSION after requiring MODULE (repeatable)
        dryRun: false,      // <boolean> invoke formatters without executing steps
        failFast: false,    // <boolean> abort the run on first failure
        format: ['pretty'], // <string[]> (type[:path]) specify the output format, optionally supply PATH to redirect formatter output (repeatable)
        colors: true,       // <boolean> disable colors in formatter output
        snippets: true,     // <boolean> hide step definition snippets for pending steps
        source: true,       // <boolean> hide source uris
        profile: [],        // <string[]> (name) specify the profile to use
        strict: false,      // <boolean> fail if there are any undefined or pending steps
        tagExpression: '',  // <string> (expression) only execute the features or scenarios with tags matching the expression
        timeout: 60000,     // <number> timeout for step definitions
        ignoreUndefinedDefinitions: false, // <boolean> Enable this config to treat undefined definitions as warnings.
    },

    //
    // =====
    // Hooks
    // =====
    // WebdriverIO provides several hooks you can use to interfere with the test process in order to enhance
    // it and to build services around it. You can either apply a single function or an array of
    // methods to it. If one of them returns with a promise, WebdriverIO will wait until that promise got
    // resolved to continue.
    /**
     * Gets executed once before all workers get launched.
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     */
    // onPrepare: function (config, capabilities) {
    // },
    /**
     * Gets executed just before initialising the webdriver session and test framework. It allows you
     * to manipulate configurations depending on the capability or spec.
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that are to be run
     */
    // beforeSession: function (config, capabilities, specs) {
    // },
    /**
     * Gets executed before test execution begins. At this point you can access to all global
     * variables like `browser`. It is the perfect place to define custom commands.
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that are to be run
     */
    before: function (_capabilities) {
           // =================
        // Assertion Library
        // =================
        const chai    = require('chai');
        global.expect = chai.expect;
        global.assert = chai.assert;
        global.should = chai.should();
        require('ts-node').register({ files: true });
    },
    /**
     * Runs before a WebdriverIO command gets executed.
     * @param {String} commandName hook command name
     * @param {Array} args arguments that command would receive
     */
    // beforeCommand: function (commandName, args) {
    // },
    /**
     * Runs before a Cucumber feature
     */
    beforeFeature: function (uri, feature, scenarios) {
        scenarioCounter = 0;
    },
    /**
     * Runs before a Cucumber scenario
     */
    // beforeScenario: function (uri, feature, scenario, sourceLocation) {
    // },
    /**
     * Runs before a Cucumber step
     */
    // beforeStep: function (uri, feature, stepData, context) {
    // },
    /**
     * Runs after a Cucumber step
     */
    afterStep: function (uri, feature, { error, result, duration, passed }, stepData, context) {
        if (error !== undefined) {
            browser.takeScreenshot();
        }
    },
    /**
     * Runs after a Cucumber scenario
     */
    afterScenario: function (uri, feature, scenario, result, sourceLocation) {
        scenarioCounter += 1;
        addArgument('Scenario #', scenarioCounter);
    },
    /**
     * Runs after a Cucumber feature
     */
    // afterFeature: function (uri, feature, scenarios) {
    // },

    /**
     * Runs after a WebdriverIO command gets executed
     * @param {String} commandName hook command name
     * @param {Array} args arguments that command would receive
     * @param {Number} result 0 - command success, 1 - command error
     * @param {Object} error error object if any
     */
    // afterCommand: function (commandName, args, result, error) {
    // },
    /**
     * Gets executed after all tests are done. You still have access to all global variables from
     * the test.
     * @param {Number} result 0 - test pass, 1 - test fail
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that ran
     */
    // after: function (result, capabilities, specs) {
    // },
    /**
     * Gets executed right after terminating the webdriver session.
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {Array.<String>} specs List of spec file paths that ran
     */
    // afterSession: function (config, capabilities, specs) {
    // },
    /**
     * Gets executed after all workers got shut down and the process is about to exit. An error
     * thrown in the onComplete hook will result in the test run failing.
     * @param {Object} exitCode 0 - success, 1 - fail
     * @param {Object} config wdio configuration object
     * @param {Array.<Object>} capabilities list of capabilities details
     * @param {<Object>} results object containing test results
     */
    // onComplete: function(exitCode, config, capabilities, results) {
    // },
    /**
    * Gets executed when a refresh happens.
    * @param {String} oldSessionId session ID of the old session
    * @param {String} newSessionId session ID of the new session
    */
    //onReload: function(oldSessionId, newSessionId) {
    //}
}

Body:
Might be worthy trying async/await as below:

Given(/^Verify the title of Salesforce web page$/, async function(){
    await browser.url('https://login.salesforce.com/');
    await browser.pause(10000);
});

I hope it helps


问:
xcode4 doesn't support Perforce?
xcode4 doesn't support Perforce?

I add a repository in xcode4. Only subversion and Git to choose.

how to add a perforce repository?

thank you.

答:
It's also useful to note that there is a setting in Preferences/Behaviors to add behaviors to particular actions.   One of those is Unlock File, which can be bound to a shell script, like the one here:

```<code>#!/bin/sh

RESULT=`/opt/local/bin/p4 edit  ${1#file://localhost} 2>&1`
SHRESULT=$?
while [ $SHRESULT -ne 0 ]
    do
    SCRIPT="tell application \"XCode\" to display dialog \"$RESULT\" buttons {\"Try again\",\"Cancel\"} default button 1"
    osascript -e "$SCRIPT"
    if [ $? -ne 0 ]
    then
        break
    fi
    RESULT=`/opt/local/bin/p4 edit  ${1#file://localhost} 2>&1`
    SHRESULT=$?
done

exit $SHRESULT
</code>```

In order to invoke p4 edit when the editor needs to start making a change.

This has been updated to put up a dialog box if the p4 edit fails.   This will repeatedly attempt it if you hit "Try Again" and will stop when you hit "Cancel", which is particularly useful if you happen to have your login expire in the first case or aren't connected to your server in the second place.

Unfortunately, it appears that the exit code isn't checked to make sure that the unlock succeeded, and it appears that Xcode changes the file to r/w in this case, so be careful when you get an error message that you either get the edit to succeed or edit the file later.

Obviously, that only solves the problem of unlocking/editing files, but I find that I like to use p4v to submit anyway.

Multiple clients/workspaces

For those of you who might be using multiple clients on the same machine (something we're doing more of now that we use Streams more often with Perforce), it can be challenging to make sure that the correct client is used to work on the file you are editing.

For us, we found the easiest fix to be using P4CONFIG to denote a specific perforce configuration file.  In our case, we generally use .p4config-<user/host>, this way I can have .p4config-laptop-gaige and choose to either check it in if need be without interfering with the .p4config-desktop-gaige.  Inside of the .p4config file, we set P4CLIENT, and that makes sure that the p4 command knows which stream to use.

ContentLicense: CC BY-SA 2.5

Title: xcode4 doesn't support Perforce?

Body:
It's also useful to note that there is a setting in Preferences/Behaviors to add behaviors to particular actions.   One of those is Unlock File, which can be bound to a shell script, like the one here:

#!/bin/sh

RESULT=`/opt/local/bin/p4 edit  ${1#file://localhost} 2>&1`
SHRESULT=$?
while [ $SHRESULT -ne 0 ]
    do
    SCRIPT="tell application \"XCode\" to display dialog \"$RESULT\" buttons {\"Try again\",\"Cancel\"} default button 1"
    osascript -e "$SCRIPT"
    if [ $? -ne 0 ]
    then
        break
    fi
    RESULT=`/opt/local/bin/p4 edit  ${1#file://localhost} 2>&1`
    SHRESULT=$?
done

exit $SHRESULT

In order to invoke p4 edit when the editor needs to start making a change.

This has been updated to put up a dialog box if the p4 edit fails.   This will repeatedly attempt it if you hit "Try Again" and will stop when you hit "Cancel", which is particularly useful if you happen to have your login expire in the first case or aren't connected to your server in the second place.

Unfortunately, it appears that the exit code isn't checked to make sure that the unlock succeeded, and it appears that Xcode changes the file to r/w in this case, so be careful when you get an error message that you either get the edit to succeed or edit the file later.

Obviously, that only solves the problem of unlocking/editing files, but I find that I like to use p4v to submit anyway.

Multiple clients/workspaces

For those of you who might be using multiple clients on the same machine (something we're doing more of now that we use Streams more often with Perforce), it can be challenging to make sure that the correct client is used to work on the file you are editing.

For us, we found the easiest fix to be using P4CONFIG to denote a specific perforce configuration file.  In our case, we generally use .p4config-<user/host>, this way I can have .p4config-laptop-gaige and choose to either check it in if need be without interfering with the .p4config-desktop-gaige.  Inside of the .p4config file, we set P4CLIENT, and that makes sure that the p4 command knows which stream to use.

ContentLicense: CC BY-SA 3.0


问:
Why does the generated view binding .inflate() method requires root parameter?
I was following the example from the documentation on a personal project.

I have a layout called activity_main.xml, for which an ActivityMainBinding class is generated. When I call ActivityMainBinding.inflate(layoutInflater), I get an error saying that the method requires the "root" parameter of type ViewGroup.

Why isn't the method with only one argument (the inflater) available?

I've tried cleaning and rebuilding the project.

build.gradle (app)

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    defaultConfig {
        applicationId "com.example.teddy"
        minSdkVersion 22
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8.toString()
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    viewBinding {
        enabled = true
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'androidx.navigation:navigation-fragment-ktx:2.2.2'
    implementation 'androidx.navigation:navigation-ui-ktx:2.2.2'
}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.drawerlayout.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <fragment
            android:id="@+id/nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:navGraph="@navigation/navigation" />

        <com.google.android.material.navigation.NavigationView
            android:id="@+id/navView"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:headerLayout="@layout/nav_header"
            app:menu="@menu/navdrawer" />
    </androidx.drawerlayout.widget.DrawerLayout>
</merge>
</code>```

MainActivity.kt

```<code>package com.example.teddy

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.drawerlayout.widget.DrawerLayout
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupWithNavController
import com.example.teddy.databinding.ActivityMainBinding
import com.google.android.material.navigation.NavigationView

class MainActivity : AppCompatActivity() {
    private lateinit var drawerLayout: DrawerLayout
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)

        val navController = this.findNavController(R.id.nav_host_fragment)
        drawerLayout = binding.drawerLayout

        val appBarConfiguration = AppBarConfiguration(navController.graph, drawerLayout)
        findViewById<NavigationView>(R.id.navView)
            .setupWithNavController(navController)
    }
}
</code>```

Does anyone know what I am missing?

EDIT
The exact error from the failed build output:

No value passed for parameter 'parent’

The tooltip on the underlined error in the code says

No value passed for parameter 'root'

答:
You should use the setContentView method in DataBindingUtil.

Change this

```<code>    binding = ActivityMainBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view)
</code>```

to this

```<code>    binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
</code>```

Body:
I was following the example from the documentation on a personal project.

I have a layout called activity_main.xml, for which an ActivityMainBinding class is generated. When I call ActivityMainBinding.inflate(layoutInflater), I get an error saying that the method requires the "root" parameter of type ViewGroup.

Why isn't the method with only one argument (the inflater) available?

I've tried cleaning and rebuilding the project.

build.gradle (app)

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    defaultConfig {
        applicationId "com.example.teddy"
        minSdkVersion 22
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8.toString()
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    viewBinding {
        enabled = true
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'androidx.navigation:navigation-fragment-ktx:2.2.2'
    implementation 'androidx.navigation:navigation-ui-ktx:2.2.2'
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.drawerlayout.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <fragment
            android:id="@+id/nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:navGraph="@navigation/navigation" />

        <com.google.android.material.navigation.NavigationView
            android:id="@+id/navView"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:headerLayout="@layout/nav_header"
            app:menu="@menu/navdrawer" />
    </androidx.drawerlayout.widget.DrawerLayout>
</merge>

MainActivity.kt

package com.example.teddy

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.drawerlayout.widget.DrawerLayout
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupWithNavController
import com.example.teddy.databinding.ActivityMainBinding
import com.google.android.material.navigation.NavigationView

class MainActivity : AppCompatActivity() {
    private lateinit var drawerLayout: DrawerLayout
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)

        val navController = this.findNavController(R.id.nav_host_fragment)
        drawerLayout = binding.drawerLayout

        val appBarConfiguration = AppBarConfiguration(navController.graph, drawerLayout)
        findViewById<NavigationView>(R.id.navView)
            .setupWithNavController(navController)
    }
}

Does anyone know what I am missing?

EDIT
The exact error from the failed build output:

No value passed for parameter 'parent’

The tooltip on the underlined error in the code says

No value passed for parameter 'root'

Body:
You should use the setContentView method in DataBindingUtil.

Change this

    binding = ActivityMainBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view)

to this

    binding = DataBindingUtil.setContentView(this, R.layout.activity_main)


问:
Get the Data values from the registry using powershell
I am trying to add an application in 'DisallowRun' registry key to avoid running application to specific users. Need to add the application if not exist. Consider 'TestApp3.exe' in this case.

Used below query to get the list of items in the key. It is giving Name(Key Name), Property(Name Value : Data Value)

```<code>Get-Item -Path "Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\DisallowRun"
</code>```

Output

Name                           Property

----                           --------

DisallowRun                    1 : TestApp1.exe

DisallowRun                    2 : TestApp2.exe

DisallowRun                    3 : TestApp3.exe

DisallowRun                    4 : TestApp4.exe

When i use .Property in the code, getting only Name Values and not Data Values

```<code>(Get-Item -Path "Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\DisallowRun").Property
</code>```

Output

1

2

3

4

If i get only the Data Values (similar to below) then i could have use contains function to check the specific application is already available or not. Please help me to get only Data Value or is there anyway to check the application is exist in the registry key.

TestApp1.exe

TestApp2.exe

TestApp3.exe

TestApp4.exe

答:
Try this out.

(Get-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\DisallowRun).PSObject.Properties | Where-Object {
    $_.Name -notmatch "^PS"
} | Select-Object -ExpandProperty Value
```

Body:
I am trying to add an application in 'DisallowRun' registry key to avoid running application to specific users. Need to add the application if not exist. Consider 'TestApp3.exe' in this case.

Used below query to get the list of items in the key. It is giving Name(Key Name), Property(Name Value : Data Value)

Get-Item -Path "Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\DisallowRun"

Output

Name                           Property

----                           --------

DisallowRun                    1 : TestApp1.exe

DisallowRun                    2 : TestApp2.exe

DisallowRun                    3 : TestApp3.exe

DisallowRun                    4 : TestApp4.exe

When i use .Property in the code, getting only Name Values and not Data Values

(Get-Item -Path "Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\DisallowRun").Property

Output

1

2

3

4

If i get only the Data Values (similar to below) then i could have use contains function to check the specific application is already available or not. Please help me to get only Data Value or is there anyway to check the application is exist in the registry key.

TestApp1.exe

TestApp2.exe

TestApp3.exe

TestApp4.exe


问:
Bootstrap 4 Flexbox - Align multiple columns with align items center
I have 3 columns that I'm trying to center vertically to the viewport. The columns need to be full width - no inline. I want them stacked vertically like I have in my codeply, just with 'align-items-center' so all three center vertically to the viewport.

Check this.

```<code><div class="container-fluid" style="border: 3px solid red;">
<div class="row min-vh-100" style="border: 4px solid blue;">
    <div class="col" style="border: 3px solid yellow;">
        <div class="flex-column align-items-center p-2" style="border: 4px solid orange;">Flex item 1</div>
        <div class="flex-column p-2" style="border: 4px solid orange;">Flex item 1</div>
        <div class="flex-column p-2" style="border: 4px solid orange;">Flex item 1</div>
    </div>
</div>
</code>```

答:
Try this one. You have used flex-column on inner items but it must be on flex and you are missing d-flex class on container. Check this out for better idea: https://getbootstrap.com/docs/4.4/utilities/flex/</p>

```<code><div class="container-fluid" style="border: 3px solid red;">
    <div class="row min-vh-100" style="border: 4px solid blue;">
        <div class="col d-flex flex-column justify-content-center" style="border: 3px solid yellow;">
            <div class="p-2" style="border: 4px solid orange;">Flex item 1</div>
            <div class="p-2" style="border: 4px solid orange;">Flex item 1</div>
            <div class="p-2" style="border: 4px solid orange;">Flex item 1</div>
        </div>
    </div>
</div>
</code>```

Body:
I have 3 columns that I'm trying to center vertically to the viewport. The columns need to be full width - no inline. I want them stacked vertically like I have in my codeply, just with 'align-items-center' so all three center vertically to the viewport.

Check this.

Flex item 1

Flex item 1

Flex item 1

Body:
Try this one. You have used flex-column on inner items but it must be on flex and you are missing d-flex class on container. Check this out for better idea: https://getbootstrap.com/docs/4.4/utilities/flex/

<div class="container-fluid" style="border: 3px solid red;">
    <div class="row min-vh-100" style="border: 4px solid blue;">
        <div class="col d-flex flex-column justify-content-center" style="border: 3px solid yellow;">
            <div class="p-2" style="border: 4px solid orange;">Flex item 1</div>
            <div class="p-2" style="border: 4px solid orange;">Flex item 1</div>
            <div class="p-2" style="border: 4px solid orange;">Flex item 1</div>
        </div>
    </div>
</div>


问:
What is secret key for JWT based authentication and how to generate it?
Recently I started working with JWT-based authentication. After the user login, a user token is generated which will look like this:

```<code>"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ".
</code>```

It consists of three parts each separated with a dot(.).First part is header which Base64 encoded. After decoding we will get something like:

```<code>{
  "alg": "HS256", //Algorithm used
  "typ": "JWT"
}
</code>```

The second part is claims and Base64 encoded. After decoding we will get something like:

```<code>{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}
</code>```

The third part is the signature and is generated with:

```<code>HMACSHA256(
 base64UrlEncode(header) + "." +
 base64UrlEncode(payload),
 *secret base64 encoded*
)
</code>```

Now, what is this secret key, and how to generate this secret key?

I tried some online generators like: "http://kjur.github.io/jsjws/tool_jwt.html"

But, I didn't get much help.

答:
A Json Web Token made up of three parts. The header, the payload and the signature Now the header is just some metadata about the token itself and the payload is the data that we can encode into the token, any data really that we want. So the more data we want to encode here the bigger the JWT. Anyway, these two parts are just plain text that will get encoded, but not encrypted.

So anyone will be able to decode them and to read them, we cannot store any sensitive data in here. But that's not a problem at all because in the third part, so in the signature, is where things really get interesting. The signature is created using the header, the payload, and the secret that is saved on the server.

And this whole process is then called signing the Json Web Token. The signing algorithm takes the header, the payload, and the secret to create a unique signature. So only this data plus the secret can create this signature, all right?
Then together with the header and the payload, these signature forms the JWT,
which then gets sent to the client.

Once the server receives a JWT to grant access to a protected route, it needs to verify it in order to determine if the user really is who he claims to be. In other words, it will verify if no one changed the header and the payload data of the token. So again, this verification step will check if no third party actually altered either the header or the payload of the Json Web Token.

So, how does this verification actually work? Well, it is actually quite straightforward. Once the JWT is received, the verification will take its header and payload, and together with the secret that is still saved on the server, basically create a test signature.

But the original signature that was generated when the JWT was first created is still in the token, right? And that's the key to this verification. Because now all we have to do is to compare the test signature with the original signature.
And if the test signature is the same as the original signature, then it means that the payload and the header have not been modified.

Because if they had been modified, then the test signature would have to be different. Therefore in this case where there has been no alteration of the data, we can then authenticate the user. And of course, if the two signatures
are actually different, well, then it means that someone tampered with the data.
Usually by trying to change the payload. But that third party manipulating the payload does of course not have access to the secret, so they cannot sign the JWT.
So the original signature will never correspond to the manipulated data.
And therefore, the verification will always fail in this case. And that's the key to making this whole system work. It's the magic that makes JWT so simple,
but also extremely powerful.

Now let's do some practices with nodejs:

Configuration file is perfect for storing JWT SECRET data. Using the standard HSA 256 encryption for the signature, the secret should at least be 32 characters long, but the longer the better.

config.env:

```<code>JWT_SECRET = my-32-character-ultra-secure-and-ultra-long-secret
//after 90days JWT will no longer be valid, even the signuter is correct and everything is matched.
JWT_EXPIRES_IN=90
</code>```

now install JWT using command

```<code>npm i jsonwebtoken

</code>```

Example after user signup passing him JWT token so he can stay logged in and get access of resources.

```<code>exports.signup = catchAsync(async (req, res, next) => {
  const newUser = await User.create({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
    passwordConfirm: req.body.passwordConfirm,
  });
  const token = jwt.sign({ id: newUser._id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN,
  });

  res.status(201).json({
    status: 'success',
    token,
    data: {
      newUser,
    },
  });
});
</code>```

output:

In my opinion, do not take help from a third-party to generate your super-secret key, because you can't say it's secret anymore. Just use your keyboard.

Body:
Recently I started working with JWT-based authentication. After the user login, a user token is generated which will look like this:

"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ".

It consists of three parts each separated with a dot(.).First part is header which Base64 encoded. After decoding we will get something like:

{
  "alg": "HS256", //Algorithm used
  "typ": "JWT"
}

The second part is claims and Base64 encoded. After decoding we will get something like:

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

The third part is the signature and is generated with:

HMACSHA256(
 base64UrlEncode(header) + "." +
 base64UrlEncode(payload),
 *secret base64 encoded*
)

Now, what is this secret key, and how to generate this secret key?

I tried some online generators like: "http://kjur.github.io/jsjws/tool_jwt.html"

But, I didn't get much help.

Body:
A Json Web Token made up of three parts. The header, the payload and the signature Now the header is just some metadata about the token itself and the payload is the data that we can encode into the token, any data really that we want. So the more data we want to encode here the bigger the JWT. Anyway, these two parts are just plain text that will get encoded, but not encrypted.

So anyone will be able to decode them and to read them, we cannot store any sensitive data in here. But that's not a problem at all because in the third part, so in the signature, is where things really get interesting. The signature is created using the header, the payload, and the secret that is saved on the server.

And this whole process is then called signing the Json Web Token. The signing algorithm takes the header, the payload, and the secret to create a unique signature. So only this data plus the secret can create this signature, all right?
Then together with the header and the payload, these signature forms the JWT,
which then gets sent to the client.

Once the server receives a JWT to grant access to a protected route, it needs to verify it in order to determine if the user really is who he claims to be. In other words, it will verify if no one changed the header and the payload data of the token. So again, this verification step will check if no third party actually altered either the header or the payload of the Json Web Token.

So, how does this verification actually work? Well, it is actually quite straightforward. Once the JWT is received, the verification will take its header and payload, and together with the secret that is still saved on the server, basically create a test signature.

But the original signature that was generated when the JWT was first created is still in the token, right? And that's the key to this verification. Because now all we have to do is to compare the test signature with the original signature.
And if the test signature is the same as the original signature, then it means that the payload and the header have not been modified.

Because if they had been modified, then the test signature would have to be different. Therefore in this case where there has been no alteration of the data, we can then authenticate the user. And of course, if the two signatures
are actually different, well, then it means that someone tampered with the data.
Usually by trying to change the payload. But that third party manipulating the payload does of course not have access to the secret, so they cannot sign the JWT.
So the original signature will never correspond to the manipulated data.
And therefore, the verification will always fail in this case. And that's the key to making this whole system work. It's the magic that makes JWT so simple,
but also extremely powerful.

Now let's do some practices with nodejs:

Configuration file is perfect for storing JWT SECRET data. Using the standard HSA 256 encryption for the signature, the secret should at least be 32 characters long, but the longer the better.

config.env:

JWT_SECRET = my-32-character-ultra-secure-and-ultra-long-secret
//after 90days JWT will no longer be valid, even the signuter is correct and everything is matched.
JWT_EXPIRES_IN=90

now install JWT using command

npm i jsonwebtoken

Example after user signup passing him JWT token so he can stay logged in and get access of resources.

exports.signup = catchAsync(async (req, res, next) => {
  const newUser = await User.create({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
    passwordConfirm: req.body.passwordConfirm,
  });
  const token = jwt.sign({ id: newUser._id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN,
  });

  res.status(201).json({
    status: 'success',
    token,
    data: {
      newUser,
    },
  });
});

output:

In my opinion, do not take help from a third-party to generate your super-secret key, because you can't say it's secret anymore. Just use your keyboard.


问:
Combinging a PHP script with another PHP file, jQuery and HTML
I have a PHP search suggestion script which uses a MySQL database as its' back-end and jQuery to push the content to the search box page. The PHP is currently in suggest.php and my search box is on index.php. I want to put the PHP script from suggest.php into the index.php script code but it doesn't seem to work. Why could this be?

Here is my code for suggest.php:

```<code><?php

$database=new mysqli('localhost','username','password','database');

if(isset($_POST['query'])){
$query=$database->real_escape_string($_POST['query']);
            if(strlen($query)>0){
                $suggestions=$database->query("SELECT name, value FROM search WHERE name LIKE '%".$query."%' ORDER BY value DESC LIMIT 5");
                if($suggestions){
                    echo '<ul id="suggest">';
                    while($result=$suggestions->fetch_object()){
                        echo '<li>'.$result->name.'</li>';
                    }
                    echo '</ul>';
                }
            }
        }
?>
</code>```

Here is my code for index.php:

```<code><script type='text/javascript' src='js/jquery.js'></script>
<script type='text/javascript'>function lookup(a){if (a.length==0){$("#suggestions").hide();} else {$.post("suggest.php",{query:"" + a + ""},function (b){$("#suggestions").html(b).show();})}};</script>

<form id='search' method='post'>
<input type='text' id='query' onkeyup='lookup(this.value);'>
<div id='suggestions'></div>
</form>
</code>```

答: Once a PHP page has been sent out, there's no way to implement any further PHP code in it without a page refresh, if what @bbg says is true. I suggest you use AJAX which can send the request out to get the suggest.php script for execution on index.php. I also suggest you put the code in suggest.php in functions (they make code beautiful, my opinion).</p>

Body:
I have a PHP search suggestion script which uses a MySQL database as its' back-end and jQuery to push the content to the search box page. The PHP is currently in suggest.php and my search box is on index.php. I want to put the PHP script from suggest.php into the index.php script code but it doesn't seem to work. Why could this be?

Here is my code for suggest.php:

<?php

$database=new mysqli('localhost','username','password','database');

if(isset($_POST['query'])){
$query=$database->real_escape_string($_POST['query']);
            if(strlen($query)>0){
                $suggestions=$database->query("SELECT name, value FROM search WHERE name LIKE '%".$query."%' ORDER BY value DESC LIMIT 5");
                if($suggestions){
                    echo '
';
                    while($result=$suggestions->fetch_object()){
                        echo '
'.$result->name.'
';
                    }
                    echo '
';
                }
            }
        }
?>

Here is my code for index.php:

<form id='search' method='post'>
<input type='text' id='query' onkeyup='lookup(this.value);'>

</form>


问:
Connection Refused by Google Speech Recognition
I want to use SpeechRecognition in Python, and after installing all the requirements when I try it out with python -m speech_recognition, these messages came out:

```<code>A moment of silence, please...
Set a minimum energy threshold to 384.82495236781006
Say something!
Got it! Now to recognize it...
Uh oh! Couldn't request results from Google Speech Recognition service;
recognition connection failed: [Errno 61] Connection refused
</code>```

So what is this Error mean? How can I fix it? Many thanks
I'm using MacOS Catalina and Python 3.7.7

答: You exceeded the usage limits probably. You can try to use other open source services, they are even more reliable and you can run them locally.</p>

Body:
I want to use SpeechRecognition in Python, and after installing all the requirements when I try it out with python -m speech_recognition, these messages came out:

A moment of silence, please...
Set a minimum energy threshold to 384.82495236781006
Say something!
Got it! Now to recognize it...
Uh oh! Couldn't request results from Google Speech Recognition service;
recognition connection failed: [Errno 61] Connection refused

So what is this Error mean? How can I fix it? Many thanks
I'm using MacOS Catalina and Python 3.7.7