问:
InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
I have 2 certificates that I am using to make a GET request. The certificates are certs.pem and key.pem and these 2 certs when I am using with Python code it is giving me response. Below is Python code snippet that I am using -

```<code>url = "https://example.com"
cert = (certs.pem, key.pem)
response = requests.get(url, cert=cert, verify=False)
</code>```

Now same GET call I want to use in java. And since Java mostly accept .jks file. So, I am trying to convert both .pem files to single .jks file.

To convert to jks file I am first combining both .pem file using command- cat certs.pem key.pem > combined.pem.

After generating combined pem I am converting it to .p12 file using command-  openssl pkcs12 -export -in combined.pem -out cert.p12. I am not using any password while creating p12 file.

After generating .p12 file I am converting it to .crt file using command- openssl pkcs12 -in cert.p12 -clcerts -nokeys -out out_cert.crt

And finally I am converting to .jks file using below code snippet -

```<code>   private static Certificate readCert(String path) throws IOException, CertificateException {
        try (FileInputStream fin = new FileInputStream(path)) {
            return CertificateFactory.getInstance("X.509").generateCertificate(fin);
        }
    }

    // To convert into jks
    public static void generateCert() {
        try {
            // Reading the cert
            Certificate cert = readCert("out_cert.crt");

            // Creating an empty JKS keystore
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(null, null);

            // Adding the cert to the keystore
            keystore.setCertificateEntry("somecert", cert);

            // Saving the keystore with a zero length password
            FileOutputStream fout = new FileOutputStream("final_cert.jks");
            keystore.store(fout, new char[0]);
        } catch (GeneralSecurityException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
</code>```

Since I want to generate .jks file without password so I am using above code snippet. We can not generate .jks file without password with keytool.

Now finally after generating the .jks file, I am using below code snippet to make GET call -

```<code>    private static final String GET_API = "https://example.com";

    private static Client getClient() throws Exception {

        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream tsStream = getClass.getResourceAsStream(Constants.JKS_FILE_PATH);  //jks file that I have genearted from pem
        keystore.load(tsStream, null);
        TrustManagerFactory tmg = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmg.init(keystore);
        TrustManager[] trustManager = tmg.getTrustManagers();

        SSLContext sslContext = null;
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManager, null);

        return ClientBuilder.newBuilder()
                .sslContext(sslContext)
                .hostnameVerifier((s1, s2) -> true)
                .build();
    }

    public static void getAPI() {
        try {
            String response = getClient().target(GET_API)
                    .request(MediaType.APPLICATION_JSON)
                    .get(String.class);
            System.out.println("Response is "+response)
        } catch (Exception e) {
            logger.error("Error in calling get api , Exception {}",e);
        }
    }
</code>```

When I am running above code snippet to call getAPI(), I am getting error as -

```<code>javax.ws.rs.ProcessingException: javax.net.ssl.SSLException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
    at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:269) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:297) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.JerseyInvocation.lambda$invoke$1(JerseyInvocation.java:675) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.JerseyInvocation.call(JerseyInvocation.java:697) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.JerseyInvocation.lambda$runInScope$3(JerseyInvocation.java:691) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.internal.Errors.process(Errors.java:292) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.internal.Errors.process(Errors.java:274) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.internal.Errors.process(Errors.java:205) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:390) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.JerseyInvocation.runInScope(JerseyInvocation.java:691) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:674) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:422) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:318) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
Caused by: javax.net.ssl.SSLException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
    at sun.security.ssl.Alert.createSSLException(Alert.java:133) ~[?:1.8.0_312]
    at sun.security.ssl.TransportContext.fatal(TransportContext.java:348) ~[?:1.8.0_312]
    at sun.security.ssl.TransportContext.fatal(TransportContext.java:291) ~[?:1.8.0_312]
    at sun.security.ssl.TransportContext.fatal(TransportContext.java:286) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1589) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:452) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:410) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:197) ~[?:1.8.0_312]
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1572) ~[?:1.8.0_312]
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1500) ~[?:1.8.0_312]
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:352) ~[?:1.8.0_312]
    at org.glassfish.jersey.client.internal.HttpUrlConnector._apply(HttpUrlConnector.java:378) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:267) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    ... 15 more
Caused by: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
    at sun.security.validator.PKIXValidator.<init>(PKIXValidator.java:104) ~[?:1.8.0_312]
    at sun.security.validator.Validator.getInstance(Validator.java:181) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.getValidator(X509TrustManagerImpl.java:302) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.checkTrustedInit(X509TrustManagerImpl.java:176) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:189) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:129) ~[?:1.8.0_312]
    at sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:638) ~[?:1.8.0_312]
    at sun.security.ssl.CertificateMessage$T12CertificateConsumer.onCertificate(CertificateMessage.java:473) ~[?:1.8.0_312]
    at sun.security.ssl.CertificateMessage$T12CertificateConsumer.consume(CertificateMessage.java:369) ~[?:1.8.0_312]
    at sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:377) ~[?:1.8.0_312]
    at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:444) ~[?:1.8.0_312]
    at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:422) ~[?:1.8.0_312]
    at sun.security.ssl.TransportContext.dispatch(TransportContext.java:182) ~[?:1.8.0_312]
    at sun.security.ssl.SSLTransport.decode(SSLTransport.java:156) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1418) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1324) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:439) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:410) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:197) ~[?:1.8.0_312]
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1572) ~[?:1.8.0_312]
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1500) ~[?:1.8.0_312]
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:352) ~[?:1.8.0_312]
    at org.glassfish.jersey.client.internal.HttpUrlConnector._apply(HttpUrlConnector.java:378) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:267) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    ... 15 more
Caused by: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
    at java.security.cert.PKIXParameters.setTrustAnchors(PKIXParameters.java:200) ~[?:1.8.0_312]
    at java.security.cert.PKIXParameters.<init>(PKIXParameters.java:120) ~[?:1.8.0_312]
    at java.security.cert.PKIXBuilderParameters.<init>(PKIXBuilderParameters.java:104) ~[?:1.8.0_312]
    at sun.security.validator.PKIXValidator.<init>(PKIXValidator.java:102) ~[?:1.8.0_312]
    at sun.security.validator.Validator.getInstance(Validator.java:181) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.getValidator(X509TrustManagerImpl.java:302) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.checkTrustedInit(X509TrustManagerImpl.java:176) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:189) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:129) ~[?:1.8.0_312]
    at sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:638) ~[?:1.8.0_312]
    at sun.security.ssl.CertificateMessage$T12CertificateConsumer.onCertificate(CertificateMessage.java:473) ~[?:1.8.0_312]
    at sun.security.ssl.CertificateMessage$T12CertificateConsumer.consume(CertificateMessage.java:369) ~[?:1.8.0_312]
    at sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:377) ~[?:1.8.0_312]
    at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:444) ~[?:1.8.0_312]
    at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:422) ~[?:1.8.0_312]
    at sun.security.ssl.TransportContext.dispatch(TransportContext.java:182) ~[?:1.8.0_312]
    at sun.security.ssl.SSLTransport.decode(SSLTransport.java:156) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1418) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1324) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:439) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:410) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:197) ~[?:1.8.0_312]
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1572) ~[?:1.8.0_312]
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1500) ~[?:1.8.0_312]
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:352) ~[?:1.8.0_312]
    at org.glassfish.jersey.client.internal.HttpUrlConnector._apply(HttpUrlConnector.java:378) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:267) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    ... 15 more
</code>```

Can someone have any idea what is going wrong in my complete process?

Thanks in Advance :-)

Body:
I have 2 certificates that I am using to make a GET request. The certificates are certs.pem and key.pem and these 2 certs when I am using with Python code it is giving me response. Below is Python code snippet that I am using -

url = "https://example.com"
cert = (certs.pem, key.pem)
response = requests.get(url, cert=cert, verify=False)

Now same GET call I want to use in java. And since Java mostly accept .jks file. So, I am trying to convert both .pem files to single .jks file.

To convert to jks file I am first combining both .pem file using command- cat certs.pem key.pem > combined.pem.

After generating combined pem I am converting it to .p12 file using command-  openssl pkcs12 -export -in combined.pem -out cert.p12. I am not using any password while creating p12 file.

After generating .p12 file I am converting it to .crt file using command- openssl pkcs12 -in cert.p12 -clcerts -nokeys -out out_cert.crt

And finally I am converting to .jks file using below code snippet -

   private static Certificate readCert(String path) throws IOException, CertificateException {
        try (FileInputStream fin = new FileInputStream(path)) {
            return CertificateFactory.getInstance("X.509").generateCertificate(fin);
        }
    }

    // To convert into jks
    public static void generateCert() {
        try {
            // Reading the cert
            Certificate cert = readCert("out_cert.crt");

            // Creating an empty JKS keystore
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(null, null);

            // Adding the cert to the keystore
            keystore.setCertificateEntry("somecert", cert);

            // Saving the keystore with a zero length password
            FileOutputStream fout = new FileOutputStream("final_cert.jks");
            keystore.store(fout, new char[0]);
        } catch (GeneralSecurityException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

Since I want to generate .jks file without password so I am using above code snippet. We can not generate .jks file without password with keytool.

Now finally after generating the .jks file, I am using below code snippet to make GET call -

    private static final String GET_API = "https://example.com";

    private static Client getClient() throws Exception {

        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream tsStream = getClass.getResourceAsStream(Constants.JKS_FILE_PATH);  //jks file that I have genearted from pem
        keystore.load(tsStream, null);
        TrustManagerFactory tmg = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmg.init(keystore);
        TrustManager[] trustManager = tmg.getTrustManagers();

        SSLContext sslContext = null;
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManager, null);

        return ClientBuilder.newBuilder()
                .sslContext(sslContext)
                .hostnameVerifier((s1, s2) -> true)
                .build();
    }

    public static void getAPI() {
        try {
            String response = getClient().target(GET_API)
                    .request(MediaType.APPLICATION_JSON)
                    .get(String.class);
            System.out.println("Response is "+response)
        } catch (Exception e) {
            logger.error("Error in calling get api , Exception {}",e);
        }
    }

When I am running above code snippet to call getAPI(), I am getting error as -

javax.ws.rs.ProcessingException: javax.net.ssl.SSLException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
    at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:269) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:297) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.JerseyInvocation.lambda$invoke$1(JerseyInvocation.java:675) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.JerseyInvocation.call(JerseyInvocation.java:697) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.JerseyInvocation.lambda$runInScope$3(JerseyInvocation.java:691) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.internal.Errors.process(Errors.java:292) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.internal.Errors.process(Errors.java:274) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.internal.Errors.process(Errors.java:205) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:390) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.JerseyInvocation.runInScope(JerseyInvocation.java:691) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:674) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:422) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:318) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
Caused by: javax.net.ssl.SSLException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
    at sun.security.ssl.Alert.createSSLException(Alert.java:133) ~[?:1.8.0_312]
    at sun.security.ssl.TransportContext.fatal(TransportContext.java:348) ~[?:1.8.0_312]
    at sun.security.ssl.TransportContext.fatal(TransportContext.java:291) ~[?:1.8.0_312]
    at sun.security.ssl.TransportContext.fatal(TransportContext.java:286) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1589) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:452) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:410) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:197) ~[?:1.8.0_312]
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1572) ~[?:1.8.0_312]
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1500) ~[?:1.8.0_312]
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:352) ~[?:1.8.0_312]
    at org.glassfish.jersey.client.internal.HttpUrlConnector._apply(HttpUrlConnector.java:378) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:267) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    ... 15 more
Caused by: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
    at sun.security.validator.PKIXValidator.<init>(PKIXValidator.java:104) ~[?:1.8.0_312]
    at sun.security.validator.Validator.getInstance(Validator.java:181) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.getValidator(X509TrustManagerImpl.java:302) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.checkTrustedInit(X509TrustManagerImpl.java:176) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:189) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:129) ~[?:1.8.0_312]
    at sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:638) ~[?:1.8.0_312]
    at sun.security.ssl.CertificateMessage$T12CertificateConsumer.onCertificate(CertificateMessage.java:473) ~[?:1.8.0_312]
    at sun.security.ssl.CertificateMessage$T12CertificateConsumer.consume(CertificateMessage.java:369) ~[?:1.8.0_312]
    at sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:377) ~[?:1.8.0_312]
    at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:444) ~[?:1.8.0_312]
    at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:422) ~[?:1.8.0_312]
    at sun.security.ssl.TransportContext.dispatch(TransportContext.java:182) ~[?:1.8.0_312]
    at sun.security.ssl.SSLTransport.decode(SSLTransport.java:156) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1418) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1324) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:439) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:410) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:197) ~[?:1.8.0_312]
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1572) ~[?:1.8.0_312]
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1500) ~[?:1.8.0_312]
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:352) ~[?:1.8.0_312]
    at org.glassfish.jersey.client.internal.HttpUrlConnector._apply(HttpUrlConnector.java:378) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:267) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    ... 15 more
Caused by: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
    at java.security.cert.PKIXParameters.setTrustAnchors(PKIXParameters.java:200) ~[?:1.8.0_312]
    at java.security.cert.PKIXParameters.<init>(PKIXParameters.java:120) ~[?:1.8.0_312]
    at java.security.cert.PKIXBuilderParameters.<init>(PKIXBuilderParameters.java:104) ~[?:1.8.0_312]
    at sun.security.validator.PKIXValidator.<init>(PKIXValidator.java:102) ~[?:1.8.0_312]
    at sun.security.validator.Validator.getInstance(Validator.java:181) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.getValidator(X509TrustManagerImpl.java:302) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.checkTrustedInit(X509TrustManagerImpl.java:176) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:189) ~[?:1.8.0_312]
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:129) ~[?:1.8.0_312]
    at sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:638) ~[?:1.8.0_312]
    at sun.security.ssl.CertificateMessage$T12CertificateConsumer.onCertificate(CertificateMessage.java:473) ~[?:1.8.0_312]
    at sun.security.ssl.CertificateMessage$T12CertificateConsumer.consume(CertificateMessage.java:369) ~[?:1.8.0_312]
    at sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:377) ~[?:1.8.0_312]
    at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:444) ~[?:1.8.0_312]
    at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:422) ~[?:1.8.0_312]
    at sun.security.ssl.TransportContext.dispatch(TransportContext.java:182) ~[?:1.8.0_312]
    at sun.security.ssl.SSLTransport.decode(SSLTransport.java:156) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1418) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1324) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:439) ~[?:1.8.0_312]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:410) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:197) ~[?:1.8.0_312]
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1572) ~[?:1.8.0_312]
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1500) ~[?:1.8.0_312]
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480) ~[?:1.8.0_312]
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:352) ~[?:1.8.0_312]
    at org.glassfish.jersey.client.internal.HttpUrlConnector._apply(HttpUrlConnector.java:378) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:267) ~[get_api-1.0.0-SNAPSHOT-jar-with-dependencies.jar:?]
    ... 15 more

Can someone have any idea what is going wrong in my complete process?

Thanks in Advance :-)


来源: stackexchange

问:
how does browser knows when to do a full re render , when to call spa code to do partial update so that spa updates without reloading the page?
User requested data -> browser sends request to server -> Server sends the data -> browser received the data -> now usually if the response is html page,browser rerenders whole html page by reloading, which decreases user interactivity...

contrast to this, if the browser received only data rather than full html, then it calls spa framework like react to update some part or full render.

How does browser knows that it should call spa framework and how does it know when to do full reload and update the whole page?

consider ,If the browser does not know, just it calls spa framework in both the cases (either when it receives full html or just json/xml data) ,now spa recieved data, what is the point of reloading the page? just it can update the whole page without reloading right?

If my concepts are wrong, please correct me .

ContentLicense: CC BY-SA 4.0


问:
Flutter firebase_auth crashed after removed SafetyNet
My flutter app is using firebase_auth (v 4.2.1) plugin to verify the phone number and which worked perfectly. But then I got "Migrate your Google SafetyNet Attestation API" warning from Google Play. When I search, found that "SafetyNet" is used in this "firebase_auth" plugin. And as for a solution for this issue I found this link (Flutter Play Store Warning : play-services-safetynet 2022).

```<code>dependencies {
  implementation platform('com.google.firebase:firebase-bom:30.3.2')
  implementation 'com.google.firebase:firebase-auth'
}
configurations.all {
    exclude group: 'com.google.android.gms', module: 'play-services-safetynet'
}
</code>```

It removes "SafetyNet" from the dependency list. Now the app is crashed when tried to verify the phone number and getting following error.

```<code>E/AndroidRuntime(15766): java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/safetynet/SafetyNet;
E/AndroidRuntime(15766):    at com.google.firebase.auth.internal.zzf.zza(com.google.firebase:firebase-auth@@21.1.0:2)
E/AndroidRuntime(15766):    at com.google.firebase.auth.FirebaseAuth.zzI(com.google.firebase:firebase-auth@@21.1.0:26)
E/AndroidRuntime(15766):    at com.google.firebase.auth.PhoneAuthProvider.verifyPhoneNumber(com.google.firebase:firebase-auth@@21.1.0:2)
E/AndroidRuntime(15766):    at io.flutter.plugins.firebase.auth.PhoneNumberVerificationStreamHandler.onListen(PhoneNumberVerificationStreamHandler.java:180)
E/AndroidRuntime(15766):    at io.flutter.plugin.common.EventChannel$IncomingStreamRequestHandler.onListen(EventChannel.java:218)
E/AndroidRuntime(15766):    at io.flutter.plugin.common.EventChannel$IncomingStreamRequestHandler.onMessage(EventChannel.java:197)
E/AndroidRuntime(15766):    at io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:295)
E/AndroidRuntime(15766):    at io.flutter.embedding.engine.dart.DartMessenger.lambda$dispatchMessageToQueue$0$io-flutter-embedding-engine-dart-DartMessenger(DartMessenger.java:319)
E/AndroidRuntime(15766):    at io.flutter.embedding.engine.dart.DartMessenger$$ExternalSyntheticLambda0.run(D8$$SyntheticClass)
E/AndroidRuntime(15766):    at android.os.Handler.handleCallback(Handler.java:751)
E/AndroidRuntime(15766):    at android.os.Handler.dispatchMessage(Handler.java:95)
E/AndroidRuntime(15766):    at android.os.Looper.loop(Looper.java:154)
E/AndroidRuntime(15766):    at android.app.ActivityThread.main(ActivityThread.java:6077)
E/AndroidRuntime(15766):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(15766):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
E/AndroidRuntime(15766):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
E/AndroidRuntime(15766): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.safetynet.SafetyNet" on path: DexPathList[[zip file "/data/app/.../base.apk"],nativeLibraryDirectories=[/data/app/.../lib/x86, /data/app/.../base.apk!/lib/x86, /system/lib, /vendor/lib]]
E/AndroidRuntime(15766):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
E/AndroidRuntime(15766):    at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
E/AndroidRuntime(15766):    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
E/AndroidRuntime(15766):    ... 16 more
</code>```

I'm not sure whether the fix for "SafetyNet" is correct or not. If it is correct, what is the fix for this new issue? OR what is the best fix for "SafetyNet" issue

Body:
My flutter app is using firebase_auth (v 4.2.1) plugin to verify the phone number and which worked perfectly. But then I got "Migrate your Google SafetyNet Attestation API" warning from Google Play. When I search, found that "SafetyNet" is used in this "firebase_auth" plugin. And as for a solution for this issue I found this link (Flutter Play Store Warning : play-services-safetynet 2022).

dependencies {
  implementation platform('com.google.firebase:firebase-bom:30.3.2')
  implementation 'com.google.firebase:firebase-auth'
}
configurations.all {
    exclude group: 'com.google.android.gms', module: 'play-services-safetynet'
}

It removes "SafetyNet" from the dependency list. Now the app is crashed when tried to verify the phone number and getting following error.

E/AndroidRuntime(15766): java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/safetynet/SafetyNet;
E/AndroidRuntime(15766):    at com.google.firebase.auth.internal.zzf.zza(com.google.firebase:firebase-auth@@21.1.0:2)
E/AndroidRuntime(15766):    at com.google.firebase.auth.FirebaseAuth.zzI(com.google.firebase:firebase-auth@@21.1.0:26)
E/AndroidRuntime(15766):    at com.google.firebase.auth.PhoneAuthProvider.verifyPhoneNumber(com.google.firebase:firebase-auth@@21.1.0:2)
E/AndroidRuntime(15766):    at io.flutter.plugins.firebase.auth.PhoneNumberVerificationStreamHandler.onListen(PhoneNumberVerificationStreamHandler.java:180)
E/AndroidRuntime(15766):    at io.flutter.plugin.common.EventChannel$IncomingStreamRequestHandler.onListen(EventChannel.java:218)
E/AndroidRuntime(15766):    at io.flutter.plugin.common.EventChannel$IncomingStreamRequestHandler.onMessage(EventChannel.java:197)
E/AndroidRuntime(15766):    at io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:295)
E/AndroidRuntime(15766):    at io.flutter.embedding.engine.dart.DartMessenger.lambda$dispatchMessageToQueue$0$io-flutter-embedding-engine-dart-DartMessenger(DartMessenger.java:319)
E/AndroidRuntime(15766):    at io.flutter.embedding.engine.dart.DartMessenger$$ExternalSyntheticLambda0.run(D8$$SyntheticClass)
E/AndroidRuntime(15766):    at android.os.Handler.handleCallback(Handler.java:751)
E/AndroidRuntime(15766):    at android.os.Handler.dispatchMessage(Handler.java:95)
E/AndroidRuntime(15766):    at android.os.Looper.loop(Looper.java:154)
E/AndroidRuntime(15766):    at android.app.ActivityThread.main(ActivityThread.java:6077)
E/AndroidRuntime(15766):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(15766):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
E/AndroidRuntime(15766):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
E/AndroidRuntime(15766): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.safetynet.SafetyNet" on path: DexPathList[[zip file "/data/app/.../base.apk"],nativeLibraryDirectories=[/data/app/.../lib/x86, /data/app/.../base.apk!/lib/x86, /system/lib, /vendor/lib]]
E/AndroidRuntime(15766):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
E/AndroidRuntime(15766):    at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
E/AndroidRuntime(15766):    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
E/AndroidRuntime(15766):    ... 16 more

I'm not sure whether the fix for "SafetyNet" is correct or not. If it is correct, what is the fix for this new issue? OR what is the best fix for "SafetyNet" issue


问:
Why disabled elements got tabindex? in editor menu items ex: edit, table, file
I need to confirmation from tiny mce editor.
-->why disabled elements accessible with the tab.
-->example: In editor menu edit, table have disabled elements still able to access with tab property.
-->normally we don't access those disabled elements.
why disabled elements getting tab index and focus
why disabled elements getting tab index and focus
why disabled elements getting tab index and focus

disabled elements not accessible with tabindex and focus.


问:
Wanted to read data from postgresql and write it to response to client in nodejs via stream
I've created a get api that takes almost many minutes to complete. I want to read the data from postgresql (using knex) and write it to the response to the client via nodejs stream because I want to make things faster. My table has about 8.7 million rows, and I want to show it on the dashboard without pagination.

I tried reading blogs and everything, but I was unable to find a specific solution.


问:
Gradle Error : Illegal null value provided in this collection
I am trying to update my spring boot version to 2.7.6 which requires gradle v6.8+ against the current version of 5.3 . But when i try to do a clean build, it fails with below error. I am not finding many solutions in the internet for this so far. Any help would be greatly appreciated.

```<code>------------------------------------------------------------
Gradle 6.8.3
------------------------------------------------------------

Build time:   2021-02-22 16:13:28 UTC
Revision:     9e26b4a9ebb910eaa1b8da8ff8575e514bc61c78

Kotlin:       1.4.20
Groovy:       2.5.12
Ant:          Apache Ant(TM) version 1.10.9 compiled on September 27 2020
JVM:          1.8.0_332-internal (OpenLogic-OpenJDK 25.332-b09)
OS:           Mac OS X 10.16 x86_64

test@test-mac test-service % gradle clean build
Starting a Gradle Daemon (subsequent builds will be faster)
> Task :buildSrc:compileJava NO-SOURCE
> Task :buildSrc:compileGroovy
> Task :buildSrc:processResources NO-SOURCE
> Task :buildSrc:classes
> Task :buildSrc:jar
> Task :buildSrc:assemble
> Task :buildSrc:compileTestJava NO-SOURCE
> Task :buildSrc:compileTestGroovy NO-SOURCE
> Task :buildSrc:processTestResources NO-SOURCE
> Task :buildSrc:testClasses UP-TO-DATE
> Task :buildSrc:test NO-SOURCE
> Task :buildSrc:check UP-TO-DATE
> Task :buildSrc:build

FAILURE: Build failed with an exception.

* Where:
Script '/Users/fazshaik/Developer/related-items-service/build-support/packaging.gradle' line: 14

* What went wrong:
A problem occurred evaluating script.
> Illegal null value provided in this collection: [login, -u, null, -p, null, phx.ocir.io]

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 11s
</code>```

The error says it fails at line NO 14 in package.gradle, but the same was working without any issues with gradle 5.3 . Below is my package.gradle file.

```<code>ext {
    dockerRegistry = "docker.test.registry"
}

task buildInformation {
    def gitSha = "git rev-parse --short HEAD"

    ext.localRepository = "test/test/testProject/$rootProject.name"
    ext.remoteRepository = "${dockerRegistry}/${localRepository}"
    ext.tag = gitSha.execute().text.trim()
}

task loginToDockerRegistry(type: Exec) {
    **** LINE NO 14 ==> commandLine "docker", "login", "-u", System.getenv("DOCKER_REGISTRY_USERNAME"), "-p", System.getenv("DOCKER_REGISTRY_PASSWORD"), dockerRegistry
}

task createDockerImageFromFatJar(type: Exec) {
    commandLine "docker", "build", "-t", "${buildInformation.localRepository}:${buildInformation.tag}", "."
}

createDockerImageFromFatJar.mustRunAfter('bootJar')

task createDockerImage(dependsOn: [ 'bootJar', 'createDockerImageFromFatJar']) {
}

task tagAsRemote(type: Exec) {
    commandLine "docker", "tag", "${buildInformation.localRepository}:${buildInformation.tag}", "${buildInformation.remoteRepository}:${buildInformation.tag}"
    println 'Docker image tagged as '+buildInformation.tag
}

task pushDockerImage(type: Exec, dependsOn: [tagAsRemote] ) {
    commandLine "docker", "push", "${buildInformation.remoteRepository}:${buildInformation.tag}"
    println 'Published docker image '+buildInformation.remoteRepository+":"+buildInformation.tag
}

task publishDockerImage(dependsOn: ['createDockerImage', 'pushDockerImage'])

pushDockerImage.mustRunAfter('createDockerImage')
</code>```

Body:
I am trying to update my spring boot version to 2.7.6 which requires gradle v6.8+ against the current version of 5.3 . But when i try to do a clean build, it fails with below error. I am not finding many solutions in the internet for this so far. Any help would be greatly appreciated.

------------------------------------------------------------
Gradle 6.8.3
------------------------------------------------------------

Build time:   2021-02-22 16:13:28 UTC
Revision:     9e26b4a9ebb910eaa1b8da8ff8575e514bc61c78

Kotlin:       1.4.20
Groovy:       2.5.12
Ant:          Apache Ant(TM) version 1.10.9 compiled on September 27 2020
JVM:          1.8.0_332-internal (OpenLogic-OpenJDK 25.332-b09)
OS:           Mac OS X 10.16 x86_64

test@test-mac test-service % gradle clean build
Starting a Gradle Daemon (subsequent builds will be faster)
> Task :buildSrc:compileJava NO-SOURCE
> Task :buildSrc:compileGroovy
> Task :buildSrc:processResources NO-SOURCE
> Task :buildSrc:classes
> Task :buildSrc:jar
> Task :buildSrc:assemble
> Task :buildSrc:compileTestJava NO-SOURCE
> Task :buildSrc:compileTestGroovy NO-SOURCE
> Task :buildSrc:processTestResources NO-SOURCE
> Task :buildSrc:testClasses UP-TO-DATE
> Task :buildSrc:test NO-SOURCE
> Task :buildSrc:check UP-TO-DATE
> Task :buildSrc:build

FAILURE: Build failed with an exception.

* Where:
Script '/Users/fazshaik/Developer/related-items-service/build-support/packaging.gradle' line: 14

* What went wrong:
A problem occurred evaluating script.
> Illegal null value provided in this collection: [login, -u, null, -p, null, phx.ocir.io]

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 11s

The error says it fails at line NO 14 in package.gradle, but the same was working without any issues with gradle 5.3 . Below is my package.gradle file.

ext {
    dockerRegistry = "docker.test.registry"
}

task buildInformation {
    def gitSha = "git rev-parse --short HEAD"

    ext.localRepository = "test/test/testProject/$rootProject.name"
    ext.remoteRepository = "${dockerRegistry}/${localRepository}"
    ext.tag = gitSha.execute().text.trim()
}

task loginToDockerRegistry(type: Exec) {
    **** LINE NO 14 ==> commandLine "docker", "login", "-u", System.getenv("DOCKER_REGISTRY_USERNAME"), "-p", System.getenv("DOCKER_REGISTRY_PASSWORD"), dockerRegistry
}

task createDockerImageFromFatJar(type: Exec) {
    commandLine "docker", "build", "-t", "${buildInformation.localRepository}:${buildInformation.tag}", "."
}

createDockerImageFromFatJar.mustRunAfter('bootJar')

task createDockerImage(dependsOn: [ 'bootJar', 'createDockerImageFromFatJar']) {
}

task tagAsRemote(type: Exec) {
    commandLine "docker", "tag", "${buildInformation.localRepository}:${buildInformation.tag}", "${buildInformation.remoteRepository}:${buildInformation.tag}"
    println 'Docker image tagged as '+buildInformation.tag
}

task pushDockerImage(type: Exec, dependsOn: [tagAsRemote] ) {
    commandLine "docker", "push", "${buildInformation.remoteRepository}:${buildInformation.tag}"
    println 'Published docker image '+buildInformation.remoteRepository+":"+buildInformation.tag
}

task publishDockerImage(dependsOn: ['createDockerImage', 'pushDockerImage'])

pushDockerImage.mustRunAfter('createDockerImage')


问:
mina-sshd server-side heartbeat not working
I'm trying to implement an sshd server by mina-sshd framework, want to make each session has a keepalive heartbeat , but mina-sshd setSessionHeartbeat api doesn't work.

Server Code:

```<code>SshServer sshd = SshServer.setUpDefaultServer();
sshd.setPort(3333);
sshd.setShellFactory(InteractiveProcessShellFactory.INSTANCE);
sshd.setSessionHeartbeat(SessionHeartbeatController.HeartbeatType.IGNORE, Duration.ofSeconds(5));
sshd.setKeyPairProvider(new ClassLoadableResourceKeyPairProvider(getClass().getClassLoader(), "rsa.key"));
sshd.setPasswordAuthenticator((username, password, session) -> username.equals(password));
sshd.start();
log.info("SSHD server started");
</code>```

Client:

```<code>user/passwd = test

ssh test@127.0.0.1 -p3333
</code>```

Body:
I'm trying to implement an sshd server by mina-sshd framework, want to make each session has a keepalive heartbeat , but mina-sshd setSessionHeartbeat api doesn't work.

Server Code:

SshServer sshd = SshServer.setUpDefaultServer();
sshd.setPort(3333);
sshd.setShellFactory(InteractiveProcessShellFactory.INSTANCE);
sshd.setSessionHeartbeat(SessionHeartbeatController.HeartbeatType.IGNORE, Duration.ofSeconds(5));
sshd.setKeyPairProvider(new ClassLoadableResourceKeyPairProvider(getClass().getClassLoader(), "rsa.key"));
sshd.setPasswordAuthenticator((username, password, session) -> username.equals(password));
sshd.start();
log.info("SSHD server started");

Client:

user/passwd = test

ssh test@127.0.0.1 -p3333


问:
How to get input data from html to nodejs
I am learning node, express and I want get input from html form, something like a signup form to js so that I can get it in mongoDB.

The error:

```<code>TypeError: Cannot read properties of undefined (reading 'uname')
    at exports.chat_create (E:\JS_stuff\controllers\chat.controller.js:20:26)
    at Layer.handle [as handle_request] (E:\JS_stuff\node_modules\express\lib\router\layer.js:95:5)
    at next (E:\JS_stuff\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (E:\JS_stuff\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (E:\JS_stuff\node_modules\express\lib\router\layer.js:95:5)
    at E:\JS_stuff\node_modules\express\lib\router\index.js:284:15
    at Function.process_params (E:\JS_stuff\node_modules\express\lib\router\index.js:346:12)
    at next (E:\JS_stuff\node_modules\express\lib\router\index.js:280:10)
    at Function.handle (E:\JS_stuff\node_modules\express\lib\router\index.js:175:3)
    at router (E:\JS_stuff\node_modules\express\lib\router\index.js:47:12)
</code>```

What I want to do is get the input from field uname and umail to js so it can insert into mongodb.

This works if I don't try to take input and just add value, something like name : 'name'.
Here is the code:

controller.js

```<code>const { default: mongoose } = require('mongoose');
const request = require('request');
const Chats = require('../models/chat.model');

exports.test = function(req, res) {
    res.send('Hello, this is a test controller!');
};

exports.chat_create = function(req, res, next) {
    var uname = req.body.uname;
    var umail = req?.body?.umail;
    let ch = new Chats({
        name: uname,
        mail: umail
    });

    ch.save(function (err) {
        if (err) {
            return next(err);
        }
        res.send('Chat added.');
    })
};
</code>```

model.js

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let ChatSchema = new Schema({
    name : {type: String, required: true},
    mail: {type: String},
});

module.exports = mongoose.model('Chats', ChatSchema);
</code>```

route.js

```<code>const express = require('express');
const router = express.Router();

const chat_controller = require('../controllers/chat.controller');

router.get('/test', chat_controller.test);
router.get('/create', chat_controller.chat_create);
router.get('/read/:id', chat_controller.read_chat);
router.get('/:id/update', chat_controller.update_chat);
router.get('/delete/:id', chat_controller.delete_chat);

module.exports = router;
</code>```
```<code>app.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
var jsdom = require("jsdom");
var JSDOM = jsdom.JSDOM;
// const request = require('request');
// import route
const chat = require('./routes/chat.route');

// initialize app
const app = express();
app.set("view engine", "ejs")
app.engine('ejs', require('ejs').__express);
app.use('/chat', chat);

// set up mongoose connection
let db_url = 'the url';
let mongoDB = process.env.MONGODB_URI || db_url;
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error: '));

app.use(bodyParser.json());
app._router.use(bodyParser.urlencoded({extended: false}));

// port
let port  = 1234;
app.listen(port, () => {
    console.log("Server is running on port " + port);
});

app.get('/chat', function (req, res) {
    res.render("form");
});
</code>```

form.ejs

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://unicons.iconscout.com/release/v4.0.0/css/line.css">
    <link rel="stylesheet" href="form.css">
</head>
<body>
    <div class="container">
        <div class="forms">
            <div class="form signup">
                <span class="title">Register</span>
                    <form action="/chat/create" method="POST">
                    <div class="input-field">
                        <input type="text" id="uname" placeholder="Enter your name" required>
                        <i class="uil uil-user"></i>
                    </div>

                    <div class="input-field">
                        <input type="text" id="umail" placeholder="Enter your email" required>
                        <i class="uil uil-envelope icon"></i>
                    </div>

                    <a href="/chat/create">
                        <div class="input-field button">
                            <input type="submit" value="Register">
                        </div>
                    </a>
              </form>

            </div>
        </div>
    </div>
    <script type="text/javascript" src="app.js"></script>

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

Body:
I am learning node, express and I want get input from html form, something like a signup form to js so that I can get it in mongoDB.

The error:

TypeError: Cannot read properties of undefined (reading 'uname')
    at exports.chat_create (E:\JS_stuff\controllers\chat.controller.js:20:26)
    at Layer.handle [as handle_request] (E:\JS_stuff\node_modules\express\lib\router\layer.js:95:5)
    at next (E:\JS_stuff\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (E:\JS_stuff\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (E:\JS_stuff\node_modules\express\lib\router\layer.js:95:5)
    at E:\JS_stuff\node_modules\express\lib\router\index.js:284:15
    at Function.process_params (E:\JS_stuff\node_modules\express\lib\router\index.js:346:12)
    at next (E:\JS_stuff\node_modules\express\lib\router\index.js:280:10)
    at Function.handle (E:\JS_stuff\node_modules\express\lib\router\index.js:175:3)
    at router (E:\JS_stuff\node_modules\express\lib\router\index.js:47:12)

What I want to do is get the input from field uname and umail to js so it can insert into mongodb.

This works if I don't try to take input and just add value, something like name : 'name'.
Here is the code:

controller.js

const { default: mongoose } = require('mongoose');
const request = require('request');
const Chats = require('../models/chat.model');

exports.test = function(req, res) {
    res.send('Hello, this is a test controller!');
};

exports.chat_create = function(req, res, next) {
    var uname = req.body.uname;
    var umail = req?.body?.umail;
    let ch = new Chats({
        name: uname,
        mail: umail
    });

    ch.save(function (err) {
        if (err) {
            return next(err);
        }
        res.send('Chat added.');
    })
};

model.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let ChatSchema = new Schema({
    name : {type: String, required: true},
    mail: {type: String},
});

module.exports = mongoose.model('Chats', ChatSchema);

route.js

const express = require('express');
const router = express.Router();

const chat_controller = require('../controllers/chat.controller');

router.get('/test', chat_controller.test);
router.get('/create', chat_controller.chat_create);
router.get('/read/:id', chat_controller.read_chat);
router.get('/:id/update', chat_controller.update_chat);
router.get('/delete/:id', chat_controller.delete_chat);

module.exports = router;

app.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
var jsdom = require("jsdom");
var JSDOM = jsdom.JSDOM;
// const request = require('request');
// import route
const chat = require('./routes/chat.route');

// initialize app
const app = express();
app.set("view engine", "ejs")
app.engine('ejs', require('ejs').__express);
app.use('/chat', chat);

// set up mongoose connection
let db_url = 'the url';
let mongoDB = process.env.MONGODB_URI || db_url;
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error: '));

app.use(bodyParser.json());
app._router.use(bodyParser.urlencoded({extended: false}));

// port
let port  = 1234;
app.listen(port, () => {
    console.log("Server is running on port " + port);
});

app.get('/chat', function (req, res) {
    res.render("form");
});

form.ejs

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://unicons.iconscout.com/release/v4.0.0/css/line.css">
    <link rel="stylesheet" href="form.css">

                Register
                    <form action="/chat/create" method="POST">

                        <input type="text" id="uname" placeholder="Enter your name" required>

                        <input type="text" id="umail" placeholder="Enter your email" required>

                            <input type="submit" value="Register">

              </form>


问:
Django - I want to store the data of 3 models into a single database in phpmyadmin (MySQL)
I have created 3 models (country, state and city) and the inputted data is getting stored in 3 different table. I want to store this data into a single table with following columns:

Database Column Schema

Models.py

```<code>class Country(models.Model):
    id = models.AutoField(primary_key=True)
    parent_id = models.IntegerField(null=False)
    name = models.CharField(null=False, max_length=255)
    status = models.CharField(null= True, choices=Status_Choices, max_length=11, default='--Select Status--')
    added_by = models.IntegerField()
    updated_by = models.IntegerField()
    created_on = models.CharField(default=get_current_datetime_str , max_length=255)
    updated_on = models.CharField(default=get_current_datetime_str, max_length=255)

    def __str__(self):
        return self.name

class State(models.Model):
    parent = models.ForeignKey(Country, on_delete=models.CASCADE)
    name = models.CharField(null=False, max_length=255)

    def __str__(self):
        return self.name

class City(models.Model):
    Country = models.ForeignKey(Country, on_delete=models.CASCADE)
    state = models.ForeignKey(State, on_delete=models.CASCADE)
    name = models.CharField(null=False, max_length=255)

    def __str__(self):
        return self.name

</code>```

admin.py

```<code>from django.contrib import admin
from location.models import Country, State, City
from django import forms
from django.contrib import admin

class CountryAdmin(admin.ModelAdmin):
    exclude = ('parent_id', 'created_on', 'updated_on', 'added_by', 'updated_by')

    def save_model(self, request, obj, form, change):
        user = request.user

        # Check if the user is authenticated (i.e. logged in)
        if user.is_authenticated:
            # If the user is authenticated, set the added_by field to the user's ID
            obj.added_by = user.id
        else:
            # The user is not authenticated, do something else
            ...

        if change:
            obj.updated_by = user.id

        # Save the model instance
        super().save_model(request, obj, form, change)

admin.site.register(Country, CountryAdmin)

@admin.register(State)
class StateAdmin(admin.ModelAdmin):
    # Define the fields to be displayed in the list view of states
    list_display = ('name', 'parent')

    # Set the heading for the states page in the Django admin interface
    verbose_name_plural = 'Locations'

@admin.register(City)
class StateAdmin(admin.ModelAdmin):
    # Define the fields to be displayed in the list view of states
    list_display = ('name', 'state')

    # Set the heading for the states page in the Django admin interface
    verbose_name_plural = 'Locations'
</code>```

forms.py

```<code>from django import forms
from .models import Country, State, City

class CountryForm(forms.ModelForm):
    class Meta:
        model = Country
        fields = ['name']

    def clean_name(self):
        name = self.cleaned_data['name']
        if name == '--Select Country--':
            raise forms.ValidationError("Please select a valid country")
        return name

class StateForm(forms.ModelForm):
    class Meta:
        model = State
        fields = ['name', 'parent']

class CityForm(forms.ModelForm):
    class Meta:
        model = City
        fields = ['name', 'state']
</code>```

I tried merging them but for that i have to add extra column for city and state. I want everything to be stored under name corresponding to their parent id (refer database schema).

Body:
I have created 3 models (country, state and city) and the inputted data is getting stored in 3 different table. I want to store this data into a single table with following columns:

Database Column Schema

Models.py

class Country(models.Model):
    id = models.AutoField(primary_key=True)
    parent_id = models.IntegerField(null=False)
    name = models.CharField(null=False, max_length=255)
    status = models.CharField(null= True, choices=Status_Choices, max_length=11, default='--Select Status--')
    added_by = models.IntegerField()
    updated_by = models.IntegerField()
    created_on = models.CharField(default=get_current_datetime_str , max_length=255)
    updated_on = models.CharField(default=get_current_datetime_str, max_length=255)

    def __str__(self):
        return self.name

class State(models.Model):
    parent = models.ForeignKey(Country, on_delete=models.CASCADE)
    name = models.CharField(null=False, max_length=255)

    def __str__(self):
        return self.name

class City(models.Model):
    Country = models.ForeignKey(Country, on_delete=models.CASCADE)
    state = models.ForeignKey(State, on_delete=models.CASCADE)
    name = models.CharField(null=False, max_length=255)

    def __str__(self):
        return self.name

admin.py

from django.contrib import admin
from location.models import Country, State, City
from django import forms
from django.contrib import admin

class CountryAdmin(admin.ModelAdmin):
    exclude = ('parent_id', 'created_on', 'updated_on', 'added_by', 'updated_by')

    def save_model(self, request, obj, form, change):
        user = request.user

        # Check if the user is authenticated (i.e. logged in)
        if user.is_authenticated:
            # If the user is authenticated, set the added_by field to the user's ID
            obj.added_by = user.id
        else:
            # The user is not authenticated, do something else
            ...

        if change:
            obj.updated_by = user.id

        # Save the model instance
        super().save_model(request, obj, form, change)

admin.site.register(Country, CountryAdmin)

@admin.register(State)
class StateAdmin(admin.ModelAdmin):
    # Define the fields to be displayed in the list view of states
    list_display = ('name', 'parent')

    # Set the heading for the states page in the Django admin interface
    verbose_name_plural = 'Locations'

@admin.register(City)
class StateAdmin(admin.ModelAdmin):
    # Define the fields to be displayed in the list view of states
    list_display = ('name', 'state')

    # Set the heading for the states page in the Django admin interface
    verbose_name_plural = 'Locations'

forms.py

from django import forms
from .models import Country, State, City

class CountryForm(forms.ModelForm):
    class Meta:
        model = Country
        fields = ['name']

    def clean_name(self):
        name = self.cleaned_data['name']
        if name == '--Select Country--':
            raise forms.ValidationError("Please select a valid country")
        return name

class StateForm(forms.ModelForm):
    class Meta:
        model = State
        fields = ['name', 'parent']

class CityForm(forms.ModelForm):
    class Meta:
        model = City
        fields = ['name', 'state']

I tried merging them but for that i have to add extra column for city and state. I want everything to be stored under name corresponding to their parent id (refer database schema).


问:
How to access Authorization code flow, Implicit Flow and Hybrid flow in Django oauth toolkit
I want to implement OpenID connect in my project.

So I started using Django Oauth Toolkit.

I was able to make the changes in Dajango Rest framework menu and was able to test the Resource owner password-based flow using the curl command

```<code>curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/
</code>```

After that I made all the changes as mentioned in the OpenId Connect menu.

I have

Generated RSA private key

Added the changes as mentioned in the documentation

Then I registered applications for each flow as mentioned in the documentation.

Then the problem arise. I tried testing these flows the same way I tested Resource owner password-based flow
eg:

For Authorization code flow

curl -X POST -d "grant_type=password&username=user&password=aryan123&scope=openid" -u "rwOah6DU7PXPbpE7CWVokh16YeMIFsPCE4zv1ZUk:5p186YD3Wvf0nMz4bfXd9UJXbQnACMfpVzHwJ6AuneoPqnjJuoPUz4CiEM653gUIhCOMtV96Yymr1kLnAimdyfxWZMP2hOzslEH9kMpfoqyOorwviY8f1rs1BqcTSUtn" http://localhost:8000/o/token/

```<code>I'm getting the error:

{
    "error": "invalid_grant",
    "error_description": "Invalid credentials given."
}
</code>```

For Implicit Flow

curl -X POST -d "grant_type=password&username=user&password=aryan123&scope=openid&response_type=id_token" -u "qKgH4Bx5QzOdSdRo5h7vUSpSaivHk0SaccMa0coH:DyNdcoS52JuanNhjjqqbRnemGaq27sQrwa43C6ieYahxCdHYXXJt4Y5ZdwXVbNZdZmt89XoAJ7kBuFoDZanZvhCCza3WMLWlCwSy5qv09W1QyJsLmTEGUzRHkytU21s1" http://localhost:8000/o/token/

```<code>I'm getting the error:
{
    "error": "invalid_grant",
    "error_description": "Invalid credentials given."
}
</code>```

For Hybrid flow

curl -X POST -d "grant_type=password&username=user&password=aryan123" -u "YpKesUZnxyvOysKje4H2NNFhs45roO8z0SBu58Y5:Yf2IAsMRoLCbLrEUHsgPByLLnmFrNYPvqtYXuaZAJV5HbHioFZtbsTzh6Oj1W7jgWOKVU0PLsUwBPO0j5y7fhOLbUFiH2X9ZhdnQ3wJ7KxFOjTHYu2Cd52IxGO7U3iF3" http://localhost:8000/o/token/

```<code>I'm getting the error:
{
    "error": "invalid_grant",
    "error_description": "Invalid credentials given."
}
</code>```

For the development purpose I have generated the private key and stored it in a python file itself like this

Note: The private key had some spaces and i removed it due to error

I'm confused about the parameters that needs to be passed in the curl. Maybe that's the problem or something else, which I'm not able to identify

Need your insight on this one.
Thanks...

Body:
I want to implement OpenID connect in my project.

So I started using Django Oauth Toolkit.

I was able to make the changes in Dajango Rest framework menu and was able to test the Resource owner password-based flow using the curl command

curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/

After that I made all the changes as mentioned in the OpenId Connect menu.

I have

Generated RSA private key

Added the changes as mentioned in the documentation

Then I registered applications for each flow as mentioned in the documentation.

Then the problem arise. I tried testing these flows the same way I tested Resource owner password-based flow
eg:

For Authorization code flow

curl -X POST -d "grant_type=password&username=user&password=aryan123&scope=openid" -u "rwOah6DU7PXPbpE7CWVokh16YeMIFsPCE4zv1ZUk:5p186YD3Wvf0nMz4bfXd9UJXbQnACMfpVzHwJ6AuneoPqnjJuoPUz4CiEM653gUIhCOMtV96Yymr1kLnAimdyfxWZMP2hOzslEH9kMpfoqyOorwviY8f1rs1BqcTSUtn" http://localhost:8000/o/token/

I'm getting the error:

{
    "error": "invalid_grant",
    "error_description": "Invalid credentials given."
}

For Implicit Flow

curl -X POST -d "grant_type=password&username=user&password=aryan123&scope=openid&response_type=id_token" -u "qKgH4Bx5QzOdSdRo5h7vUSpSaivHk0SaccMa0coH:DyNdcoS52JuanNhjjqqbRnemGaq27sQrwa43C6ieYahxCdHYXXJt4Y5ZdwXVbNZdZmt89XoAJ7kBuFoDZanZvhCCza3WMLWlCwSy5qv09W1QyJsLmTEGUzRHkytU21s1" http://localhost:8000/o/token/

I'm getting the error:
{
    "error": "invalid_grant",
    "error_description": "Invalid credentials given."
}

For Hybrid flow

curl -X POST -d "grant_type=password&username=user&password=aryan123" -u "YpKesUZnxyvOysKje4H2NNFhs45roO8z0SBu58Y5:Yf2IAsMRoLCbLrEUHsgPByLLnmFrNYPvqtYXuaZAJV5HbHioFZtbsTzh6Oj1W7jgWOKVU0PLsUwBPO0j5y7fhOLbUFiH2X9ZhdnQ3wJ7KxFOjTHYu2Cd52IxGO7U3iF3" http://localhost:8000/o/token/

I'm getting the error:
{
    "error": "invalid_grant",
    "error_description": "Invalid credentials given."
}

For the development purpose I have generated the private key and stored it in a python file itself like this

Note: The private key had some spaces and i removed it due to error

I'm confused about the parameters that needs to be passed in the curl. Maybe that's the problem or something else, which I'm not able to identify

Need your insight on this one.
Thanks...


问:
Merge transactions of two tables

Thanks for your attention to answer the question.
You can understand this problem seeing Above image or
My Question is that I have table1 in which I am inserting Issue Items details and I have table2 in which I am inserting Receive Items details. There are two case which have to cover first case is - when I issue 3 items and receive 5 Items Or second case is - when I issue 10 Items I receive 4 item. Please help to give the solution for the same.

I tried joins and union to solve this but did not resolve it.

Title: Merge transactions of two tables


问:
context is fragment is always false
I want to show some common snackbar by context.
When the context is Activity, Fragment or DialogFragment, I want to handle by them.
So I wrote codes like below, but it doesn't work at Fragment or DialogFragment.
I can only check that the context is activty.
I don't understand why context is fragment is not working.

```<code>fun Context.showSnackBar(text: String) {
    when(this) {
        is Fragment,  // not working
        is DialogFragment -> { // not working
            showSnackBar(text)
        }
        is Activity -> {
            showSnackBar(text)
        }
    }
}

</code>```

usecase updated

```<code>1. RootApplication.context.showSnackBar()

2. passed paramter context -> fun foo(context: Context){context.showSnackBar()}

3. binding View's context -> binding.text.context.showSnackBar()

</code>```

Title: context is fragment is always false

Body:
I want to show some common snackbar by context.
When the context is Activity, Fragment or DialogFragment, I want to handle by them.
So I wrote codes like below, but it doesn't work at Fragment or DialogFragment.
I can only check that the context is activty.
I don't understand why context is fragment is not working.

fun Context.showSnackBar(text: String) {
    when(this) {
        is Fragment,  // not working
        is DialogFragment -> { // not working
            showSnackBar(text)
        }
        is Activity -> {
            showSnackBar(text)
        }
    }
}

usecase updated

1. RootApplication.context.showSnackBar()

2. passed paramter context -> fun foo(context: Context){context.showSnackBar()}

3. binding View's context -> binding.text.context.showSnackBar()


问:
Flutter Web Email Attachment as PDF
Can Someone please help me out regarding Email Attachment in flutter Web. I have already done this thing easily in the Android Using the path_provider to first store it in the Temp Directory and then getting the path to share it on the email or anywhere. But Unfortunately path_provider doesn't support in web. So I want that same thing in flutter web. My PDF file is converted into Bytes. How can I Attach that file with the Email in windows or Mac using Flutter Web.

I have Tried share_plus and path_provider in web but path_provider doesn't support in web similarly dart:io.

Title: Flutter Web Email Attachment as PDF


问:
Highlight characters within words in Opensearch query
I have set up a custom analyser that uses an edge_ngram filter for a text field. I'm then trying to highlight the characters a user types but opensearch is highlighting the entire word, even if only a small number of characters have been typed.

E.g. Typing "Man" in the search bar will result in the word "Manly" being highlighted. Manly Trail Running Tour. What I really want is Manly Trail Running Tour.

This should be possible with the fvh highlighting type and chars as the boundary_scanner argument per the docs https://opensearch.org/docs/2.1/opensearch/search/highlight/#highlighting-options

Settings

```<code>"title_autocomplete": {
  "type": "text",
  "term_vector": "with_positions_offsets",
  "analyzer": "autocomplete"
}

"analysis": {
  "filter": {
    "edge_ngram_filter": {
      "type": "edge_ngram",
      "min_gram": "3",
      "max_gram": "20"
    }
  },
  "analyzer": {
    "autocomplete": {
      "filter": [
        "lowercase",
        "edge_ngram_filter"
       ],
       "type": "custom",
       "tokenizer": "standard"
    }
  }
}
</code>```

Query:

```<code>
{
  "track_total_hits": true,
  "highlight": {
    "type": "fvh",
    "boundary_scanner": "chars",
    "fields": {
      "title_autocomplete": {}
    }
  },
  "size": 6,
  "query": {
    "multi_match": {
      "query": "Man",
      "fields": [
        "title_autocomplete^2"
      ]
    }
  }
}
</code>```

Body:
I have set up a custom analyser that uses an edge_ngram filter for a text field. I'm then trying to highlight the characters a user types but opensearch is highlighting the entire word, even if only a small number of characters have been typed.

E.g. Typing "Man" in the search bar will result in the word "Manly" being highlighted. Manly Trail Running Tour. What I really want is Manly Trail Running Tour.

This should be possible with the fvh highlighting type and chars as the boundary_scanner argument per the docs https://opensearch.org/docs/2.1/opensearch/search/highlight/#highlighting-options

Settings

"title_autocomplete": {
  "type": "text",
  "term_vector": "with_positions_offsets",
  "analyzer": "autocomplete"
}

"analysis": {
  "filter": {
    "edge_ngram_filter": {
      "type": "edge_ngram",
      "min_gram": "3",
      "max_gram": "20"
    }
  },
  "analyzer": {
    "autocomplete": {
      "filter": [
        "lowercase",
        "edge_ngram_filter"
       ],
       "type": "custom",
       "tokenizer": "standard"
    }
  }
}

Query:

{
  "track_total_hits": true,
  "highlight": {
    "type": "fvh",
    "boundary_scanner": "chars",
    "fields": {
      "title_autocomplete": {}
    }
  },
  "size": 6,
  "query": {
    "multi_match": {
      "query": "Man",
      "fields": [
        "title_autocomplete^2"
      ]
    }
  }
}


问:
Does Power BI app shared with an external guest user show up in their own tenant or my tenant?
I have added an external azure AD user as guest into my AD.

If I publish a Power BI app and assign permission to this external user, then will the app shared with the external guest user show up in their own tenant or my tenant?


问:
What's the difference between this and `webpack` or `vite` for packing javascript code and Electron Forge for building JavaScript?
When I read the document of electron.

Electron Forge

Electron Forge is a batteries-included toolkit for building and publishing Electron apps. Get your Electron app started the right way with first-class support for JavaScript bundling and an extensible module ecosystem.

I have several questions about this sentence:

1.building Electron apps.

so it can build electron code to .msi and .exe installer, right?

2.JavaScript bundling
what's the difference between this and webpack or vite for packing javascript code?

3. what's the meaning of extensible module ecosystem?


问:
Function App not connecting to private Cognitive Search
Having deployed Function App and Cognitive Search components into Azure (via terraform) we are running into issues of the Function App not being able to connect to Cognitive Search (unless it's public).

Configuration of Cognitive Search:

Public network access disabled

Private endpoint added

Is sitting on a subnet within the virtual network

Private DNS Zone added for "privatelink.search.windows.net"

Private DNS Zone is connected to the virtual network

It is accessible from a Container Instance that sits on the same vnet, which makes me believe it's a configuration in the Function App.

Configuration of Function App:

dotnet function app

Subnet created with a delegation for Microsoft.Web/serverFarms

VNet integration is switched on against the function app subnet

Is linked to an Elastic Premium service plan

Service endpoint to Microsoft.Storage has been added to the function app subnet

The Function App is otherwise accessible via a Health endpoint and when the Cognitive Search component is marked as publicly accessible, the search function runs correctly.

If I set the "vnet_route_all_enabled" flag in the terraform or set the "WEBSITE_VNET_ROUTE_ALL" value in the app_settings block of the azurerm_windows_function_app resource to true/"1", then all connections to the Function App return a 500 error (even to the HealthCheck endpoint).

The exception generated by the Azure.Search.Documents.SearchClient class when calling SearchAsync is that the target failed to respond. I'm suspecting that the function app is NOT using the vnet to route the connection and is attempting to use the public one.

Is there anything obvious that I've missed?


问:
N replaced by ! on ios Using itext pdf in java
N replaced by ! on ios using itext pdf in java while sending it on android and desktops it works fine but when sending the pdf on ios n gets replaced.

```<code><dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.6</version>
</dependency>
</code>```

Using this version of itextpdf.

Is it due to the older version..?

Cannot use PdfReader and PdfStammper because I am not editing existing pdf I am creating a new pdf.

Body:
N replaced by ! on ios using itext pdf in java while sending it on android and desktops it works fine but when sending the pdf on ios n gets replaced.

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.6</version>
</dependency>

Using this version of itextpdf.

Is it due to the older version..?

Cannot use PdfReader and PdfStammper because I am not editing existing pdf I am creating a new pdf.


问:
FBLPromises.framework does not contain bitcode - failing build XCODE 14.2

'/Users/apple/Library/Developer/Xcode/DerivedData/Unity-iPhone-fqqzmksymhhvlkeeynbylkkvusgy/Build/Products/ReleaseForRunning-iphoneos/PromisesObjC/FBLPromises.framework/FBLPromises'
does not contain bitcode. You must rebuild it with bitcode enabled
(Xcode setting ENABLE_BITCODE), obtain an updated library from the
vendor, or disable bitcode for this target. file
'/Users/apple/Library/Developer/Xcode/DerivedData/Unity-iPhone-fqqzmksymhhvlkeeynbylkkvusgy/Build/Products/ReleaseForRunning-iphoneos/PromisesObjC/FBLPromises.framework/FBLPromises'
for architecture arm64

Issue when I change the BITCODE It solve ALL THE ISSUES BUT AFTER THAT BUILD CRASHED ON LUNCH.


问:
how can i validate date fields while day mouth and year filed is separate fields
actually I am confused about how to validate every single field of my date

```<code><div class='p-0 m-0'>
  <label class='form-label QstFonts mx-5'>What is your date of birth?</label>
  <div class='mt-5 mb-2 d-flex align-items-center justify-content-center'>
    <input
      asp-for='HLApplication.Day'
      id='txtbox1'
      onkeyup="GnderTextboxsValidation('txtbox1','txtbox2','txtbox3','genderButton')"
      class='input-text col-lg-3 col-2 m-lg-2 m-2 py-4'
      requird
      maxlength='2'
      placeholder='DD'
    />
    <span> / </span>
    <input
      asp-for='HLApplication.Month'
      id='txtbox2'
      onkeyup="GnderTextboxsValidation('txtbox1','txtbox2','txtbox3','genderButton')"
      class='input-text col-lg-3 col-2 m-lg-2 m-2 py-4'
      requird
      maxlength='2'
      placeholder='MM'
    />
    <span> / </span>
    <input
      asp-for='HLApplication.Year'
      id='txtbox3'
      onkeyup="GnderTextboxsValidation('txtbox1','txtbox2','txtbox3','genderButton')"
      class='input-text col-lg-3 col-2 m-lg-2 m-2 py-4'
      requird
      maxlength='4'
      placeholder='YYYY'
    />
  </div>
  <div class='row p-0 m-0'>
    <div class='col-12  p-0 m-0'>
      <div class='p-0 mx-5 row m-auto d-flex'>
        <button
          id='genderButton'
          disabled
          type='button'
          onclick="HairLossClick('37','38'); SubmitForm();"
          class='btn btn-primary my-lg-4 my-1 py-3 h-25 m-auto'
        >
          Continue
        </button>
      </div>
    </div>
  </div>
</div>;
</code>```

the following code is for disable and enable btn on basis of textboxs

```<code>function GnderTextboxsValidation(txtbox1, txtbox2, txtbox3, Button) {
    if (document.getElementById(txtbox1).value === "" ||
        document.getElementById(txtbox2).value === "" ||
        document.getElementById(txtbox3).value === "") {
        document.getElementById(Button).disabled = true;
    } else {
        document.getElementById(Button).disabled = false;
    }
}
</code>```

this is my js party now i'm only checking if field is empty i disable button

Body:
actually I am confused about how to validate every single field of my date

  What is your date of birth?

    <input
      asp-for='HLApplication.Day'
      id='txtbox1'
      onkeyup="GnderTextboxsValidation('txtbox1','txtbox2','txtbox3','genderButton')"
      class='input-text col-lg-3 col-2 m-lg-2 m-2 py-4'
      requird
      maxlength='2'
      placeholder='DD'
    />
     /
    <input
      asp-for='HLApplication.Month'
      id='txtbox2'
      onkeyup="GnderTextboxsValidation('txtbox1','txtbox2','txtbox3','genderButton')"
      class='input-text col-lg-3 col-2 m-lg-2 m-2 py-4'
      requird
      maxlength='2'
      placeholder='MM'
    />
     /
    <input
      asp-for='HLApplication.Year'
      id='txtbox3'
      onkeyup="GnderTextboxsValidation('txtbox1','txtbox2','txtbox3','genderButton')"
      class='input-text col-lg-3 col-2 m-lg-2 m-2 py-4'
      requird
      maxlength='4'
      placeholder='YYYY'
    />

        <button
          id='genderButton'
          disabled
          type='button'
          onclick="HairLossClick('37','38'); SubmitForm();"
          class='btn btn-primary my-lg-4 my-1 py-3 h-25 m-auto'
        >
          Continue
        </button>

;

the following code is for disable and enable btn on basis of textboxs

function GnderTextboxsValidation(txtbox1, txtbox2, txtbox3, Button) {
    if (document.getElementById(txtbox1).value === "" ||
        document.getElementById(txtbox2).value === "" ||
        document.getElementById(txtbox3).value === "") {
        document.getElementById(Button).disabled = true;
    } else {
        document.getElementById(Button).disabled = false;
    }
}

this is my js party now i'm only checking if field is empty i disable button


问:
custom JAVA SDK file in android studio project
Client provide me a SDK file to build a RFID Reader Apps for Handheld Device.
How to use or open custom JAVA SDK file in my Android Studio IDE.

I tried to open that file in my Android Studio IDE but I failed because There was no gradle file.
Please give me suggestion ,how I open SDK.


问:
how to solve the sparkSession class not found in intellij project
While submitting scala spark project I am getting this error

```<code>Caused by: java.lang.ClassNotFoundException: org.apache.spark.sql.SparkSession$
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
</code>```

After many repeated attempts I am not able to solve this problem. Can anybody help me to submit my project

I have tried revalidating the cache and submitted the project still not solved

Body:
While submitting scala spark project I am getting this error

Caused by: java.lang.ClassNotFoundException: org.apache.spark.sql.SparkSession$
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)

After many repeated attempts I am not able to solve this problem. Can anybody help me to submit my project

I have tried revalidating the cache and submitted the project still not solved


问:
Why do I receive deprecated package warnings when using npm install
I hope you are doing well!

I got asked about why should I use -f to force npm install packages to install. In the documentation it states that

force npm to fetch remote resources even if a local copy exists on disk.
But does this mean that it redownloads global packages for the local project or what does it solve exactly?

Another thing happens is when I use npm install, I see a lot of warnings in the console that

WARNING: X package is deprecated
But when I run npm outdated I see that all packages are all fairly up to date (all match the recommended version to download), so I assume this might be a dependency for a certain package. But does it affect our work negatively? Why does this happen?

For the packages I download, I generally look for packages that have in the 6 digits Weekly Downloads from npm so I don't think we are using unfamiliar packages.

I am asking these questions because they have been asked to me but I don't have a straight answer to them.

Thank You!

I don't understand how npm install -f works


问:
Argument Z must be 2D error while running python code for plotting the data

# Import libraries
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

# Creating dataset
x = np.loadtxt('pfl.dat',unpack=True, usecols=[0])
y = np.loadtxt('pfl.dat',unpack=True, usecols=[1])
z = np.loadtxt('pfl.dat',unpack=True, usecols=[2])

# Creating figure
fig = plt.figure(figsize =(14, 9))
ax = plt.axes(projection ='3d')

# Creating color map
my_cmap = plt.get_cmap('hot')

# Creating plot
surf = ax.plot_surface(x, y, z,
                                        rstride = 8,
                                        cstride = 8,
                                        alpha = 0.8,
                                        cmap = my_cmap)
cset = ax.contourf(x, y, z,
                                zdir ='z',
                                offset = np.min(z),
                                cmap = my_cmap)
cset = ax.contourf(x, y, z,
                                zdir ='x',
                                offset =-5,
                                cmap = my_cmap)
cset = ax.contourf(x, y, z,
                                zdir ='y',
                                offset = 5,
                                cmap = my_cmap)
fig.colorbar(surf, ax = ax,
                        shrink = 0.5,
                        aspect = 5)

# Adding labels
ax.set_xlabel('X-axis')
ax.set_xlim(-5, 5)
ax.set_ylabel('Y-axis')
ax.set_ylim(-5, 5)
ax.set_zlabel('Z-axis')
ax.set_zlim(np.min(z), np.max(z))
ax.set_title('3D surface having 2D contour plot projections')

# show plot
plt.show()
```

I tried to plot the imported data; but each time I get the same error:

raise ValueError("Argument Z must be 2-dimensional.") ValueError: Argument Z must be 2-dimensional

I searched for similar problems on SO; but did not get any solution.

Body:
# Import libraries
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

# Creating dataset
x = np.loadtxt('pfl.dat',unpack=True, usecols=[0])
y = np.loadtxt('pfl.dat',unpack=True, usecols=[1])
z = np.loadtxt('pfl.dat',unpack=True, usecols=[2])

# Creating figure
fig = plt.figure(figsize =(14, 9))
ax = plt.axes(projection ='3d')

# Creating color map
my_cmap = plt.get_cmap('hot')

# Creating plot
surf = ax.plot_surface(x, y, z,
                                        rstride = 8,
                                        cstride = 8,
                                        alpha = 0.8,
                                        cmap = my_cmap)
cset = ax.contourf(x, y, z,
                                zdir ='z',
                                offset = np.min(z),
                                cmap = my_cmap)
cset = ax.contourf(x, y, z,
                                zdir ='x',
                                offset =-5,
                                cmap = my_cmap)
cset = ax.contourf(x, y, z,
                                zdir ='y',
                                offset = 5,
                                cmap = my_cmap)
fig.colorbar(surf, ax = ax,
                        shrink = 0.5,
                        aspect = 5)

# Adding labels
ax.set_xlabel('X-axis')
ax.set_xlim(-5, 5)
ax.set_ylabel('Y-axis')
ax.set_ylim(-5, 5)
ax.set_zlabel('Z-axis')
ax.set_zlim(np.min(z), np.max(z))
ax.set_title('3D surface having 2D contour plot projections')

# show plot
plt.show()

I tried to plot the imported data; but each time I get the same error:

raise ValueError("Argument Z must be 2-dimensional.") ValueError: Argument Z must be 2-dimensional

I searched for similar problems on SO; but did not get any solution.


问:
GCP Cloud Storage Transfer Service - Agents unable to connect to pool
I wanted to make use of GCP Cloud Transfer Service to sync data from on-premise. For this I had to install agents and connect them to a pool. I was following the steps here, where they provide docker commands to install a transfer agent. Instead of docker, I used podman:

```<code>podman run -ti --name gcloud-config docker.io/google/cloud-sdk gcloud auth application-default login

podman run -d --rm \
--env https_proxy=<some_proxy> \
--volumes-from gcloud-config \
-v <some_dir>:<some_dir> \
gcr.io/cloud-ingest/tsop-agent:latest \
--project-id=<some_project_id> \
--hostname=$(hostname) \
--agent-pool=source_agent_pool
</code>```

The agents do start but they aren't able to connect to the pool.
If I see the output of the agent container (using podman attach containerID)

```<code>0B/s txSum:      0B taskResps[copy:0 delete:0 list:0] ctrlMsgAge:10m50s (??) |
</code>```

and agent.INFO logs:

```<code>Build target: //cloud/transfer/online/onprem/workers/agent:agent
Build id: <some_id>
I1222 06:47:51.288924       3 log_spam.go:51] Command line arguments:
I1222 06:47:51.288926       3 log_spam.go:53]  argv[0]: './agent'
I1222 06:47:51.288928       3 log_spam.go:53]  argv[1]: '--project-id=<project_id>'
I1222 06:47:51.288930       3 log_spam.go:53]  argv[2]: '--hostname=<hostname>'
I1222 06:47:51.288931       3 log_spam.go:53]  argv[3]: '--agent-pool=source_agent_pool'
I1222 06:47:51.288933       3 log_spam.go:53]  argv[4]: '--container-id=49be0b94bced'
I1222 06:47:51.289408       3 prodlayer.go:217] layer successfully set to NO_LAYER with source DEFAULT
I1222 06:47:53.148699       3 handler.go:45] TaskletHandler initialized to delete at most 1000 objects in parallel:
I1222 06:47:53.148725       3 handler.go:48] TaskletHandler initialized with delete-files: 1024
I1222 06:47:53.148827       3 copy.go:145] TaskletHandler initialized with copy-files: &{0xc00073d2c0 10800000000000}
I1222 06:47:53.148860       3 handler.go:61] TaskletHandler initialized to process at most 256 list outputs in parallel:
I1222 06:48:51.291680       3 cpuutilization.go:86] Last minute's CPU utilization: 0
I1222 06:49:51.291017       3 cpuutilization.go:86] Last minute's CPU utilization: 0
I1222 06:50:51.290721       3 cpuutilization.go:86] Last minute's CPU utilization: 0
I1222 06:51:51.291057       3 cpuutilization.go:86] Last minute's CPU utilization: 0
I1222 06:52:51.290677       3 cpuutilization.go:86] Last minute's CPU utilization: 0
I1222 06:53:51.290445       3 cpuutilization.go:86] Last minute's CPU utilization: 0
</code>```

I also checked all the troubleshooting steps here, but couldn't find anything. Is it something to do with using podman instead of docker?

Body:
I wanted to make use of GCP Cloud Transfer Service to sync data from on-premise. For this I had to install agents and connect them to a pool. I was following the steps here, where they provide docker commands to install a transfer agent. Instead of docker, I used podman:

podman run -ti --name gcloud-config docker.io/google/cloud-sdk gcloud auth application-default login

podman run -d --rm \
--env https_proxy=<some_proxy> \
--volumes-from gcloud-config \
-v <some_dir>:<some_dir> \
gcr.io/cloud-ingest/tsop-agent:latest \
--project-id=<some_project_id> \
--hostname=$(hostname) \
--agent-pool=source_agent_pool

The agents do start but they aren't able to connect to the pool.
If I see the output of the agent container (using podman attach containerID)

0B/s txSum:      0B taskResps[copy:0 delete:0 list:0] ctrlMsgAge:10m50s (??) |

and agent.INFO logs:

Build target: //cloud/transfer/online/onprem/workers/agent:agent
Build id: <some_id>
I1222 06:47:51.288924       3 log_spam.go:51] Command line arguments:
I1222 06:47:51.288926       3 log_spam.go:53]  argv[0]: './agent'
I1222 06:47:51.288928       3 log_spam.go:53]  argv[1]: '--project-id=<project_id>'
I1222 06:47:51.288930       3 log_spam.go:53]  argv[2]: '--hostname=<hostname>'
I1222 06:47:51.288931       3 log_spam.go:53]  argv[3]: '--agent-pool=source_agent_pool'
I1222 06:47:51.288933       3 log_spam.go:53]  argv[4]: '--container-id=49be0b94bced'
I1222 06:47:51.289408       3 prodlayer.go:217] layer successfully set to NO_LAYER with source DEFAULT
I1222 06:47:53.148699       3 handler.go:45] TaskletHandler initialized to delete at most 1000 objects in parallel:
I1222 06:47:53.148725       3 handler.go:48] TaskletHandler initialized with delete-files: 1024
I1222 06:47:53.148827       3 copy.go:145] TaskletHandler initialized with copy-files: &{0xc00073d2c0 10800000000000}
I1222 06:47:53.148860       3 handler.go:61] TaskletHandler initialized to process at most 256 list outputs in parallel:
I1222 06:48:51.291680       3 cpuutilization.go:86] Last minute's CPU utilization: 0
I1222 06:49:51.291017       3 cpuutilization.go:86] Last minute's CPU utilization: 0
I1222 06:50:51.290721       3 cpuutilization.go:86] Last minute's CPU utilization: 0
I1222 06:51:51.291057       3 cpuutilization.go:86] Last minute's CPU utilization: 0
I1222 06:52:51.290677       3 cpuutilization.go:86] Last minute's CPU utilization: 0
I1222 06:53:51.290445       3 cpuutilization.go:86] Last minute's CPU utilization: 0

I also checked all the troubleshooting steps here, but couldn't find anything. Is it something to do with using podman instead of docker?


问:
how to update Vulnerable Library (libjpeg-turbo 1.5.3) in saleforce org Or application
update Vulnerable Library libjpeg-turbo 1.5.3 to latest version

we have salesforce web application with salesforce org so found vulnerability issue in black duck scan tool so we need to update this library with updated version.


问:
Is it possible to add randomly generated Id/String for a program argument (Java) in IntelliJ configuration
I was running a code in Java which needs input from program arguments. In IntelliJ IDEA, is it possible to provide a random dynamic id every time I run the code?</p>