问:
InvalidKeyException : Illegal Key Size - Java code throwing exception for encryption class - how to fix?
I've been trying to get some working Java code to use for encrypting Paypal buttons. This is no easy task! Even when I get some code, from Paypal, I'm faced with errors..ugh..

So here is what I have so far, that I think will work eventually.

I downloaded the Java.zip file from Paypal's website. Within it are two classes - ClientSide.java and ButtonEncryption.java

The Problem - I'm getting an InvalidKeyException : Illegal key size error.

Questions

1) How do I resolve this issue? 2) What line of code is throwing the error?

```<code>C:\jakarta-tomcat\webapps\PlanB\WEB-INF\classes>java palmb.servlets.paypal.ButtonEncryption
java.io.IOException: exception decrypting data - java.security.InvalidKeyException: Illegal key size
        at org.bouncycastle.jce.provider.JDKPKCS12KeyStore.cryptData(Unknown Source)
        at org.bouncycastle.jce.provider.JDKPKCS12KeyStore.engineLoad(Unknown Source)
        at java.security.KeyStore.load(Unknown Source)
        at palmb.servlets.paypal.ClientSide.getButtonEncryptionValue(ClientSide.java:63)
        at palmb.servlets.paypal.ButtonEncryption.main(ButtonEncryption.java:81)
</code>```

ClientSide class

```<code>package palmb.servlets.paypal;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertStore;
import java.security.cert.CertStoreException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.CollectionCertStoreParameters;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Enumeration;

import org.bouncycastle.cms.CMSEnvelopedData;
import org.bouncycastle.cms.CMSEnvelopedDataGenerator;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.openssl.PEMReader;
import org.bouncycastle.util.encoders.Base64;

/**
 */
public class ClientSide
{
    private String  keyPath;
    private String  certPath;
    private String  paypalCertPath;
    private String  keyPass;

    public ClientSide( String keyPath, String certPath, String paypalCertPath, String keyPass )
    {
        this.keyPath = keyPath;
        this.certPath = certPath;
        this.paypalCertPath = paypalCertPath;
        this.keyPass = keyPass;
    }

    public String getButtonEncryptionValue(String _data, String _privateKeyPath, String _certPath, String _payPalCertPath,
                                            String _keyPass) throws IOException,CertificateException,KeyStoreException,
                                            UnrecoverableKeyException,InvalidAlgorithmParameterException,NoSuchAlgorithmException,
                                            NoSuchProviderException,CertStoreException,CMSException {
        _data = _data.replace(',', '\n');
        CertificateFactory cf = CertificateFactory.getInstance("X509", "BC");

        // Read the Private Key
        KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
        ks.load( new FileInputStream(_privateKeyPath), _keyPass.toCharArray() );

        String keyAlias = null;
        Enumeration aliases = ks.aliases();
        while (aliases.hasMoreElements()) {
            keyAlias = (String) aliases.nextElement();
        }

        PrivateKey privateKey = (PrivateKey) ks.getKey( keyAlias, _keyPass.toCharArray() );

        // Read the Certificate
        X509Certificate certificate = (X509Certificate) cf.generateCertificate( new FileInputStream(_certPath) );

        // Read the PayPal Cert
        X509Certificate payPalCert = (X509Certificate) cf.generateCertificate( new FileInputStream(_payPalCertPath) );

        // Create the Data
        byte[] data = _data.getBytes();

        // Sign the Data with my signing only key pair
        CMSSignedDataGenerator signedGenerator = new CMSSignedDataGenerator();

        signedGenerator.addSigner( privateKey, certificate, CMSSignedDataGenerator.DIGEST_SHA1 );

        ArrayList certList = new ArrayList();
        certList.add(certificate);
        CertStore certStore = CertStore.getInstance( "Collection", new CollectionCertStoreParameters(certList) );
        signedGenerator.addCertificatesAndCRLs(certStore);

        CMSProcessableByteArray cmsByteArray = new CMSProcessableByteArray(data);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        cmsByteArray.write(baos);
        System.out.println( "CMSProcessableByteArray contains [" + baos.toString() + "]" );

        CMSSignedData signedData = signedGenerator.generate(cmsByteArray, true, "BC");

        byte[] signed = signedData.getEncoded();

        CMSEnvelopedDataGenerator envGenerator = new CMSEnvelopedDataGenerator();
        envGenerator.addKeyTransRecipient(payPalCert);
        CMSEnvelopedData envData = envGenerator.generate( new CMSProcessableByteArray(signed),
                CMSEnvelopedDataGenerator.DES_EDE3_CBC, "BC" );

        byte[] pkcs7Bytes = envData.getEncoded();

        return new String( DERtoPEM(pkcs7Bytes, "PKCS7") );

    }

    public static byte[] DERtoPEM(byte[] bytes, String headfoot)
    {
        ByteArrayOutputStream pemStream = new ByteArrayOutputStream();
        PrintWriter writer = new PrintWriter(pemStream);

        byte[] stringBytes = Base64.encode(bytes);

        System.out.println("Converting " + stringBytes.length + " bytes");

        String encoded = new String(stringBytes);

        if (headfoot != null) {
            writer.print("-----BEGIN " + headfoot + "-----\n");
        }

        // write 64 chars per line till done
        int i = 0;
        while ((i + 1) * 64 < encoded.length()) {
            writer.print(encoded.substring(i * 64, (i + 1) * 64));
            writer.print("\n");
            i++;
        }
        if (encoded.length() % 64 != 0) {
            writer.print(encoded.substring(i * 64)); // write remainder
            writer.print("\n");
        }
        if (headfoot != null) {
            writer.print("-----END " + headfoot + "-----\n");
        }
        writer.flush();
        return pemStream.toByteArray();
    }

}
</code>```

ButtonEncryption class

```<code>package palmb.servlets.paypal;

//import com.paypal.crypto.sample.*;

import palmb.servlets.paypal.ClientSide;

import java.io.*;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertStoreException;
import java.security.cert.CertificateException;
import org.bouncycastle.cms.CMSException;

/**
 */
public class ButtonEncryption {

    //path to public cert
    private static String certPath = "C:/jakarta-tomcat/webapps/PlanB/Certs/public-cert.pem";

    //path to private key in PKCS12 format
    private static String keyPath = "C:/jakarta-tomcat/webapps/PlanB/Certs/my_pkcs12.p12";

    //path to Paypal's public cert
    private static String paypalCertPath = "C:/jakarta-tomcat/webapps/PlanB/Certs/paypal_cert_pem.txt";

    //private key password
    private static String keyPass = "password"; //will be replaced with actual password when compiled and executed

    //the button command, properties/parameters
    private static String cmdText = "cmd=_xclick\nbusiness=buyer@hotmail.com\nitem_name=vase\nitemprice=25.00";  //cmd=_xclick,business=sample@paypal.com,amount=1.00,currency_code=USD

    //output file for form code
    private static String output = "test.html";

    public static void main(String[] args)
    {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        String stage = "sandbox";

        try
        {
            ClientSide client_side = new ClientSide( keyPath, certPath, paypalCertPath, keyPass );

            String result = client_side.getButtonEncryptionValue( cmdText, keyPath, certPath, paypalCertPath, keyPass );

            File outputFile = new File( output );
            if ( outputFile.exists() )
                outputFile.delete();

            if ( result != null && result != "")
            {
                try {
                    OutputStream fout= new FileOutputStream( output );
                    OutputStream bout= new BufferedOutputStream(fout);
                    OutputStreamWriter out = new OutputStreamWriter(bout, "US-ASCII");

                    out.write( "<form action=\"https://www." );
                    out.write( stage );
                    out.write( "paypal.com/cgi-bin/webscr\" method=\"post\">" );
                    out.write( "<input type=\"hidden\" name=\"cmd\" value=\"_s-xclick\">" );  ;
                    out.write( "<input type=\"image\" src=\"https://www." );
                    out.write( stage );
                    out.write( "paypal.com/en_US/i/btn/x-click-but23.gif\" border=\"0\" name=\"submit\" " );
                    out.write( "alt=\"Make payments with PayPal - it's fast, free and secure!\">" );
                    out.write( "<input type=\"hidden\" name=\"encrypted\" value=\"" );
                    out.write( result );
                    out.write( "\">" );
                    out.write( "</form>");

                    out.flush();  // Don't forget to flush!
                    out.close();
                  }
                  catch (UnsupportedEncodingException e) {
                    System.out.println(
                     "This VM does not support the ASCII character set."
                    );
                  }
                  catch (IOException e) {
                    System.out.println(e.getMessage());
                  }
            }
        }
        catch (NoSuchAlgorithmException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (NoSuchProviderException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (CMSException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (CertificateException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (KeyStoreException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (UnrecoverableKeyException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (InvalidAlgorithmParameterException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (CertStoreException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
</code>```

Edited : info about keys/certificates

I generated the Private Key and Public Certificate with OpenSSL via the following commands.

Private Key

openssl genrsa -out private-key.pem 1024

Public Certificate

openssl req -new -key private-key.pem -x509 -days 1095 -out public-cert.pem

Created PKCS12 File

openssl pkcs12 -export -in public-cert.pem -inkey private-key.pem -out my_pkcs12.p12

Additionally, I had to download the Paypal Public Certificate from the Paypal website.

Edited - adding compilation warnings - BouncyCastle

```<code>C:\jakarta-tomcat\webapps\PlanB\WEB-INF\classes>javac .\palmb\servlets\paypal\ClientSide.java -Xlint
.\palmb\servlets\paypal\ClientSide.java:85: warning: [deprecation] addSigner(java.security.PrivateKey,java.security.cert.X509Certificate,java.lang.String) in org.bouncycastle.cms.CMSSignedDataGenerator has been deprecated
                signedGenerator.addSigner( privateKey, certificate, CMSSignedDat
aGenerator.DIGEST_SHA1 );
                               ^
.\palmb\servlets\paypal\ClientSide.java:88: warning: [unchecked] unchecked call
to add(E) as a member of the raw type java.util.ArrayList
                certList.add(certificate);
                            ^
.\palmb\servlets\paypal\ClientSide.java:90: warning: [deprecation] addCertificatesAndCRLs(java.security.cert.CertStore) in org.bouncycastle.cms.CMSSignedGenerat
or has been deprecated
                signedGenerator.addCertificatesAndCRLs(certStore);
                               ^
.\palmb\servlets\paypal\ClientSide.java:97: warning: [deprecation] generate(org.
bouncycastle.cms.CMSProcessable,boolean,java.lang.String) in org.bouncycastle.cm
s.CMSSignedDataGenerator has been deprecated
                CMSSignedData signedData = signedGenerator.generate(cmsByteArray, true, "BC");
                                                          ^
.\palmb\servlets\paypal\ClientSide.java:102: warning: [deprecation] addKeyTransR
ecipient(java.security.cert.X509Certificate) in org.bouncycastle.cms.CMSEnvelope
dGenerator has been deprecated
                envGenerator.addKeyTransRecipient(payPalCert);
                            ^
.\palmb\servlets\paypal\ClientSide.java:103: warning: [deprecation] generate(org.bouncycastle.cms.CMSProcessable,java.lang.String,java.lang.String) in org.bouncycastle.cms.CMSEnvelopedDataGenerator has been deprecated
                CMSEnvelopedData envData = envGenerator.generate( new CMSProcess
ableByteArray(signed),
                                                       ^
6 warnings
</code>```

JCE policy file installation steps

These are the steps I took to installing the JCE Unlimited Strength Policy files:

1) Went to Java JCE Download Page on Oracle.

2) Extracted files from zip.

3) Placed local_policy.jar and US_export_policy.jar files in C:\Java\jdk1.6.0_22\jre\lib\security folder.

Note: C:\Java\jdk1.6.0_22 is set as %JAVA_HOME%

4) Updated system classpath to include location of jars.

Note: There are other files, that came with the JDK 1.6 within the security folder, including : java.policy, java.security, javaws.policy, trusted.libraries - but those probably have nothing to do with the JCE files, right?

Edit 6/23/2011 - results after further configuration

I went to Bouncy Castle page at http://www.bouncycastle.org/specifications.html#install

Scroll down to 5.0 Bouncy Castle Provider then read info under 5.1 Example. It makes mention of adding a parameter for the Bouncy Castle Provider to the java.security file. My file is under C:\Java\jdk1.6.0_22\jre\lib\security.

I added the following line to my file - security.provider.10=org.bouncycastle.jce.provider.BouncyCastleProvider

In addition, I discovered that I hadn't added the Bouncy Castle jars to the classpath, so I went ahead and did so.

Now after making these changes, recompiling and attempting to execute ClientSide.java I'm given the same exception : but maybe the focus should be on the part of the exception where it says this about bouncycastle provider -

```<code>at org.bouncycastle.jce.provider.JDKPKCS12KeyStore.cryptData(Unknown Source)
at org.bouncycastle.jce.provider.JDKPKCS12KeyStore.engineLoad(Unknown Source)
</code>```

@PeteyB - I'm certain that I installed the policy files correctly. Based on what I've stated here, is there anything else you can suggest I try? Can you look at the Bouncy Castle site @ http://www.bouncycastle.org/specifications.html#install and see if there is something I'm missing?

答:
I faced the same issue. Tried adding the US_export_policy.jar and local_policy.jar in the java security folder first but the issue persisted. Then added the below in java_opts inside tomcat setenv.shfile and it worked.

```<code>-Djdk.tls.ephemeralDHKeySize=2048
</code>```

Please check this link for further info

Body:
I've been trying to get some working Java code to use for encrypting Paypal buttons. This is no easy task! Even when I get some code, from Paypal, I'm faced with errors..ugh..

So here is what I have so far, that I think will work eventually.

I downloaded the Java.zip file from Paypal's website. Within it are two classes - ClientSide.java and ButtonEncryption.java

The Problem - I'm getting an InvalidKeyException : Illegal key size error.

Questions

1) How do I resolve this issue? 2) What line of code is throwing the error?

C:\jakarta-tomcat\webapps\PlanB\WEB-INF\classes>java palmb.servlets.paypal.ButtonEncryption
java.io.IOException: exception decrypting data - java.security.InvalidKeyException: Illegal key size
        at org.bouncycastle.jce.provider.JDKPKCS12KeyStore.cryptData(Unknown Source)
        at org.bouncycastle.jce.provider.JDKPKCS12KeyStore.engineLoad(Unknown Source)
        at java.security.KeyStore.load(Unknown Source)
        at palmb.servlets.paypal.ClientSide.getButtonEncryptionValue(ClientSide.java:63)
        at palmb.servlets.paypal.ButtonEncryption.main(ButtonEncryption.java:81)

ClientSide class

package palmb.servlets.paypal;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertStore;
import java.security.cert.CertStoreException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.CollectionCertStoreParameters;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Enumeration;

import org.bouncycastle.cms.CMSEnvelopedData;
import org.bouncycastle.cms.CMSEnvelopedDataGenerator;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.openssl.PEMReader;
import org.bouncycastle.util.encoders.Base64;

/**
 */
public class ClientSide
{
    private String  keyPath;
    private String  certPath;
    private String  paypalCertPath;
    private String  keyPass;

    public ClientSide( String keyPath, String certPath, String paypalCertPath, String keyPass )
    {
        this.keyPath = keyPath;
        this.certPath = certPath;
        this.paypalCertPath = paypalCertPath;
        this.keyPass = keyPass;
    }

    public String getButtonEncryptionValue(String _data, String _privateKeyPath, String _certPath, String _payPalCertPath,
                                            String _keyPass) throws IOException,CertificateException,KeyStoreException,
                                            UnrecoverableKeyException,InvalidAlgorithmParameterException,NoSuchAlgorithmException,
                                            NoSuchProviderException,CertStoreException,CMSException {
        _data = _data.replace(',', '\n');
        CertificateFactory cf = CertificateFactory.getInstance("X509", "BC");

        // Read the Private Key
        KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
        ks.load( new FileInputStream(_privateKeyPath), _keyPass.toCharArray() );

        String keyAlias = null;
        Enumeration aliases = ks.aliases();
        while (aliases.hasMoreElements()) {
            keyAlias = (String) aliases.nextElement();
        }

        PrivateKey privateKey = (PrivateKey) ks.getKey( keyAlias, _keyPass.toCharArray() );

        // Read the Certificate
        X509Certificate certificate = (X509Certificate) cf.generateCertificate( new FileInputStream(_certPath) );

        // Read the PayPal Cert
        X509Certificate payPalCert = (X509Certificate) cf.generateCertificate( new FileInputStream(_payPalCertPath) );

        // Create the Data
        byte[] data = _data.getBytes();

        // Sign the Data with my signing only key pair
        CMSSignedDataGenerator signedGenerator = new CMSSignedDataGenerator();

        signedGenerator.addSigner( privateKey, certificate, CMSSignedDataGenerator.DIGEST_SHA1 );

        ArrayList certList = new ArrayList();
        certList.add(certificate);
        CertStore certStore = CertStore.getInstance( "Collection", new CollectionCertStoreParameters(certList) );
        signedGenerator.addCertificatesAndCRLs(certStore);

        CMSProcessableByteArray cmsByteArray = new CMSProcessableByteArray(data);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        cmsByteArray.write(baos);
        System.out.println( "CMSProcessableByteArray contains [" + baos.toString() + "]" );

        CMSSignedData signedData = signedGenerator.generate(cmsByteArray, true, "BC");

        byte[] signed = signedData.getEncoded();

        CMSEnvelopedDataGenerator envGenerator = new CMSEnvelopedDataGenerator();
        envGenerator.addKeyTransRecipient(payPalCert);
        CMSEnvelopedData envData = envGenerator.generate( new CMSProcessableByteArray(signed),
                CMSEnvelopedDataGenerator.DES_EDE3_CBC, "BC" );

        byte[] pkcs7Bytes = envData.getEncoded();

        return new String( DERtoPEM(pkcs7Bytes, "PKCS7") );

    }

    public static byte[] DERtoPEM(byte[] bytes, String headfoot)
    {
        ByteArrayOutputStream pemStream = new ByteArrayOutputStream();
        PrintWriter writer = new PrintWriter(pemStream);

        byte[] stringBytes = Base64.encode(bytes);

        System.out.println("Converting " + stringBytes.length + " bytes");

        String encoded = new String(stringBytes);

        if (headfoot != null) {
            writer.print("-----BEGIN " + headfoot + "-----\n");
        }

        // write 64 chars per line till done
        int i = 0;
        while ((i + 1) * 64 < encoded.length()) {
            writer.print(encoded.substring(i * 64, (i + 1) * 64));
            writer.print("\n");
            i++;
        }
        if (encoded.length() % 64 != 0) {
            writer.print(encoded.substring(i * 64)); // write remainder
            writer.print("\n");
        }
        if (headfoot != null) {
            writer.print("-----END " + headfoot + "-----\n");
        }
        writer.flush();
        return pemStream.toByteArray();
    }

}

ButtonEncryption class

package palmb.servlets.paypal;

//import com.paypal.crypto.sample.*;

import palmb.servlets.paypal.ClientSide;

import java.io.*;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertStoreException;
import java.security.cert.CertificateException;
import org.bouncycastle.cms.CMSException;

/**
 */
public class ButtonEncryption {

    //path to public cert
    private static String certPath = "C:/jakarta-tomcat/webapps/PlanB/Certs/public-cert.pem";

    //path to private key in PKCS12 format
    private static String keyPath = "C:/jakarta-tomcat/webapps/PlanB/Certs/my_pkcs12.p12";

    //path to Paypal's public cert
    private static String paypalCertPath = "C:/jakarta-tomcat/webapps/PlanB/Certs/paypal_cert_pem.txt";

    //private key password
    private static String keyPass = "password"; //will be replaced with actual password when compiled and executed

    //the button command, properties/parameters
    private static String cmdText = "cmd=_xclick\nbusiness=buyer@hotmail.com\nitem_name=vase\nitemprice=25.00";  //cmd=_xclick,business=sample@paypal.com,amount=1.00,currency_code=USD

    //output file for form code
    private static String output = "test.html";

    public static void main(String[] args)
    {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        String stage = "sandbox";

        try
        {
            ClientSide client_side = new ClientSide( keyPath, certPath, paypalCertPath, keyPass );

            String result = client_side.getButtonEncryptionValue( cmdText, keyPath, certPath, paypalCertPath, keyPass );

            File outputFile = new File( output );
            if ( outputFile.exists() )
                outputFile.delete();

            if ( result != null && result != "")
            {
                try {
                    OutputStream fout= new FileOutputStream( output );
                    OutputStream bout= new BufferedOutputStream(fout);
                    OutputStreamWriter out = new OutputStreamWriter(bout, "US-ASCII");

                    out.write( "<form action=\"https://www." );
                    out.write( stage );
                    out.write( "paypal.com/cgi-bin/webscr\" method=\"post\">" );
                    out.write( "<input type=\"hidden\" name=\"cmd\" value=\"_s-xclick\">" );  ;
                    out.write( "<input type=\"image\" src=\"https://www." );
                    out.write( stage );
                    out.write( "paypal.com/en_US/i/btn/x-click-but23.gif\" border=\"0\" name=\"submit\" " );
                    out.write( "alt=\"Make payments with PayPal - it's fast, free and secure!\">" );
                    out.write( "<input type=\"hidden\" name=\"encrypted\" value=\"" );
                    out.write( result );
                    out.write( "\">" );
                    out.write( "</form>");

                    out.flush();  // Don't forget to flush!
                    out.close();
                  }
                  catch (UnsupportedEncodingException e) {
                    System.out.println(
                     "This VM does not support the ASCII character set."
                    );
                  }
                  catch (IOException e) {
                    System.out.println(e.getMessage());
                  }
            }
        }
        catch (NoSuchAlgorithmException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (NoSuchProviderException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (CMSException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (CertificateException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (KeyStoreException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (UnrecoverableKeyException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (InvalidAlgorithmParameterException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (CertStoreException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Edited : info about keys/certificates

I generated the Private Key and Public Certificate with OpenSSL via the following commands.

Private Key

openssl genrsa -out private-key.pem 1024

Public Certificate

openssl req -new -key private-key.pem -x509 -days 1095 -out public-cert.pem

Created PKCS12 File

openssl pkcs12 -export -in public-cert.pem -inkey private-key.pem -out my_pkcs12.p12

Additionally, I had to download the Paypal Public Certificate from the Paypal website.

Edited - adding compilation warnings - BouncyCastle

C:\jakarta-tomcat\webapps\PlanB\WEB-INF\classes>javac .\palmb\servlets\paypal\ClientSide.java -Xlint
.\palmb\servlets\paypal\ClientSide.java:85: warning: [deprecation] addSigner(java.security.PrivateKey,java.security.cert.X509Certificate,java.lang.String) in org.bouncycastle.cms.CMSSignedDataGenerator has been deprecated
                signedGenerator.addSigner( privateKey, certificate, CMSSignedDat
aGenerator.DIGEST_SHA1 );
                               ^
.\palmb\servlets\paypal\ClientSide.java:88: warning: [unchecked] unchecked call
to add(E) as a member of the raw type java.util.ArrayList
                certList.add(certificate);
                            ^
.\palmb\servlets\paypal\ClientSide.java:90: warning: [deprecation] addCertificatesAndCRLs(java.security.cert.CertStore) in org.bouncycastle.cms.CMSSignedGenerat
or has been deprecated
                signedGenerator.addCertificatesAndCRLs(certStore);
                               ^
.\palmb\servlets\paypal\ClientSide.java:97: warning: [deprecation] generate(org.
bouncycastle.cms.CMSProcessable,boolean,java.lang.String) in org.bouncycastle.cm
s.CMSSignedDataGenerator has been deprecated
                CMSSignedData signedData = signedGenerator.generate(cmsByteArray, true, "BC");
                                                          ^
.\palmb\servlets\paypal\ClientSide.java:102: warning: [deprecation] addKeyTransR
ecipient(java.security.cert.X509Certificate) in org.bouncycastle.cms.CMSEnvelope
dGenerator has been deprecated
                envGenerator.addKeyTransRecipient(payPalCert);
                            ^
.\palmb\servlets\paypal\ClientSide.java:103: warning: [deprecation] generate(org.bouncycastle.cms.CMSProcessable,java.lang.String,java.lang.String) in org.bouncycastle.cms.CMSEnvelopedDataGenerator has been deprecated
                CMSEnvelopedData envData = envGenerator.generate( new CMSProcess
ableByteArray(signed),
                                                       ^
6 warnings

JCE policy file installation steps

These are the steps I took to installing the JCE Unlimited Strength Policy files:

1) Went to Java JCE Download Page on Oracle.

2) Extracted files from zip.

3) Placed local_policy.jar and US_export_policy.jar files in C:\Java\jdk1.6.0_22\jre\lib\security folder.

Note: C:\Java\jdk1.6.0_22 is set as %JAVA_HOME%

4) Updated system classpath to include location of jars.

Note: There are other files, that came with the JDK 1.6 within the security folder, including : java.policy, java.security, javaws.policy, trusted.libraries - but those probably have nothing to do with the JCE files, right?

Edit 6/23/2011 - results after further configuration

I went to Bouncy Castle page at http://www.bouncycastle.org/specifications.html#install

Scroll down to 5.0 Bouncy Castle Provider then read info under 5.1 Example. It makes mention of adding a parameter for the Bouncy Castle Provider to the java.security file. My file is under C:\Java\jdk1.6.0_22\jre\lib\security.

I added the following line to my file - security.provider.10=org.bouncycastle.jce.provider.BouncyCastleProvider

In addition, I discovered that I hadn't added the Bouncy Castle jars to the classpath, so I went ahead and did so.

Now after making these changes, recompiling and attempting to execute ClientSide.java I'm given the same exception : but maybe the focus should be on the part of the exception where it says this about bouncycastle provider -

at org.bouncycastle.jce.provider.JDKPKCS12KeyStore.cryptData(Unknown Source)
at org.bouncycastle.jce.provider.JDKPKCS12KeyStore.engineLoad(Unknown Source)

@PeteyB - I'm certain that I installed the policy files correctly. Based on what I've stated here, is there anything else you can suggest I try? Can you look at the Bouncy Castle site @ http://www.bouncycastle.org/specifications.html#install and see if there is something I'm missing?

Body:
I faced the same issue. Tried adding the US_export_policy.jar and local_policy.jar in the java security folder first but the issue persisted. Then added the below in java_opts inside tomcat setenv.shfile and it worked.

-Djdk.tls.ephemeralDHKeySize=2048

Please check this link for further info


来源: stackexchange

问:
Pass click event to nested component - React | Material-UI
Im having an issue. When you click listItem (whole separated li element) I want to call the onChange function on the checkbox component inside listItem.

I could easily move that function from checkbox to parent but I will loose the checked prop.

Checking the checkbox itself doesnt work, but just open the console to see the results. I want handleToggle function to fire properly when whole element is clicked (not only checkbox)

```<code>  <List>
    {['first', 'second', 'third'].map((name, i) => (
      <ListItem key={i} dense button>
        <ListItemText primary={name} />
        <Checkbox
          disableRipple
          checked={false}
          onChange={(evt, checked) => this.handleToggle(evt, checked, name)}
        />
      </ListItem>
    ))}
  </List>
</code>```

Code SandBox

Edit

I don't want to use state in this component at all. Summarizing - how to pass event from ListItem (parent) to it's children (Checkbox)?

Final edit: I've found out the way how to deal with it. No state needed. Just two simple lines of code.

Since checkbox state is fully controlled by redux, I just moved the onClick func to the ListItem element with one line on code in it's body:

...dispatch(toggle(!this.props.elements[nameOfElement], name));

Anyways thanks to everyone for help. Upvoted every answer.

答:
One way to tackle this issue might be to use React refs to keep a reference of the child <ListItem/>, and probably use an uncontrolled component in order to detach your output from state updates, that is in this case, replace <Checkbox /> with <input type="checkbox"/>.

Checkboxes would then be updated either directly from the DOM element itself using onChange on <input />, or through React using onClick on the <ListIem/> that references the <input /> DOM element.

```<code>...
class App extends React.Component {
  constructor(props) {
    super(props);
    this.checkboxes = [
      {
        name: "first",
        checked: false
      },
      {
        name: "second",
        checked: false
      },
      {
        name: "third",
        checked: false
      }
    ];
  }

  handleListItemClicked = (evt, name) => {
    console.log("ListItem clicked :", name);
    this.checkboxes[name].checked = !this.checkboxes[name].checked;
  };

  handleInputChanged = (evt, name) => {
    console.log("input changed, evt.target :", evt.target);
    evt.target.checked = !evt.target.checked;
  };

  render() {
    return (
      <List>
        {this.checkboxes.map(({ name }, i) => (
          <div>
            <ListItem
              key={i}
              onClick={evt => this.handleListItemClicked(evt, name)}
              dense
              button
            >
              <ListItemText primary={name} />
              <input
                type="checkbox"
                name={name}
                ref={checkbox => {
                  this.checkboxes[name] = checkbox;
                }}
                onChange={evt => this.handleInputChanged(evt, name)}
              />
            </ListItem>
          </div>
        ))}
      </List>
    );
  }
}

...
</code>```

Here is a fork of your initial Code Sandbox : https://codesandbox.io/s/mox93j6nry

Hope this helps!

ContentLicense: CC BY-SA 3.0

Body:
Im having an issue. When you click listItem (whole separated li element) I want to call the onChange function on the checkbox component inside listItem.

I could easily move that function from checkbox to parent but I will loose the checked prop.

Checking the checkbox itself doesnt work, but just open the console to see the results. I want handleToggle function to fire properly when whole element is clicked (not only checkbox)

  <List>
    {['first', 'second', 'third'].map((name, i) => (
      <ListItem key={i} dense button>
        <ListItemText primary={name} />
        <Checkbox
          disableRipple
          checked={false}
          onChange={(evt, checked) => this.handleToggle(evt, checked, name)}
        />
      </ListItem>
    ))}
  </List>

Code SandBox

Edit

I don't want to use state in this component at all. Summarizing - how to pass event from ListItem (parent) to it's children (Checkbox)?

Final edit: I've found out the way how to deal with it. No state needed. Just two simple lines of code.

Since checkbox state is fully controlled by redux, I just moved the onClick func to the ListItem element with one line on code in it's body:

...dispatch(toggle(!this.props.elements[nameOfElement], name));

Anyways thanks to everyone for help. Upvoted every answer.

Body:
One way to tackle this issue might be to use React refs to keep a reference of the child <ListItem/>, and probably use an uncontrolled component in order to detach your output from state updates, that is in this case, replace <Checkbox /> with <input type="checkbox"/>.

Checkboxes would then be updated either directly from the DOM element itself using onChange on <input />, or through React using onClick on the <ListIem/> that references the <input /> DOM element.

...
class App extends React.Component {
  constructor(props) {
    super(props);
    this.checkboxes = [
      {
        name: "first",
        checked: false
      },
      {
        name: "second",
        checked: false
      },
      {
        name: "third",
        checked: false
      }
    ];
  }

  handleListItemClicked = (evt, name) => {
    console.log("ListItem clicked :", name);
    this.checkboxes[name].checked = !this.checkboxes[name].checked;
  };

  handleInputChanged = (evt, name) => {
    console.log("input changed, evt.target :", evt.target);
    evt.target.checked = !evt.target.checked;
  };

  render() {
    return (
      <List>
        {this.checkboxes.map(({ name }, i) => (
          <div>
            <ListItem
              key={i}
              onClick={evt => this.handleListItemClicked(evt, name)}
              dense
              button
            >
              <ListItemText primary={name} />
              <input
                type="checkbox"
                name={name}
                ref={checkbox => {
                  this.checkboxes[name] = checkbox;
                }}
                onChange={evt => this.handleInputChanged(evt, name)}
              />
            </ListItem>
          </div>
        ))}
      </List>
    );
  }
}

...

Here is a fork of your initial Code Sandbox : https://codesandbox.io/s/mox93j6nry

Hope this helps!


问:
Setting up kubernetes on linux raspberry
I am trying to setup kubernetes cluster on raspberry pi. I have two pi, one of them will work as master and other one will work as worker.

I am not using Hypriot Os instead using Raspbian stretch image. I followed these tutorial link1 link2. Link1 recommend to use Hypriot Os but I continued with Raspbian Stretch. This is what I have done till now on both master and worker:

Installed docker

Disabled swapfile

Added cgroup in /boot/cmdline.txt

Installed kubernetes in both the pi.

Initiated the master and worker then joined the master node.

Till now everything seems to working ok. But while running the command kubectl get nodes, I get:

```<code>NAME          STATUS     ROLES     AGE       VERSION
raspberrypi   NotReady   master    1h        v1.8.4
worker        NotReady   <none>    40m       v1.8.4
</code>```

My first question is why it shows worker as NotReady even my worker pi is on and running.

Next question is how can I access the cluster from the its dashboard. How to install dashboard.?

答:
Issues have been resolved in the comment section.

for debugging k8s Nodes in the cluster, we use the following command to get precise information

get the list of nodes

```<code>kubectl get nodes
</code>```

get the comprehensive info

```<code> kubectl describe nodes NODE_NAME
</code>```

by the above system information, we can verify and validate the status of kubelet docker and kube-proxy

Body:
I am trying to setup kubernetes cluster on raspberry pi. I have two pi, one of them will work as master and other one will work as worker.

I am not using Hypriot Os instead using Raspbian stretch image. I followed these tutorial link1 link2. Link1 recommend to use Hypriot Os but I continued with Raspbian Stretch. This is what I have done till now on both master and worker:

Installed docker

Disabled swapfile

Added cgroup in /boot/cmdline.txt

Installed kubernetes in both the pi.

Initiated the master and worker then joined the master node.

Till now everything seems to working ok. But while running the command kubectl get nodes, I get:

NAME          STATUS     ROLES     AGE       VERSION
raspberrypi   NotReady   master    1h        v1.8.4
worker        NotReady   <none>    40m       v1.8.4

My first question is why it shows worker as NotReady even my worker pi is on and running.

Next question is how can I access the cluster from the its dashboard. How to install dashboard.?

Body:
Issues have been resolved in the comment section.

for debugging k8s Nodes in the cluster, we use the following command to get precise information

get the list of nodes

kubectl get nodes

get the comprehensive info

 kubectl describe nodes NODE_NAME

by the above system information, we can verify and validate the status of kubelet docker and kube-proxy


问:
C# interface breakage, ABI
Suppose we have the class X in version 1 of the assembly A.dll:

```<code>class X {
    SomeType Property { set; get; }
}
</code>```

and then in version 2 of the assembly A.dll:

```<code>class X {
    SomeType Property { set; get; }
    SomeType OtherProperty { set; get; }
}
</code>```

Now suppose we have a second assembly B.dll that loads A.dll and uses X. Will the addition of the property OtherProperty break the ABI? Will B.dll fail to use A.dll/X? If not, would the order of the declarations make any difference? If the properties had been virtual, had it made any difference?

I guess I'm really asking: what are the general ABI rules? I know changing interfaces after they have been published is a bad thing, but I really would like to be able to add properties in some instances, without adding subclasses.

答: It won't break compatibility if is just used by the assembly B. But it will break if the assembly B defines a class which implements the interface, because that class doesn't implement the newly introduced property.

ContentLicense: CC BY-SA 2.5

Title: C# interface breakage, ABI

Body:
Suppose we have the class X in version 1 of the assembly A.dll:

class X {
    SomeType Property { set; get; }
}

and then in version 2 of the assembly A.dll:

class X {
    SomeType Property { set; get; }
    SomeType OtherProperty { set; get; }
}

Now suppose we have a second assembly B.dll that loads A.dll and uses X. Will the addition of the property OtherProperty break the ABI? Will B.dll fail to use A.dll/X? If not, would the order of the declarations make any difference? If the properties had been virtual, had it made any difference?

I guess I'm really asking: what are the general ABI rules? I know changing interfaces after they have been published is a bad thing, but I really would like to be able to add properties in some instances, without adding subclasses.


问:
Position Highcharts label to right side
I have a basic chart with a custom label, eg:

```<code>labels: {
  items: [{
    html: 'Testing Label',
    style: {
      left: '50px',
      top: '50px'
    }
  }]
}
</code>```

This works, but I'd like to position the label from the right side, I tried doing:

```<code>style: {
  right: '50px',
  top: '50px'
}
</code>```

but this doesn't work...

JsFiddle link:
http://jsfiddle.net/0ze2u47h/3/

答:
It seems that right property is not supported in chart.labels. For more complex configuration you can render the label using SVGRenderer:

```<code>  chart: {
    events: {
      load: function() {
        var chart = this,
          renderer = chart.renderer;

          var label = this.renderer.label('Test label', null, 100).add();
          label.attr({
            x: chart.plotWidth + chart.plotLeft - label.width
          });
      }
    }
  }
</code>```

Live demo: http://jsfiddle.net/kkulig/aob1e197/

The advantage of rendering labels via renderer (not via constructor options) is that you can access parameters of the already created chart and label (chart.plotWidth, chart.plotLeft, label.width in this case).

API reference: https://api.highcharts.com/class-reference/Highcharts.SVGRenderer#label

Title: Position Highcharts label to right side

Body:
I have a basic chart with a custom label, eg:

labels: {
  items: [{
    html: 'Testing Label',
    style: {
      left: '50px',
      top: '50px'
    }
  }]
}

This works, but I'd like to position the label from the right side, I tried doing:

style: {
  right: '50px',
  top: '50px'
}

but this doesn't work...

JsFiddle link:
http://jsfiddle.net/0ze2u47h/3/

Body:
It seems that right property is not supported in chart.labels. For more complex configuration you can render the label using SVGRenderer:

  chart: {
    events: {
      load: function() {
        var chart = this,
          renderer = chart.renderer;

          var label = this.renderer.label('Test label', null, 100).add();
          label.attr({
            x: chart.plotWidth + chart.plotLeft - label.width
          });
      }
    }
  }

Live demo: http://jsfiddle.net/kkulig/aob1e197/

The advantage of rendering labels via renderer (not via constructor options) is that you can access parameters of the already created chart and label (chart.plotWidth, chart.plotLeft, label.width in this case).

API reference: https://api.highcharts.com/class-reference/Highcharts.SVGRenderer#label


问:
Use a pipe which depends on a service in another service
In a service A, I need to use a pipe P. This pipe P needs a service B to work.  What I did so far in something like this:

My P pipe definition

```<code>export class PPipe implements PipeTransform {

  constructor(private aService: AService) {}

  transform(value:number) : string {
    return number.toString();
  }
}
</code>```

How I use it in my service B

```<code>@Injectable()
export class BService {

  pPipe = new PPipe();

  myFn() {
    const nbToStr = pPipe.transform(69);
  }
}
</code>```

But I get an error when building: Expected 1 arguments, but got 0..

Do I need to pass an instance of PPipe everytime I want to use it ? If so, how it is doable from a HTML template ?

Thanks for helping

答:
As another answer explains, it can be solved by exposing a pipe as a provider (it's not a provider by default) and injecting it as any other service. This way AService will be injected into PPipe by Angular injector.

The only proper case for using pipe transform manually is when a pipe is third-party and contains useful code that is available only in pipe class (e.g. Angular built-in pipes).

If a pipe is first-party, the proper way to handle this is to not call pipe transform but to use AService in BService directly. The pipe has to be refactored to be as slim as possible, while AService contains all code that is needed to reuse pipe's functionality.

Body:
In a service A, I need to use a pipe P. This pipe P needs a service B to work.  What I did so far in something like this:

My P pipe definition

export class PPipe implements PipeTransform {

  constructor(private aService: AService) {}

  transform(value:number) : string {
    return number.toString();
  }
}

How I use it in my service B

@Injectable()
export class BService {

  pPipe = new PPipe();

  myFn() {
    const nbToStr = pPipe.transform(69);
  }
}

But I get an error when building: Expected 1 arguments, but got 0..

Do I need to pass an instance of PPipe everytime I want to use it ? If so, how it is doable from a HTML template ?

Thanks for helping


问:
Execution failed with app:processDebugGoogleServices'

I have been trying to add retrieve some of my images from Firebase firestore. After I added the dependencies I have the following error

"Error:Execution failed for task ':app:processDebugGoogleServices'. >
  Please fix the version conflict either by updating the version of the
  google-services plugin (information about the latest version is
  available at
  https://bintray.com/android/android-tools/com.google.gms.google-services/)
  or updating the version of com.google.android.gms to 10.0.1."

This is my module app gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    buildToolsVersion "27.0.1"
    defaultConfig {
        applicationId "com.example.rimapps.charpapers"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions{
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'

    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:27.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:27.+'
    compile 'com.android.support:recyclerview-v7:27.+'
    compile 'com.android.support:cardview-v7:27.+'
    compile 'com.google.firebase:firebase-messaging:10.0.1'
    testCompile 'junit:junit:4.12'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.google.firebase:firebase-firestore:11.4.2'
    compile 'com.google.firebase:firebase-appindexing:10.0.1'

}
apply plugin: 'com.google.gms.google-services'```
</div>
</div>

This is my project gradle </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        //classpath 'com.google.gms:google-services:3.1.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.1.1'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://maven.google.com" }

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}</code>```

Please help to solve this problem I have tried all I could.

答:
To solve your issue, change this:

```<code> compile 'com.google.firebase:firebase-messaging:11.6.2'
 compile 'com.google.firebase:firebase-firestore:11.6.2'
 compile 'com.google.firebase:firebase-appindexing:11.6.2'
</code>```

THE FIREBASE VERSION IS:  11.6.2 - November 27, 2017

But you should update your gradle file:

```<code>... dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
...
</code>```

And now, change the compile for implementation:

```<code> implementation 'com.google.firebase:firebase-messaging:11.6.2'
 implementation 'com.google.firebase:firebase-firestore:11.6.2'
 implementation 'com.google.firebase:firebase-appindexing:11.6.2'
</code>```

Body:
I have been trying to add retrieve some of my images from Firebase firestore. After I added the dependencies I have the following error

"Error:Execution failed for task ':app:processDebugGoogleServices'. >
  Please fix the version conflict either by updating the version of the
  google-services plugin (information about the latest version is
  available at
  https://bintray.com/android/android-tools/com.google.gms.google-services/)
  or updating the version of com.google.android.gms to 10.0.1."

This is my module app gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    buildToolsVersion "27.0.1"
    defaultConfig {
        applicationId "com.example.rimapps.charpapers"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions{
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'

    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:27.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:27.+'
    compile 'com.android.support:recyclerview-v7:27.+'
    compile 'com.android.support:cardview-v7:27.+'
    compile 'com.google.firebase:firebase-messaging:10.0.1'
    testCompile 'junit:junit:4.12'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.google.firebase:firebase-firestore:11.4.2'
    compile 'com.google.firebase:firebase-appindexing:10.0.1'

}
apply plugin: 'com.google.gms.google-services'

This is my project gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        //classpath 'com.google.gms:google-services:3.1.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.1.1'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://maven.google.com" }

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Please help to solve this problem I have tried all I could.

Body:
To solve your issue, change this:

 compile 'com.google.firebase:firebase-messaging:11.6.2'
 compile 'com.google.firebase:firebase-firestore:11.6.2'
 compile 'com.google.firebase:firebase-appindexing:11.6.2'

THE FIREBASE VERSION IS:  11.6.2 - November 27, 2017

But you should update your gradle file:

... dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
...

And now, change the compile for implementation:

 implementation 'com.google.firebase:firebase-messaging:11.6.2'
 implementation 'com.google.firebase:firebase-firestore:11.6.2'
 implementation 'com.google.firebase:firebase-appindexing:11.6.2'


问:
captcha with sum of two numbers
how can I write captcha with sum of two numbers ?example:1+4
(please answer to this question completely,I don't know any thing about captcha!)</p>

答:
```<code>CAPTCHA is an acronym for:

Completely
Automated
Public
Turing-test to tell
Computers and
Humans
Apart
</code>```

CAPTCHA  code was created to stop automated computer spam robots from filling out forms, harvesting email addresses, and then sending out countless spam emails.

Title: captcha with sum of two numbers

Body:
CAPTCHA is an acronym for:

Completely
Automated
Public
Turing-test to tell
Computers and
Humans
Apart

CAPTCHA  code was created to stop automated computer spam robots from filling out forms, harvesting email addresses, and then sending out countless spam emails.


问:
Laravel - Additional relationship on a pivot table
I have a regular pivot table with 2 keys. However, I also have a 3rd column where I want to store a different key with a one to many relationship. Is this possible to have?

Example:

Pivot table:

Organization 1 | Organization 2 | Relation type

1 | 2 | 1

1 | 3 | 2

In this case organization number 1 has a relation with organization number 2 with the relation type being number 1. Organization number 1 also has a relation with organization number 3 with relation type 2.

Now is my question, how do I set up that additional one to many relationship on the pivot table?

答:
What you have here is a ternary relationship. You are saying that an organisation A relates with an organisation B and a relationship type. This is a very uncommon use case because in the vast majority of cases ternary relationships can be simplified to binary ones. You need a very deep inspection of your data model to determine whether your case can be simplified, but assuming that it can't here's my suggestions.

It's worth checking the eloquent docs in particular under Defining Custom Intermediate Table Models for this. Note that this requires Laravel 5.4+ to work.

The following should work:

```<code>class OrganisationOrganisationLink extends Pivot {
    public relationType() {
          return $this->belongsTo(RelationType::class); //You need to specify the foreign key correctly as a 2nd parameter
    }
}
</code>```

Then in your original model:

```<code>class Organisation extends Model {
    public relatedOrganisation() {
        return $this->belongsToMany(self::class)->using(OrganisationOrganisationLink::class);
    }
}
</code>```

Then when making practical use of this you can e.g. do:

```<code>$organisation = Organisation::with('relatedOrganisation')->first();
echo "Got ".$organisation->name." which relates to "
     .$organisation->relatedOrganisation->first()->name
     ." with relationship type "
     $organisation->relatedOrganisation->first()->pivot->relationshipType()->value('name');
</code>```

Of course the fields I've assumed may not exist but hopefully you get the idea.

Body:
What you have here is a ternary relationship. You are saying that an organisation A relates with an organisation B and a relationship type. This is a very uncommon use case because in the vast majority of cases ternary relationships can be simplified to binary ones. You need a very deep inspection of your data model to determine whether your case can be simplified, but assuming that it can't here's my suggestions.

It's worth checking the eloquent docs in particular under Defining Custom Intermediate Table Models for this. Note that this requires Laravel 5.4+ to work.

The following should work:

class OrganisationOrganisationLink extends Pivot {
    public relationType() {
          return $this->belongsTo(RelationType::class); //You need to specify the foreign key correctly as a 2nd parameter
    }
}

Then in your original model:

class Organisation extends Model {
    public relatedOrganisation() {
        return $this->belongsToMany(self::class)->using(OrganisationOrganisationLink::class);
    }
}

Then when making practical use of this you can e.g. do:

$organisation = Organisation::with('relatedOrganisation')->first();
echo "Got ".$organisation->name." which relates to "
     .$organisation->relatedOrganisation->first()->name
     ." with relationship type "
     $organisation->relatedOrganisation->first()->pivot->relationshipType()->value('name');

Of course the fields I've assumed may not exist but hopefully you get the idea.


问:
Sharing manager list with threads and process creates seperate copies
I want to share a list between the processes and threads. So I found the multiprocessing.Manager() for creating a list. I wrote the following piece of code:

```<code>import multiprocessing
import threading
import time

def consumer(l):
    counter = 0
    while counter < 20:
        time.sleep(5)
        l = l[len(l)/2:]
        print "consumer l: {}".format(l)
        counter += 5

def producer(l):
    for i in range(10):
        time.sleep(i)
        l.append(i)
        print "producer l: {}".format(l)

if __name__=="__main__":
    mgr = multiprocessing.Manager()
    l = mgr.list()

    p = threading.Thread(target=producer, args=(l,))
    c = multiprocessing.Process(target=consumer, args=(l,))

    p.start()
    c.start()

    p.join()
    c.join()
    print "done"
</code>```

It creates a process and a thread sharing a list created by manager. Producer appends to the list after every i seconds while consumer halves the list every 5 seconds. I expected that the lists would be same and both will be operating on it. But I observe that consumer and producer share the list only once and next time the lists are seperated.

Output observed:

```<code>producer l: [0]
producer l: [0, 1]
producer l: [0, 1, 2]
consumer l: [1, 2]
producer l: [0, 1, 2, 3]
producer l: [0, 1, 2, 3, 4]
consumer l: [2]
producer l: [0, 1, 2, 3, 4, 5]
consumer l: [2]
consumer l: [2]
producer l: [0, 1, 2, 3, 4, 5, 6]
producer l: [0, 1, 2, 3, 4, 5, 6, 7]
producer l: [0, 1, 2, 3, 4, 5, 6, 7, 8]
producer l: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
done
</code>```

What should be done so that both of them uses same list throughout?

答:
Your problem is this line:

```<code>    l = l[len(l)/2:]
</code>```

It looks ok, but what it actually does is that it creates a new copy of l and assigns l to this new object. This means the variables diverge at your first consumer execution, and the l in consumer is no longer bound to the l passed to it.

Consider this version of your consumer:

```<code>def consumer(l):
    counter = 0
    while counter < 20:
        time.sleep(5)
        n = len(l)/2
        for _ in range(0,n+1):
            try:
                l.pop()
            except IndexError:
                pass
        print "consumer l: {}".format(l)
        counter += 5
</code>```

It is not elegant and it probably is not quite what you are looking for, but I have replaced assigning l to a new instance with list manipulation methods (pop in this case). As long as you keep modifying your l with list management methods like pop, append, insert or remove, you are fine.

NB your producer would be suffering from the same problem if you assigned there l to something new, but you already have l.append() there, so that part is fine.

Body:
I want to share a list between the processes and threads. So I found the multiprocessing.Manager() for creating a list. I wrote the following piece of code:

import multiprocessing
import threading
import time

def consumer(l):
    counter = 0
    while counter < 20:
        time.sleep(5)
        l = l[len(l)/2:]
        print "consumer l: {}".format(l)
        counter += 5

def producer(l):
    for i in range(10):
        time.sleep(i)
        l.append(i)
        print "producer l: {}".format(l)

if __name__=="__main__":
    mgr = multiprocessing.Manager()
    l = mgr.list()

    p = threading.Thread(target=producer, args=(l,))
    c = multiprocessing.Process(target=consumer, args=(l,))

    p.start()
    c.start()

    p.join()
    c.join()
    print "done"

It creates a process and a thread sharing a list created by manager. Producer appends to the list after every i seconds while consumer halves the list every 5 seconds. I expected that the lists would be same and both will be operating on it. But I observe that consumer and producer share the list only once and next time the lists are seperated.

Output observed:

producer l: [0]
producer l: [0, 1]
producer l: [0, 1, 2]
consumer l: [1, 2]
producer l: [0, 1, 2, 3]
producer l: [0, 1, 2, 3, 4]
consumer l: [2]
producer l: [0, 1, 2, 3, 4, 5]
consumer l: [2]
consumer l: [2]
producer l: [0, 1, 2, 3, 4, 5, 6]
producer l: [0, 1, 2, 3, 4, 5, 6, 7]
producer l: [0, 1, 2, 3, 4, 5, 6, 7, 8]
producer l: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
done

What should be done so that both of them uses same list throughout?

Body:
Your problem is this line:

    l = l[len(l)/2:]

It looks ok, but what it actually does is that it creates a new copy of l and assigns l to this new object. This means the variables diverge at your first consumer execution, and the l in consumer is no longer bound to the l passed to it.

Consider this version of your consumer:

def consumer(l):
    counter = 0
    while counter < 20:
        time.sleep(5)
        n = len(l)/2
        for _ in range(0,n+1):
            try:
                l.pop()
            except IndexError:
                pass
        print "consumer l: {}".format(l)
        counter += 5

It is not elegant and it probably is not quite what you are looking for, but I have replaced assigning l to a new instance with list manipulation methods (pop in this case). As long as you keep modifying your l with list management methods like pop, append, insert or remove, you are fine.

NB your producer would be suffering from the same problem if you assigned there l to something new, but you already have l.append() there, so that part is fine.


问:
AAPT2 gradle issue in android studio 3.0 beta4
Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

We have already added android.enableAapt2=false in gradle.properties file

答:
Solved it mate finally

please update your compileSdkVersion to 26.That will solve your issue.I think so

```<code>android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
</code>```

i have Solved it with increasing compileSDKVersion to 26

Body:
Solved it mate finally

please update your compileSdkVersion to 26.That will solve your issue.I think so

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'

i have Solved it with increasing compileSDKVersion to 26


问:
Revolution Slider - "Invalid left Tween Value: NaN"
I am using a theme from wrapbootstrap on a project and I am getting a Not a number value on the slider which is causing some minor performance issues with site speed.

Here is a link to the theme:
http://themes.iamabdus.com/bigbag/1.0/index.html

Please see the chrome console error for:

invalid left tween value: NaN

Does anyone know how to get around this issue? Would be appreciated, even if a quick fix/workaround.

答:
I came across the same error for a wrapbootstrap theme as well and I looked further into jedison's comment and sure enough this was the case for my app.

When I logout of my ionic app, I clear out my pages. However, the revolution init function is still being called and this throws the error.

The solution that worked for me was I put this line in my logout function,

jQuery('#rev-slider').revpause();

then on login, all pages are reloaded, with a new rev slider and its init function.


问:
C#: How do you make VSC# Express 2008 refactor the name of events when object is renamed?
How do you make Visual Studio C# Express 2008 refactor the name of events when object is renamed?

Let's say I have an object named txtCars and it already has an event handler for on txtCarsTextChanged and I rename the object from txtCars to txtTrucks. Everything else is refactored but the event txtCarsTextChanged isn't. Is there a shortcut to make it all refactor or atleast along with the events, even on the form design.cs file without having to edit the event name and back in the form designer.cs file manually?

答: If you mean that you'd like txtCarsTextChanged when you rename the txtCars object, then I'm afraid the answer is no. However, you can right click the name of the event and perform a separate Rename refactor on it as well. That should pick up any instance of where that event is used, including designer generated code.

OwnerDisplayName: Miles West

OwnerDisplayName: Andy

LastEditorDisplayName: Andy


问:
Rails 5 don't precompile JS files with ES6 code in production
I am deploying an app with some javascript that contain ES6 code.

When I did run bundle exec rake assets:precompile RAILS_ENV=production, I got:

```<code>ExecJS::RuntimeError: SyntaxError: Unexpected token: punc ())
</code>```

This is because prueba.js has the following:

```<code>var greetings = () => {
  let saludo = 'tio';
  console.log('saludo' + saludo)
};
greetings();
</code>```

And Uglify don't recognize ES6. For fix this, I had installed and setting the gems:

```<code>gem 'sprockets-es6', '~> 0.9.2'
gem 'babel-transpiler', '~> 0.7.0'
</code>```

But isn't working,

In application.rb, I have:

```<code>require "action_view/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
require 'sprockets/es6'
</code>```

Note: If i run rake assets:precompile without RAILS_ENV=production, I don't get errors

答:
When using ES6, if you use uglifier (3.2.0)
you can change the file production.rb

with config.assets.js_compressor = Uglifier.new(harmony: true)

Body:
I am deploying an app with some javascript that contain ES6 code.

When I did run bundle exec rake assets:precompile RAILS_ENV=production, I got:

ExecJS::RuntimeError: SyntaxError: Unexpected token: punc ())

This is because prueba.js has the following:

var greetings = () => {
  let saludo = 'tio';
  console.log('saludo' + saludo)
};
greetings();

And Uglify don't recognize ES6. For fix this, I had installed and setting the gems:

gem 'sprockets-es6', '~> 0.9.2'
gem 'babel-transpiler', '~> 0.7.0'

But isn't working,

In application.rb, I have:

require "action_view/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
require 'sprockets/es6'

Note: If i run rake assets:precompile without RAILS_ENV=production, I don't get errors


问:
Javascript/jQuery --> How to make loop so that after the last testimonial /li/ the whole ul will repeat again?
How to make loop so that after the last testimonial /li/ the whole ul will repeat again (so after the last slide there will be first slide again)?

This is my jsFiddle: https://jsfiddle.net/t2zwo0fr/14/

This is the function which does interval, I want to enhance it with loop so that after the last testimonial /li/ there whole ul will repeat:

```<code>function blink() {
    if (active || slideIndex >= slideCount - 1) {
        return;
    }
    slideIndex++;
    active = true;
    $('ul').animate(
        {'left': $('ul').position().left-szer1slidu},
        3000,
        function() {
            { active = false; }
        }
    );
}
setInterval(blink,1000);
</code>```

答:
Well, when the animation reaches the third li, I would use appendChild to move the first li to the last position and every time the "previous" animation is called, I'd insertBefore the other way around.. but that's without jQuery. :p

Also, don't forget to update the position of the ul to still show the current li.

Body:
How to make loop so that after the last testimonial /li/ the whole ul will repeat again (so after the last slide there will be first slide again)?

This is my jsFiddle: https://jsfiddle.net/t2zwo0fr/14/

This is the function which does interval, I want to enhance it with loop so that after the last testimonial /li/ there whole ul will repeat:

function blink() {
    if (active || slideIndex >= slideCount - 1) {
        return;
    }
    slideIndex++;
    active = true;
    $('ul').animate(
        {'left': $('ul').position().left-szer1slidu},
        3000,
        function() {
            { active = false; }
        }
    );
}
setInterval(blink,1000);


问:
node js. how do i call local file from html
i have this file to run app.js

```<code>var express = require('express')
var app = express();
var router = express.Router();
var path = __dirname + '/views/';

router.get("/",function(req,res){
 res.sendFile(path + "index.html");
});

app.use("/",router);

app.use("*",function(req,res){
 res.sendFile(path + "index.html");
});

app.listen(8080,function(){
 console.log("Live at Port 8080");
});
</code>```

and i have "index.html" inside of "views" folder.
i want to import my local css file inside of "css" folder.
i tried to call the file like this

```<code><link href="css/main.css">
</code>```

or

```<code><link href="../css/main.css">
</code>```

but it didnt work.
is there any specific method to get them?

thanks

答:
Put your css folder inside view folder</p>

```<code>var express = require('express')
var app = express();
var router = express.Router();
var path = __dirname + '/views/';
app.use(express.static(path.join(__dirname, 'views')));

router.get("/",function(req,res){
 res.sendFile("index.html");
});

app.use("/",router);

app.use("*",function(req,res){
 res.sendFile("index.html");
});

app.listen(8080,function(){
 console.log("Live at Port 8080");
});
</code>```

Body:
i have this file to run app.js

var express = require('express')
var app = express();
var router = express.Router();
var path = __dirname + '/views/';

router.get("/",function(req,res){
 res.sendFile(path + "index.html");
});

app.use("/",router);

app.use("*",function(req,res){
 res.sendFile(path + "index.html");
});

app.listen(8080,function(){
 console.log("Live at Port 8080");
});

and i have "index.html" inside of "views" folder.
i want to import my local css file inside of "css" folder.
i tried to call the file like this

<link href="css/main.css">

or

<link href="../css/main.css">

but it didnt work.
is there any specific method to get them?

thanks

Body:
Put your css folder inside view folder

var express = require('express')
var app = express();
var router = express.Router();
var path = __dirname + '/views/';
app.use(express.static(path.join(__dirname, 'views')));

router.get("/",function(req,res){
 res.sendFile("index.html");
});

app.use("/",router);

app.use("*",function(req,res){
 res.sendFile("index.html");
});

app.listen(8080,function(){
 console.log("Live at Port 8080");
});


问:
Unable to run conda in Mac OS after installing Anaconda
After installing Anaconda, I try to validate the install, and when I run conda in bash, I get a 'command not found' error.

I'm running macOS Sierra and trying to installing Anaconda for Python 2.7.

答:
Anaconda places it's binaries in it's own install directory. As mentioned in the Anaconda documentation the defaults for these are as follows:

Windows 10: C:\Users\<your-username>\Anaconda3\

macOS: /Users/<your-username>/anaconda3

Linux: /home/<your-username>/anaconda3

When installing Anaconda it should prompt you:

Do you wish the installer to prepend the Anaconda<2 or 3>install
  location to PATH in your /home//.bashrc?

If you choose not to do this then the path to the Anaconda binaries will not be added to your PATH environment variable in your shell. Therefor you will either need to call the activate script using the full path to your install directory (in macOS), like:

```<code>/Users/<your-username>/anaconda3/bin/activate root
</code>```

Alternatively, you should manually add the Anaconda binary path to your PATH environment file in your ~/.bashrc file. Instructions on how do do this can be found in the Anaconda documentation, here: Should I add Anaconda to the macOS or Linux PATH?

Body:
Anaconda places it's binaries in it's own install directory. As mentioned in the Anaconda documentation the defaults for these are as follows:

Windows 10: C:\Users\<your-username>\Anaconda3\

macOS: /Users/<your-username>/anaconda3

Linux: /home/<your-username>/anaconda3

When installing Anaconda it should prompt you:

Do you wish the installer to prepend the Anaconda<2 or 3>install
  location to PATH in your /home//.bashrc?

If you choose not to do this then the path to the Anaconda binaries will not be added to your PATH environment variable in your shell. Therefor you will either need to call the activate script using the full path to your install directory (in macOS), like:

/Users/<your-username>/anaconda3/bin/activate root

Alternatively, you should manually add the Anaconda binary path to your PATH environment file in your ~/.bashrc file. Instructions on how do do this can be found in the Anaconda documentation, here: Should I add Anaconda to the macOS or Linux PATH?


问:
Does the registration token refresh whenever the app is launched in iOS?
When I install app for the first time and it asks for the permission for getting notification, if I press yes then the Device token is generated, but whenever I relaunch the app, I get the error:

```<code>Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)
</code>```

Can anyone tell whether the device token is generated every time the app is launched?

答:
Today the doc says https://firebase.google.com/docs/cloud-messaging/ios/client#access_the_registration_token

The app is restored on a new device

The user uninstalls/reinstall the app

The user clears app data.

Seems like FCM Token is not generated when we delete the instance ID.

Body:
When I install app for the first time and it asks for the permission for getting notification, if I press yes then the Device token is generated, but whenever I relaunch the app, I get the error:

Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)

Can anyone tell whether the device token is generated every time the app is launched?


问:
How can I get today's timestamp in PHP
I tried

```<code>$dtToday = DateTime::createFromFormat('Y-m-d', date('Y-m-d'));
</code>```

but when I output it

```<code>die($dtToday->format('d M Y g:i:s a'));
</code>```

I still get the time eg "22 Jan 2011 4:53:59 pm". Why is that?

UPDATE

Ah... many people misunderstood me, my bad, I forgot to point out the main point. I created the date with just the date portion, I don't want the time. So I'd expect something like

```<code>22 Jan 2011 12:00:00 am
</code>```

答:
See the documentation for DateTime::createFromFormat:

If format does not contain the character ! then portions of the generated time which are not specified in format will be set to the current system time.

If you do the following function call, you'll get the result you expect:

```<code>$dtToday = DateTime::createFromFormat('!Y-m-d', date('Y-m-d'));
</code>```

Title: How can I get today's timestamp in PHP

Body:
I tried

$dtToday = DateTime::createFromFormat('Y-m-d', date('Y-m-d'));

but when I output it

die($dtToday->format('d M Y g:i:s a'));

I still get the time eg "22 Jan 2011 4:53:59 pm". Why is that?

UPDATE

Ah... many people misunderstood me, my bad, I forgot to point out the main point. I created the date with just the date portion, I don't want the time. So I'd expect something like

22 Jan 2011 12:00:00 am

Body:
See the documentation for DateTime::createFromFormat:

If format does not contain the character ! then portions of the generated time which are not specified in format will be set to the current system time.

If you do the following function call, you'll get the result you expect:

$dtToday = DateTime::createFromFormat('!Y-m-d', date('Y-m-d'));


问:
Django multiple template rendering
At the moment I'm working on a pretty complex page that needs to be updated when a user selects a recipe that is displayed on the page.Upon selection of a recipe, the price and the name of the recipe need to be displayed on the page.

My thought is to render multiple extend/include templates that are each responsible for their own part of the webpage.However, I face a few problems:

I need multiple view functions to process data for all templates.

I need to pass the request to multiple view functions so that they return the template with the correct data

One of the functions not only takes the request but also the slug of a model object to update data on the page.

Questions:

How do I send responses/data from different view functions to each other?

How do I pass the request to multiple functions?

Does the rendering of the extends also make sure that the base.html is rendered?

Are extends the right thing to use or should I use includes?

So far I have thought of this system:

base.html

```<code><body>
    {% block extend1 %}
    {% endblock %}

    {% block extend2 %}
    {% endblock %}

    {% block extend3 %}
    {% endblock %}
</body>
</code>```

extend1.html (example for the 3 extends)

```<code>{% extends base.html %}

{% block extend1 %}
    #html code
{% endblock
</code>```

views.py

```<code>def extend1(request):
    #do something
    template = 'extend1.html'
    context = a, b, c
    return render(template.render(context))

def extend2(request):
    #do something
    template = 'extend2.html'
    context = d, e, f
    return render(template.render(context))

def extend3(request, slug):
    #do something
    template = 'extend3.html'
    context = g, h, i
    return render(template.render(context))
</code>```

答:
You're labouring under a misapprehension of how the Django template language works- By default Django takes a Request, relays it (via the urls in your urls.py) to the View, which can take the data from the request, and render a Template- the result of which is the HTML from your template.html page interpolated with the context information that you passed to the rendering- as a Response to the browser, which displays the HTML as a page.

The template rendering happens server side- once it's been returned as a Response, Django templates no longer have any control over what is displayed client side. The Django template language is used to determine what will be rendered to the Response but after Template rendering, it doesn't exist on the page anymore and can't be used to modify what's displayed client-side. For that you need Javascript.

Javascript and it's various permutations is what people use to provide client-side interactivity to a webpage In your example, a Javascript event would fire when the user selects a recipe, and could place an AJAX call back to your server which would fetch that specific recipe information.

I recommend doing some more advanced reading into APIs (A good starting point is Django Rest Framework, which has an in-depth tutorial) and making API calls. And possibly look into Single Page Apps (SPAs) and Django tutorials, as that sounds like what you're trying to achieve.

Title: Django multiple template rendering

Body:
At the moment I'm working on a pretty complex page that needs to be updated when a user selects a recipe that is displayed on the page.Upon selection of a recipe, the price and the name of the recipe need to be displayed on the page.

My thought is to render multiple extend/include templates that are each responsible for their own part of the webpage.However, I face a few problems:

I need multiple view functions to process data for all templates.

I need to pass the request to multiple view functions so that they return the template with the correct data

One of the functions not only takes the request but also the slug of a model object to update data on the page.

Questions:

How do I send responses/data from different view functions to each other?

How do I pass the request to multiple functions?

Does the rendering of the extends also make sure that the base.html is rendered?

Are extends the right thing to use or should I use includes?

So far I have thought of this system:

base.html

    {% block extend1 %}
    {% endblock %}

    {% block extend2 %}
    {% endblock %}

    {% block extend3 %}
    {% endblock %}

extend1.html (example for the 3 extends)

{% extends base.html %}

{% block extend1 %}
    #html code
{% endblock

views.py

def extend1(request):
    #do something
    template = 'extend1.html'
    context = a, b, c
    return render(template.render(context))

def extend2(request):
    #do something
    template = 'extend2.html'
    context = d, e, f
    return render(template.render(context))

def extend3(request, slug):
    #do something
    template = 'extend3.html'
    context = g, h, i
    return render(template.render(context))


问:
Nested maps in Firebase and custom objects
Apologies for the rather basic question but I am having a little trouble with my code.

I intended to create a database of events and I wanted the flexibility of retrieving an entire day's worth of events, or a month's worth or even a years worth. So I decided to store the data under 'year'>'month'>'day'. Initially I tried to do it using custom java objects that I thought would be easier to work with, but unfortunately this adds an extra child node between each object with the name of the getter method.
I achieved what I wanted using long nested hash maps:
    Map<String,Map<String,Map<String,Map<String,Object>>>> mMap = new HashMap<>();

but I am sure that there must be a better way.

I have saved a picture but I can't post it as my reputation <10.
link to json map showing what my custom objects made vs the intended result achieve by the nested maps

so here is the class for the first map (object class not included as it is a bit long):

```<code>public class DayKeyBookingsMap {
private Map<String, BookingObject> dayKeyBookingsMap = new HashMap<>();

public DayKeyBookingsMap(){}
public DayKeyBookingsMap(BookingObject bookingObject){
    dayKeyBookingsMap.put(bookingObject.getDateKey(),bookingObject);
}

public Map<String, BookingObject> getDayKeyBookingsMap() {
    return dayKeyBookingsMap;    }

public void setDayKeyBookingsMap(Map<String, BookingObject> dayKeyBookingsMap) {
    this.dayKeyBookingsMap = dayKeyBookingsMap;    }
}
</code>```

and a separate class of the next level:

```<code>public class MonthKeyBookingsMap {
private Map<String,DayKeyBookingsMap> monthKeyBookingsMap = new HashMap<>();

public MonthKeyBookingsMap(){}
public MonthKeyBookingsMap(BookingObject bookingObject){
    DayKeyBookingsMap dayKeyBookingsMap = new DayKeyBookingsMap(bookingObject);
    monthKeyBookingsMap.put(bookingObject.getMonthKey(),dayKeyBookingsMap);
}

public Map<String, DayKeyBookingsMap> getMonthKeyBookingsMap() {
    return monthKeyBookingsMap;
}

public void setMonthKeyBookingsMap(Map<String, DayKeyBookingsMap> monthKeyBookingsMap) {
    this.monthKeyBookingsMap = monthKeyBookingsMap;
}
}
</code>```

and I haven't included the third level. But I constructed the final object with:

```<code>YearKeyBookingsMap(myBasicObject)
</code>```

which called the third level constructure, which in turn used the second level constructor etc.:

```<code>public YearKeyBookingsMap(BookingObject bookingObject){
    MonthKeyBookingsMap monthKeyBookingsMap = new MonthKeyBookingsMap(bookingObject);
    yearKeyBookingsMap.put(bookingObject.getYearKey(),monthKeyBookingsMap);
}
</code>```

答:
To achieve something like this:

You only need to use six lines of code:

```<code>Map<String, Object> map = new HashMap<String, Object>();
map.put("dateKey", "20170105");
map.put("eventTitle", "New Booking");
map.put("monthKey", "01");
map.put("yearKey", "2017");
FirebaseDatabase.getInstance().getReference().child("AAAAB").child("2017").child("01").child("20170105").setValue(map);
</code>```

There is no need to use nested HashMap.

Body:
Apologies for the rather basic question but I am having a little trouble with my code.

I intended to create a database of events and I wanted the flexibility of retrieving an entire day's worth of events, or a month's worth or even a years worth. So I decided to store the data under 'year'>'month'>'day'. Initially I tried to do it using custom java objects that I thought would be easier to work with, but unfortunately this adds an extra child node between each object with the name of the getter method.
I achieved what I wanted using long nested hash maps:
    Map<String,Map<String,Map<String,Map<String,Object>>>> mMap = new HashMap<>();

but I am sure that there must be a better way.

I have saved a picture but I can't post it as my reputation <10.
link to json map showing what my custom objects made vs the intended result achieve by the nested maps

so here is the class for the first map (object class not included as it is a bit long):

public class DayKeyBookingsMap {
private Map<String, BookingObject> dayKeyBookingsMap = new HashMap<>();

public DayKeyBookingsMap(){}
public DayKeyBookingsMap(BookingObject bookingObject){
    dayKeyBookingsMap.put(bookingObject.getDateKey(),bookingObject);
}

public Map<String, BookingObject> getDayKeyBookingsMap() {
    return dayKeyBookingsMap;    }

public void setDayKeyBookingsMap(Map<String, BookingObject> dayKeyBookingsMap) {
    this.dayKeyBookingsMap = dayKeyBookingsMap;    }
}

and a separate class of the next level:

public class MonthKeyBookingsMap {
private Map<String,DayKeyBookingsMap> monthKeyBookingsMap = new HashMap<>();

public MonthKeyBookingsMap(){}
public MonthKeyBookingsMap(BookingObject bookingObject){
    DayKeyBookingsMap dayKeyBookingsMap = new DayKeyBookingsMap(bookingObject);
    monthKeyBookingsMap.put(bookingObject.getMonthKey(),dayKeyBookingsMap);
}

public Map<String, DayKeyBookingsMap> getMonthKeyBookingsMap() {
    return monthKeyBookingsMap;
}

public void setMonthKeyBookingsMap(Map<String, DayKeyBookingsMap> monthKeyBookingsMap) {
    this.monthKeyBookingsMap = monthKeyBookingsMap;
}
}

and I haven't included the third level. But I constructed the final object with:

YearKeyBookingsMap(myBasicObject)

which called the third level constructure, which in turn used the second level constructor etc.:

public YearKeyBookingsMap(BookingObject bookingObject){
    MonthKeyBookingsMap monthKeyBookingsMap = new MonthKeyBookingsMap(bookingObject);
    yearKeyBookingsMap.put(bookingObject.getYearKey(),monthKeyBookingsMap);
}

Body:
To achieve something like this:

You only need to use six lines of code:

Map<String, Object> map = new HashMap<String, Object>();
map.put("dateKey", "20170105");
map.put("eventTitle", "New Booking");
map.put("monthKey", "01");
map.put("yearKey", "2017");
FirebaseDatabase.getInstance().getReference().child("AAAAB").child("2017").child("01").child("20170105").setValue(map);

There is no need to use nested HashMap.


问:
Difference between Spring and Spring Boot
There are many people who advised me to use Spring Boot instead of Spring to develop REST web services.
I want to know what exactly the difference between the two is?</p>

答:
Spring Boot is opinionated view of Spring Framework projects.Let's analyse it through one program taken from Spring Boot Documentation.

```<code>@RestController
@EnableAutoConfiguration
public class Example {

    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Example.class, args);
    }
  }
</code>```

It's a very basic REST API and you need to add Spring-boot-starter-web in your POM.xml for the same. Since you have added starter-web dependency, the annotation
@EnableAutoConfiguration guesses that you want to develop a web application and sets up Spring accordingly.

Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. For example, if HSQLDB is on your classpath, and you have not manually configured any database connection beans, then Spring Boot auto-configures an in-memory database.

It's opinionated like maven. Maven creates a project structure for you which it thinks is the general pattern of projects like it adds src/main/java folder or resource folder for you.

Spring boot helps in faster development. It has many starter projects that helps you get going quite faster. It also includes many non functional features like: embedded servers, security, metrics, health checks etc. In short, it makes, spring based application development easier with minimally invading code(Less configuration files, less no of annotations).

Reference: https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-documentation-about

Body:
Spring Boot is opinionated view of Spring Framework projects.Let's analyse it through one program taken from Spring Boot Documentation.

@RestController
@EnableAutoConfiguration
public class Example {

    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Example.class, args);
    }
  }

It's a very basic REST API and you need to add Spring-boot-starter-web in your POM.xml for the same. Since you have added starter-web dependency, the annotation
@EnableAutoConfiguration guesses that you want to develop a web application and sets up Spring accordingly.

Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. For example, if HSQLDB is on your classpath, and you have not manually configured any database connection beans, then Spring Boot auto-configures an in-memory database.

It's opinionated like maven. Maven creates a project structure for you which it thinks is the general pattern of projects like it adds src/main/java folder or resource folder for you.

Spring boot helps in faster development. It has many starter projects that helps you get going quite faster. It also includes many non functional features like: embedded servers, security, metrics, health checks etc. In short, it makes, spring based application development easier with minimally invading code(Less configuration files, less no of annotations).

Reference: https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-documentation-about


问:
PHP Strange Behaviour of file_exists
I have this for loop in php:

```<code>for ($i=0; $i <= 10; $i++) {
      if (file_exists('./img/'.$i.'.jpg')) {
          echo 'FILE: '.$i.'.jpg EXISTS!';
      } else {
          echo 'FILE: '.$i.'.jpg NOT EXISTS!';
      }
}
</code>```

I put in folder img only 1.jpg and 3.jpg so i need to get only for 1.jpg and 3.jpg file exists but i im getting for all files that does not exists or one file exists and all others does not exists...why is this function not returning correctly results?

答:
I think you are confused with the file structure and relative path

./ is same as / gets the same folders in script running dir, If you want to go to parent dir then you need to add ../

I have created the same program it works fine.

Running path /var/www/html/test and checking file folder /var/www/html/test/img and it works fine

```<code>   for ($i=1; $i <= 10; $i++) {
    $selva = "./img/$i.jpg";
      if (file_exists($selva)) {
          echo 'FILE: '.$selva.' EXISTS!<br>';
      } else {
          echo 'FILE: '.$selva.' NOT EXISTS!<br>';
      }
   }
</code>```

I think you trying to access outside dir from the php running dir so you need to use ../

Else you can simply give the absolute path

you can get current folder by using dirname(__FILE__)

Title: PHP Strange Behaviour of file_exists

Body:
I have this for loop in php:

for ($i=0; $i <= 10; $i++) {
      if (file_exists('./img/'.$i.'.jpg')) {
          echo 'FILE: '.$i.'.jpg EXISTS!';
      } else {
          echo 'FILE: '.$i.'.jpg NOT EXISTS!';
      }
}

I put in folder img only 1.jpg and 3.jpg so i need to get only for 1.jpg and 3.jpg file exists but i im getting for all files that does not exists or one file exists and all others does not exists...why is this function not returning correctly results?

Body:
I think you are confused with the file structure and relative path

./ is same as / gets the same folders in script running dir, If you want to go to parent dir then you need to add ../

I have created the same program it works fine.

Running path /var/www/html/test and checking file folder /var/www/html/test/img and it works fine

   for ($i=1; $i <= 10; $i++) {
    $selva = "./img/$i.jpg";
      if (file_exists($selva)) {
          echo 'FILE: '.$selva.' EXISTS!<br>';
      } else {
          echo 'FILE: '.$selva.' NOT EXISTS!<br>';
      }
   }

I think you trying to access outside dir from the php running dir so you need to use ../

Else you can simply give the absolute path

you can get current folder by using dirname(__FILE__)


问:
Setting a VBA form object using a string

Hello,

I am trying to set up a form which is a calendar from which the user can select a date (by default the current month appears). The form consists of 42 command buttons (I have left the default name ie. CommandButton1) which I am setting the day number.

At the moment I have a long-winded section of code for each button (I used Excel to generate this rather than type it all out) which locks and hides the button if it is outside of the month in question which looks like this:

```<code>NewDate.CommandButton1.Caption = Format(DATlngFirstMonth - DATintDayNumFirst + DATintX, "dd")
If DATintX < DATintDayNumFirst Then
    With NewDate.CommandButton1
        .Locked = True
        .Visible = DATbooShowExtraDays
        .ForeColor = RGB(150, 150, 150)
    End With
Else
    With NewDate.CommandButton1
        .Locked = False
        .Visible = True
        .ForeColor = RGB(0, 0, 0)
    End With
End If
</code>```

I know that I can refer to a command button by:

```<code>Dim objCommandButton As Object
Set objCommandButton = NewDate.CommandButton1
</code>```

..which neatens the code up somewhat. But what I would like to do is refer to the command button as a string so I can loop through all 42, ie.

```<code>Dim n as integer
n = 1

Do Until n > 42
Set objCommandButton = NewDate.CommandButton & n
'Some operations
n = n + 1
Loop
</code>```

Many thanks in advance for assistance.

答:
You can loop through all controls of the form. Try

```<code>Sub LoopButtons()
Dim it As Object

For Each it In NewDate.Controls
    Debug.Print it.Name
Next it

End Sub
</code>```

Then you can put conditional expression (if ... then) in place of Debug.Print or whatever. For example

```<code>If Instr(it.Name, "CommandButton") Then
'do your code
end if
</code>```

Body:
Hello,

I am trying to set up a form which is a calendar from which the user can select a date (by default the current month appears). The form consists of 42 command buttons (I have left the default name ie. CommandButton1) which I am setting the day number.

At the moment I have a long-winded section of code for each button (I used Excel to generate this rather than type it all out) which locks and hides the button if it is outside of the month in question which looks like this:

NewDate.CommandButton1.Caption = Format(DATlngFirstMonth - DATintDayNumFirst + DATintX, "dd")
If DATintX < DATintDayNumFirst Then
    With NewDate.CommandButton1
        .Locked = True
        .Visible = DATbooShowExtraDays
        .ForeColor = RGB(150, 150, 150)
    End With
Else
    With NewDate.CommandButton1
        .Locked = False
        .Visible = True
        .ForeColor = RGB(0, 0, 0)
    End With
End If

I know that I can refer to a command button by:

Dim objCommandButton As Object
Set objCommandButton = NewDate.CommandButton1

..which neatens the code up somewhat. But what I would like to do is refer to the command button as a string so I can loop through all 42, ie.

Dim n as integer
n = 1

Do Until n > 42
Set objCommandButton = NewDate.CommandButton & n
'Some operations
n = n + 1
Loop

Many thanks in advance for assistance.

Body:
You can loop through all controls of the form. Try

Sub LoopButtons()
Dim it As Object

For Each it In NewDate.Controls
    Debug.Print it.Name
Next it

End Sub

Then you can put conditional expression (if ... then) in place of Debug.Print or whatever. For example

If Instr(it.Name, "CommandButton") Then
'do your code
end if