问:
Mongo SSL with Java Exception sending message
I'm using mongo to create SSL connection between the java client and a mongo replica set. It worked fine with mongo shell so I assume I have done something wrong with java. There is already a thread that is similar to this but it didn't help.
Here is my configuration:

Starting two mongod:

```<code>mongod --keyFile D:\mongoDBFiles\mongokey --sslMode requireSSL --sslPEMKeyFile D:\mongoDBFiles\mongodb.pem --port 27017 --dbpath D:\mongoDBFiles\node1 --replSet foo --smallfiles --oplogSize 128
mongod --keyFile D:\mongoDBFiles\mongokey --sslMode requireSSL --sslPEMKeyFile D:\mongoDBFiles\mongodb.pem --port 27018 --dbpath D:\mongoDBFiles\node2 --replSet foo --smallfiles --oplogSize 128
</code>```

If I just use mongo shell it would work well like this:

```<code>mongo --ssl --sslCAFile D:\mongoDBFiles\mongodb.pem --sslPEMKeyFile D:\mongoDBFiles\mongoclient.pem --sslPEMKeyPassword password
</code>```

However it doesn't work with java driver:

```<code>        final MongoCredential credential = MongoCredential.createCredential("admin", "admin", "password".toCharArray());
        final MongoClientOptions o = new MongoClientOptions.Builder().socketFactory(SSLSocketFactory.getDefault()).build();
        final MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017), new ServerAddress("localhost", 27018)),
                Arrays.asList(credential), o);

        mongoClient.slaveOk();
        MongoDatabase database = mongoClient.getDatabase("testDB");

        final MongoCollection<Document> coll = database.getCollection("testCollection");

        Document doc = new Document("test Document timestamp ", new Date().toString());

        coll.insertOne(doc);

        FindIterable<Document> itr = coll.find();
        int counter = 1;

        for (Document docu : itr) {
            System.out.println("Document number " + counter);
            System.out.println(docu.toString());
            counter++;
        }
</code>```

Anything went well before adding the ssl options. I also create the keystore just as instructed in the mongoDB website:

```<code>%JAVA_HOME%\bin\keytool -importcert -trustcacerts -file D:\mongoDBFiles\mongodb.crt -keystore mongoKeyStore -storepass password
</code>```

And the VM arguments:

```<code>-Djavax.net.ssl.trustStore=mongoKeyStore -Djavax.net.ssl.trustStorePassword=password
</code>```

And finally the error stack trace:

```<code>16:45:31.760 [main] INFO  org.mongodb.driver.cluster - Cluster created with settings {hosts=[localhost:27017, localhost:27018], mode=MULTIPLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
16:45:31.762 [main] INFO  org.mongodb.driver.cluster - Adding discovered server localhost:27017 to client view of cluster
16:45:31.795 [main] INFO  org.mongodb.driver.cluster - Adding discovered server localhost:27018 to client view of cluster
16:45:31.796 [main] DEBUG org.mongodb.driver.cluster - Updating cluster description to  {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING}, {address=localhost:27018, type=UNKNOWN, state=CONNECTING}]
16:45:31.814 [main] INFO  org.mongodb.driver.cluster - No server chosen by PrimaryServerSelector from cluster description ClusterDescription{type=UNKNOWN, connectionMode=MULTIPLE, all=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING}, ServerDescription{address=localhost:27018, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
16:45:31.889 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27018] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:2}
16:45:31.889 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27017] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:1}
16:45:31.889 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27018] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:2}
16:45:31.889 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27017] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:1}
16:45:31.894 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27018] INFO  org.mongodb.driver.cluster - Exception in monitor thread while connecting to server localhost:27018
com.mongodb.MongoSocketWriteException: Exception sending message
at     com.mongodb.connection.InternalStreamConnection.translateWriteException(InternalStreamConnection.java:461) ~[mongo-java-driver-3.0.0.jar:na]
at   com.mongodb.connection.InternalStreamConnection.sendMessage(InternalStreamConnection.java:204) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.CommandHelper.sendMessage(CommandHelper.java:89) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32) ~[mongo-java-driver-3.0.0.jar:na]
at     com.mongodb.connection.InternalStreamConnectionInitializer.initializeConnectionDescription(InternalStreamConnectionInitializer.java:83) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:43) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:127) ~[mongo-java-driver-3.0.0.jar:na]
at java.lang.Thread.run(Thread.java:722) [na:1.7.0_03]
Caused by: javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
at sun.security.ssl.Alerts.getSSLException(Alerts.java:208) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1868) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1826) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1809) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1735) ~[na:1.7.0_03]
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:116) ~[na:1.7.0_03]
at com.mongodb.connection.SocketStream.write(SocketStream.java:75) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.InternalStreamConnection.sendMessage(InternalStreamConnection.java:200) ~[mongo-java-driver-3.0.0.jar:na]
... 7 common frames omitted
Caused by: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
at sun.security.validator.PKIXValidator.<init>(PKIXValidator.java:90) ~[na:1.7.0_03]
at sun.security.validator.Validator.getInstance(Validator.java:179) ~[na:1.7.0_03]
at sun.security.ssl.X509TrustManagerImpl.getValidator(X509TrustManagerImpl.java:314) ~[na:1.7.0_03]
at sun.security.ssl.X509TrustManagerImpl.checkTrustedInit(X509TrustManagerImpl.java:173) ~[na:1.7.0_03]
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:186) ~[na:1.7.0_03]
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126) ~[na:1.7.0_03]
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1319) ~[na:1.7.0_03]
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:154) ~[na:1.7.0_03]
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868) ~[na:1.7.0_03]
at sun.security.ssl.Handshaker.process_record(Handshaker.java:804) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:998) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1294) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:685) ~[na:1.7.0_03]
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:111) ~[na:1.7.0_03]
... 9 common frames omitted
Caused by: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
at java.security.cert.PKIXParameters.setTrustAnchors(PKIXParameters.java:200) ~[na:1.7.0_03]
at java.security.cert.PKIXParameters.<init>(PKIXParameters.java:120) ~[na:1.7.0_03]
at java.security.cert.PKIXBuilderParameters.<init>(PKIXBuilderParameters.java:104) ~[na:1.7.0_03]
at sun.security.validator.PKIXValidator.<init>(PKIXValidator.java:88) ~[na:1.7.0_03]
... 22 common frames omitted
16:45:31.894 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27017] INFO  org.mongodb.driver.cluster - Exception in monitor thread while connecting to server localhost:27017
com.mongodb.MongoSocketWriteException: Exception sending message
at   com.mongodb.connection.InternalStreamConnection.translateWriteException(InternalStreamConnection.java:461) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.InternalStreamConnection.sendMessage(InternalStreamConnection.java:204) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.CommandHelper.sendMessage(CommandHelper.java:89) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.InternalStreamConnectionInitializer.initializeConnectionDescription(InternalStreamConnectionInitializer.java:83) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:43) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:127) ~[mongo-java-driver-3.0.0.jar:na]
at java.lang.Thread.run(Thread.java:722) [na:1.7.0_03]
Caused by: javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
at sun.security.ssl.Alerts.getSSLException(Alerts.java:208) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1868) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1826) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1809) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1735) ~[na:1.7.0_03]
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:116) ~[na:1.7.0_03]
at com.mongodb.connection.SocketStream.write(SocketStream.java:75) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.InternalStreamConnection.sendMessage(InternalStreamConnection.java:200) ~[mongo-java-driver-3.0.0.jar:na]
... 7 common frames omitted
Caused by: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
at sun.security.validator.PKIXValidator.<init>(PKIXValidator.java:90) ~[na:1.7.0_03]
at sun.security.validator.Validator.getInstance(Validator.java:179) ~[na:1.7.0_03]
at sun.security.ssl.X509TrustManagerImpl.getValidator(X509TrustManagerImpl.java:314) ~[na:1.7.0_03]
at sun.security.ssl.X509TrustManagerImpl.checkTrustedInit(X509TrustManagerImpl.java:173) ~[na:1.7.0_03]
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:186) ~[na:1.7.0_03]
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126) ~[na:1.7.0_03]
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1319) ~[na:1.7.0_03]
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:154) ~[na:1.7.0_03]
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868) ~[na:1.7.0_03]
at sun.security.ssl.Handshaker.process_record(Handshaker.java:804) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:998) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1294) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:685) ~[na:1.7.0_03]
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:111) ~[na:1.7.0_03]
... 9 common frames omitted
Caused by: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
at java.security.cert.PKIXParameters.setTrustAnchors(PKIXParameters.java:200) ~[na:1.7.0_03]
at java.security.cert.PKIXParameters.<init>(PKIXParameters.java:120) ~[na:1.7.0_03]
at java.security.cert.PKIXBuilderParameters.<init>(PKIXBuilderParameters.java:104) ~[na:1.7.0_03]
at sun.security.validator.PKIXValidator.<init>(PKIXValidator.java:88) ~[na:1.7.0_03]
... 22 common frames omitted
16:45:31.895 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27018] DEBUG org.mongodb.driver.cluster - Updating cluster description to  {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING}, {address=localhost:27018, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketWriteException: Exception sending message}, caused by {javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty}, caused by {java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty}, caused by {java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty}}]
16:45:31.895 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27017] DEBUG org.mongodb.driver.cluster - Updating cluster description to  {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketWriteException: Exception sending message}, caused by {javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty}, caused by {java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty}, caused by {java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty}}, {address=localhost:27018, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketWriteException: Exception sending message}, caused by {javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty}, caused by {java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty}, caused by {java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty}}]
16:45:32.402 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27018] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:3}
16:45:32.402 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27017] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:4}
16:45:32.402 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27018] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:3}
16:45:32.403 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27017] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:4}
16:45:32.911 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27017] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:6}
16:45:32.911 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27018] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:5}
</code>```

Thank you!

答:
There was the same problem with me when we were trying to connect mongo db with spark locally on spark.

Few things to check make sure your spark command is correct.
 i)spark-submit --master local[8] --class
--conf spark.executor.extraJavaOptions=-Djavax.net.ssl.trustStore=
--driver-java-options -Djavax.net.ssl.trustStore=

ii) also check the mongo configuration of the server i used below
net:
 bindIp: 0.0.0.0,localhost
 port: 27017
 ssl:
  mode: requireSSL
  PEMKeyFile: test-server1.pem
  disabledProtocols: TLS1_0,TLS1_1

Issue for us was that we were using CAFile: /etc/ssl/caToValidateClientCertificates.pem property in mongo file . So the CA certificate of java trust store was not matching with the java one.

Make sure also if CA certs are matching . if not then remove the line of CAFile:  from mongo .

At mongo server end it was giving error like this  SSL: error:14094438:SSL routines:ssl3_read_bytes:tlsv1 alert internal error

Body:
I'm using mongo to create SSL connection between the java client and a mongo replica set. It worked fine with mongo shell so I assume I have done something wrong with java. There is already a thread that is similar to this but it didn't help.
Here is my configuration:

Starting two mongod:

mongod --keyFile D:\mongoDBFiles\mongokey --sslMode requireSSL --sslPEMKeyFile D:\mongoDBFiles\mongodb.pem --port 27017 --dbpath D:\mongoDBFiles\node1 --replSet foo --smallfiles --oplogSize 128
mongod --keyFile D:\mongoDBFiles\mongokey --sslMode requireSSL --sslPEMKeyFile D:\mongoDBFiles\mongodb.pem --port 27018 --dbpath D:\mongoDBFiles\node2 --replSet foo --smallfiles --oplogSize 128

If I just use mongo shell it would work well like this:

mongo --ssl --sslCAFile D:\mongoDBFiles\mongodb.pem --sslPEMKeyFile D:\mongoDBFiles\mongoclient.pem --sslPEMKeyPassword password

However it doesn't work with java driver:

        final MongoCredential credential = MongoCredential.createCredential("admin", "admin", "password".toCharArray());
        final MongoClientOptions o = new MongoClientOptions.Builder().socketFactory(SSLSocketFactory.getDefault()).build();
        final MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017), new ServerAddress("localhost", 27018)),
                Arrays.asList(credential), o);

        mongoClient.slaveOk();
        MongoDatabase database = mongoClient.getDatabase("testDB");

        final MongoCollection<Document> coll = database.getCollection("testCollection");

        Document doc = new Document("test Document timestamp ", new Date().toString());

        coll.insertOne(doc);

        FindIterable<Document> itr = coll.find();
        int counter = 1;

        for (Document docu : itr) {
            System.out.println("Document number " + counter);
            System.out.println(docu.toString());
            counter++;
        }

Anything went well before adding the ssl options. I also create the keystore just as instructed in the mongoDB website:

%JAVA_HOME%\bin\keytool -importcert -trustcacerts -file D:\mongoDBFiles\mongodb.crt -keystore mongoKeyStore -storepass password

And the VM arguments:

-Djavax.net.ssl.trustStore=mongoKeyStore -Djavax.net.ssl.trustStorePassword=password

And finally the error stack trace:

16:45:31.760 [main] INFO  org.mongodb.driver.cluster - Cluster created with settings {hosts=[localhost:27017, localhost:27018], mode=MULTIPLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
16:45:31.762 [main] INFO  org.mongodb.driver.cluster - Adding discovered server localhost:27017 to client view of cluster
16:45:31.795 [main] INFO  org.mongodb.driver.cluster - Adding discovered server localhost:27018 to client view of cluster
16:45:31.796 [main] DEBUG org.mongodb.driver.cluster - Updating cluster description to  {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING}, {address=localhost:27018, type=UNKNOWN, state=CONNECTING}]
16:45:31.814 [main] INFO  org.mongodb.driver.cluster - No server chosen by PrimaryServerSelector from cluster description ClusterDescription{type=UNKNOWN, connectionMode=MULTIPLE, all=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING}, ServerDescription{address=localhost:27018, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
16:45:31.889 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27018] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:2}
16:45:31.889 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27017] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:1}
16:45:31.889 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27018] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:2}
16:45:31.889 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27017] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:1}
16:45:31.894 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27018] INFO  org.mongodb.driver.cluster - Exception in monitor thread while connecting to server localhost:27018
com.mongodb.MongoSocketWriteException: Exception sending message
at     com.mongodb.connection.InternalStreamConnection.translateWriteException(InternalStreamConnection.java:461) ~[mongo-java-driver-3.0.0.jar:na]
at   com.mongodb.connection.InternalStreamConnection.sendMessage(InternalStreamConnection.java:204) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.CommandHelper.sendMessage(CommandHelper.java:89) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32) ~[mongo-java-driver-3.0.0.jar:na]
at     com.mongodb.connection.InternalStreamConnectionInitializer.initializeConnectionDescription(InternalStreamConnectionInitializer.java:83) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:43) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:127) ~[mongo-java-driver-3.0.0.jar:na]
at java.lang.Thread.run(Thread.java:722) [na:1.7.0_03]
Caused by: javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
at sun.security.ssl.Alerts.getSSLException(Alerts.java:208) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1868) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1826) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1809) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1735) ~[na:1.7.0_03]
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:116) ~[na:1.7.0_03]
at com.mongodb.connection.SocketStream.write(SocketStream.java:75) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.InternalStreamConnection.sendMessage(InternalStreamConnection.java:200) ~[mongo-java-driver-3.0.0.jar:na]
... 7 common frames omitted
Caused by: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
at sun.security.validator.PKIXValidator.<init>(PKIXValidator.java:90) ~[na:1.7.0_03]
at sun.security.validator.Validator.getInstance(Validator.java:179) ~[na:1.7.0_03]
at sun.security.ssl.X509TrustManagerImpl.getValidator(X509TrustManagerImpl.java:314) ~[na:1.7.0_03]
at sun.security.ssl.X509TrustManagerImpl.checkTrustedInit(X509TrustManagerImpl.java:173) ~[na:1.7.0_03]
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:186) ~[na:1.7.0_03]
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126) ~[na:1.7.0_03]
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1319) ~[na:1.7.0_03]
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:154) ~[na:1.7.0_03]
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868) ~[na:1.7.0_03]
at sun.security.ssl.Handshaker.process_record(Handshaker.java:804) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:998) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1294) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:685) ~[na:1.7.0_03]
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:111) ~[na:1.7.0_03]
... 9 common frames omitted
Caused by: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
at java.security.cert.PKIXParameters.setTrustAnchors(PKIXParameters.java:200) ~[na:1.7.0_03]
at java.security.cert.PKIXParameters.<init>(PKIXParameters.java:120) ~[na:1.7.0_03]
at java.security.cert.PKIXBuilderParameters.<init>(PKIXBuilderParameters.java:104) ~[na:1.7.0_03]
at sun.security.validator.PKIXValidator.<init>(PKIXValidator.java:88) ~[na:1.7.0_03]
... 22 common frames omitted
16:45:31.894 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27017] INFO  org.mongodb.driver.cluster - Exception in monitor thread while connecting to server localhost:27017
com.mongodb.MongoSocketWriteException: Exception sending message
at   com.mongodb.connection.InternalStreamConnection.translateWriteException(InternalStreamConnection.java:461) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.InternalStreamConnection.sendMessage(InternalStreamConnection.java:204) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.CommandHelper.sendMessage(CommandHelper.java:89) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.InternalStreamConnectionInitializer.initializeConnectionDescription(InternalStreamConnectionInitializer.java:83) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:43) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:127) ~[mongo-java-driver-3.0.0.jar:na]
at java.lang.Thread.run(Thread.java:722) [na:1.7.0_03]
Caused by: javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
at sun.security.ssl.Alerts.getSSLException(Alerts.java:208) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1868) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1826) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1809) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1735) ~[na:1.7.0_03]
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:116) ~[na:1.7.0_03]
at com.mongodb.connection.SocketStream.write(SocketStream.java:75) ~[mongo-java-driver-3.0.0.jar:na]
at com.mongodb.connection.InternalStreamConnection.sendMessage(InternalStreamConnection.java:200) ~[mongo-java-driver-3.0.0.jar:na]
... 7 common frames omitted
Caused by: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
at sun.security.validator.PKIXValidator.<init>(PKIXValidator.java:90) ~[na:1.7.0_03]
at sun.security.validator.Validator.getInstance(Validator.java:179) ~[na:1.7.0_03]
at sun.security.ssl.X509TrustManagerImpl.getValidator(X509TrustManagerImpl.java:314) ~[na:1.7.0_03]
at sun.security.ssl.X509TrustManagerImpl.checkTrustedInit(X509TrustManagerImpl.java:173) ~[na:1.7.0_03]
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:186) ~[na:1.7.0_03]
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126) ~[na:1.7.0_03]
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1319) ~[na:1.7.0_03]
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:154) ~[na:1.7.0_03]
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868) ~[na:1.7.0_03]
at sun.security.ssl.Handshaker.process_record(Handshaker.java:804) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:998) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1294) ~[na:1.7.0_03]
at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:685) ~[na:1.7.0_03]
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:111) ~[na:1.7.0_03]
... 9 common frames omitted
Caused by: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
at java.security.cert.PKIXParameters.setTrustAnchors(PKIXParameters.java:200) ~[na:1.7.0_03]
at java.security.cert.PKIXParameters.<init>(PKIXParameters.java:120) ~[na:1.7.0_03]
at java.security.cert.PKIXBuilderParameters.<init>(PKIXBuilderParameters.java:104) ~[na:1.7.0_03]
at sun.security.validator.PKIXValidator.<init>(PKIXValidator.java:88) ~[na:1.7.0_03]
... 22 common frames omitted
16:45:31.895 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27018] DEBUG org.mongodb.driver.cluster - Updating cluster description to  {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING}, {address=localhost:27018, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketWriteException: Exception sending message}, caused by {javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty}, caused by {java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty}, caused by {java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty}}]
16:45:31.895 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27017] DEBUG org.mongodb.driver.cluster - Updating cluster description to  {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketWriteException: Exception sending message}, caused by {javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty}, caused by {java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty}, caused by {java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty}}, {address=localhost:27018, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketWriteException: Exception sending message}, caused by {javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty}, caused by {java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty}, caused by {java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty}}]
16:45:32.402 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27018] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:3}
16:45:32.402 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27017] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:4}
16:45:32.402 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27018] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:3}
16:45:32.403 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27017] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:4}
16:45:32.911 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27017] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:6}
16:45:32.911 [cluster-ClusterId{value='5527e20bdea3b318ecf76f4e', description='null'}-localhost:27018] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:5}

Thank you!


来源: stackexchange

问:
Will go get command update the package in my local machine
Suppose I download a package using go get <Import path of package>. Now after x number of days that package has been updated remotely and now if I run again go get <Import path of package> will it be updated on my local too?

答:
The go get <Import path of package> command will not update the local copy if there is already a local copy installed.

The go get documentation says:

The -u flag instructs get to use the network to update the named packages and their dependencies. By default, get uses the network to check out missing packages but does not use it to look for updates to existing packages.

Run go get -u <Import path of package> to get or update the local copy.

ContentLicense: CC BY-SA 4.0


问:
Serial communication from JavaScript?
Is it possible to communicate over a machine's serial port through JavaScript?

I have to write a short program that sends data to a microcontroller over the serial port that has a GUI and is cross-platform compatible, and I really don't want to use Java's Swing.

答:
JavaScript itself doesn't have any built in functionality to allow you to access the serial port. However, various JavaScript engines (v8, rhino, etc) allow you to write your own custom native objects.

You might want to check out node.js, which is a JavaScript library for v8 that's focused on writing server-side code (rather than web browser client code). It seems that someone's already written a serialport package for that:

https://github.com/voodootikigod/node-serialport

ContentLicense: CC BY-SA 3.0

Title: Serial communication from JavaScript?


问:
How to start an animation loop in Tkinter for an event?
I wrote some code using Tkinter in Python 3 that plots a graph in a canvas. I also made it such that when I move the mouse over the canvas the graph scrolls to the left.

The problem is that I want the graph to scroll when I press the space bar for example. But I don't want it to scroll 1 step each time I press the space bar but I want it to start scrolling indefinitely when I press it once and stop the scroll when I press it again. I want the space bar to be a play/pause key.

How can I accomplish this? I don't want to use matplotlib anywhere.

MY CODE AS IT IS NOW:

```<code>from tkinter import *
import numpy as np

# The function of the graph
def f(x):
    return np.sin(x)+np.sin(3*x-1)+np.sin(0.5*(x+np.pi))+0.3*np.sin(10*x)

class GraphPlot():
    def __init__(self, master):
        self.master = master

        # Data for the graph and steps to move to the right
        self.data_x = np.linspace(0, 4*np.pi, 1000)
        self.data_y = f(self.data_x)
        self.step = 0.1

        # A switch to delete to clear the canvas each iteration before plotting the next frame
        self.gate = False

        # Setting the Tkinter window and the canvas in place
        self.ws = master.winfo_screenwidth()
        self.hs = master.winfo_screenheight()
        ww = self.ws*0.75
        hw = self.hs*0.50
        self.canvas = Canvas(self.master, width = ww, height = hw, bg = 'black')
        self.canvas.grid()
        self.master.update()
        self.w = self.canvas.winfo_width()
        self.h = self.canvas.winfo_height()
        self.canvas.focus_set()

        # Plot first frame
        self.drawData(self.data_x, self.data_y)

        # Plot next frames each time I press the space bar
        self.canvas.bind('<KeyPress-space>', self.updateData)

    def drawData(self, data_x, data_y):
        '''This is my function to plot a grpah in a canvas
        canvas without embedding any matplotlib figure'''

        # Setting the axis limits
        x_min, x_max = min(data_x), max(data_x)
        y_min, y_max = min(data_y), max(data_y)

        # Translating data to pixel positions inside the canvas
        pixel_x = (data_x-x_min)*self.w/(x_max-x_min)
        pixel_y = -(data_y-y_max)*self.h/(y_max-y_min)
        points = []
        for i in range(len(data_x)):
            points.append(pixel_x[i])
            points.append(pixel_y[i])
        points = tuple(points)

        # Deleting previous frame before plotting the next frame (except for the first frame)
        if self.gate:
            self.canvas.delete('curve')
        else:
            self.gate = True

        # Plotting
        self.canvas.create_line(points, fill = 'white', tag = 'curve')

    def updateData(self, event):
        # Changing data for the next frame
        self.data_x += self.step
        self.data_y = f(self.data_x)

        # Plot new frame
        self.drawData(self.data_x, self.data_y)

root = Tk()
GraphPlot(root)
root.mainloop()
</code>```

I've tried some ideas. For example I used a new function, PlayPause(), with a  while loop and a new switch, self.go, but this didn't work as expected.

CODE THAT I EXPECTED TO WORK BUT DIDN'T:

```<code>from tkinter import *
import numpy as np

def f(x):
    return np.sin(x)+np.sin(3*x-1)+np.sin(0.5*(x+np.pi))+0.3*np.sin(10*x)

class GraphPlot():
    def __init__(self, master):
        self.master = master
        self.data_x = np.linspace(0, 4*np.pi, 1000)
        self.data_y = f(self.data_x)
        self.step = 0.1
        self.go = False # The new switch
        self.gate = False
        self.ws = master.winfo_screenwidth()
        self.hs = master.winfo_screenheight()
        ww = self.ws*0.75
        hw = self.hs*0.50
        self.canvas = Canvas(self.master, width = ww, height = hw, bg = 'black')
        self.canvas.grid()
        self.master.update()
        self.w = self.canvas.winfo_width()
        self.h = self.canvas.winfo_height()
        self.canvas.focus_set()
        self.drawData(self.data_x, self.data_y)
        self.canvas.bind('<KeyPress-space>', self.PlayPause)

    def drawData(self, data_x, data_y):
        x_min, x_max = min(data_x), max(data_x)
        y_min, y_max = min(data_y), max(data_y)
        pixel_x = (data_x-x_min)*self.w/(x_max-x_min)
        pixel_y = -(data_y-y_max)*self.h/(y_max-y_min)
        points = []
        for i in range(len(data_x)):
            points.append(pixel_x[i])
            points.append(pixel_y[i])
        points = tuple(points)
        if self.gate:
            self.canvas.delete('curve')
        else:
            self.gate = True
        self.canvas.create_line(points, fill = 'white', tag = 'curve')

    def updateData(self):
        self.data_x += self.step
        self.data_y = f(self.data_x)
        self.drawData(self.data_x, self.data_y)

    def PlayPause(self, event):
        if self.go:
            self.go = False
        else:
            self.go = True
        while self.go:
            self.updateData()

root = Tk()
GraphPlot(root)
root.mainloop()
</code>```

答:
You could add a method to toggle_play_pause, and bind the space key to it. Upon space key press, this method toggles a boolean flag pause that when turned off allows the update to be called.

update will keep calling itself every 10/1000 of a second, until the space key is pressed again, and the pause flag set to True.

```<code>import tkinter as tk
import numpy as np

def f(x):
    return np.sin(x)+np.sin(3*x-1)+np.sin(0.5*(x+np.pi))+0.3*np.sin(10*x)

class GraphPlot():
    def __init__(self, master):
        self.master = master

        # Data for the graph and steps to move to the right
        self.data_x = np.linspace(0, 4*np.pi, 1000)
        self.data_y = f(self.data_x)
        self.step = 0.1

        # A switch to delete to clear the canvas each iteration before plotting the next frame
        self.gate = False

        # Setting the Tkinter window and the canvas in place
        self.ws = master.winfo_screenwidth()
        self.hs = master.winfo_screenheight()
        ww = self.ws * 0.75
        hw = self.hs * 0.50
        self.canvas = tk.Canvas(self.master, width=ww, height=hw, bg='black')
        self.canvas.grid()
        self.master.update()
        self.w = self.canvas.winfo_width()
        self.h = self.canvas.winfo_height()
        self.canvas.focus_set()

        # Plot first frame
        self.drawData(self.data_x, self.data_y)

        # Plot next frames each time I press the space bar
        self.canvas.bind('<KeyPress-space>', self.toggle_play_pause)

        self.pause = True
        self._update_call_handle = None

    def drawData(self, data_x, data_y):
        '''This is my function to plot a grpah in a canvas
        canvas without embedding any matplotlib figure'''

        # Setting the axis limits
        x_min, x_max = min(data_x), max(data_x)
        y_min, y_max = min(data_y), max(data_y)

        # Translating data to pixel positions inside the canvas
        pixel_x = (data_x-x_min)*self.w/(x_max-x_min)
        pixel_y = -(data_y-y_max)*self.h/(y_max-y_min)
        points = []
        for i in range(len(data_x)):
            points.append(pixel_x[i])
            points.append(pixel_y[i])
        points = tuple(points)

        # Deleting previous frame before plotting the next frame (except for the first frame)
        if self.gate:
            self.canvas.delete('curve')
        else:
            self.gate = True

        # Plotting
        self.canvas.create_line(points, fill = 'white', tag = 'curve')

    def toggle_play_pause(self, dummy_event):
        self.pause = not self.pause
        if not self.pause:
            self.updateData()

    def updateData(self):
        # Changing data for the next frame
        self.data_x += self.step
        self.data_y = f(self.data_x)

        # Plot new frame
        self.drawData(self.data_x, self.data_y)
        if not self.pause:
            self._update_call_handle = root.after(10, self.updateData)
        else:
            root.after_cancel(self._update_call_handle)
            self._update_call_handle = None

root = tk.Tk()
GraphPlot(root)
root.mainloop()
</code>```

Body:
I wrote some code using Tkinter in Python 3 that plots a graph in a canvas. I also made it such that when I move the mouse over the canvas the graph scrolls to the left.

The problem is that I want the graph to scroll when I press the space bar for example. But I don't want it to scroll 1 step each time I press the space bar but I want it to start scrolling indefinitely when I press it once and stop the scroll when I press it again. I want the space bar to be a play/pause key.

How can I accomplish this? I don't want to use matplotlib anywhere.

MY CODE AS IT IS NOW:

from tkinter import *
import numpy as np

# The function of the graph
def f(x):
    return np.sin(x)+np.sin(3*x-1)+np.sin(0.5*(x+np.pi))+0.3*np.sin(10*x)

class GraphPlot():
    def __init__(self, master):
        self.master = master

        # Data for the graph and steps to move to the right
        self.data_x = np.linspace(0, 4*np.pi, 1000)
        self.data_y = f(self.data_x)
        self.step = 0.1

        # A switch to delete to clear the canvas each iteration before plotting the next frame
        self.gate = False

        # Setting the Tkinter window and the canvas in place
        self.ws = master.winfo_screenwidth()
        self.hs = master.winfo_screenheight()
        ww = self.ws*0.75
        hw = self.hs*0.50
        self.canvas = Canvas(self.master, width = ww, height = hw, bg = 'black')
        self.canvas.grid()
        self.master.update()
        self.w = self.canvas.winfo_width()
        self.h = self.canvas.winfo_height()
        self.canvas.focus_set()

        # Plot first frame
        self.drawData(self.data_x, self.data_y)

        # Plot next frames each time I press the space bar
        self.canvas.bind('<KeyPress-space>', self.updateData)

    def drawData(self, data_x, data_y):
        '''This is my function to plot a grpah in a canvas
        canvas without embedding any matplotlib figure'''

        # Setting the axis limits
        x_min, x_max = min(data_x), max(data_x)
        y_min, y_max = min(data_y), max(data_y)

        # Translating data to pixel positions inside the canvas
        pixel_x = (data_x-x_min)*self.w/(x_max-x_min)
        pixel_y = -(data_y-y_max)*self.h/(y_max-y_min)
        points = []
        for i in range(len(data_x)):
            points.append(pixel_x[i])
            points.append(pixel_y[i])
        points = tuple(points)

        # Deleting previous frame before plotting the next frame (except for the first frame)
        if self.gate:
            self.canvas.delete('curve')
        else:
            self.gate = True

        # Plotting
        self.canvas.create_line(points, fill = 'white', tag = 'curve')

    def updateData(self, event):
        # Changing data for the next frame
        self.data_x += self.step
        self.data_y = f(self.data_x)

        # Plot new frame
        self.drawData(self.data_x, self.data_y)

root = Tk()
GraphPlot(root)
root.mainloop()

I've tried some ideas. For example I used a new function, PlayPause(), with a  while loop and a new switch, self.go, but this didn't work as expected.

CODE THAT I EXPECTED TO WORK BUT DIDN'T:

from tkinter import *
import numpy as np

def f(x):
    return np.sin(x)+np.sin(3*x-1)+np.sin(0.5*(x+np.pi))+0.3*np.sin(10*x)

class GraphPlot():
    def __init__(self, master):
        self.master = master
        self.data_x = np.linspace(0, 4*np.pi, 1000)
        self.data_y = f(self.data_x)
        self.step = 0.1
        self.go = False # The new switch
        self.gate = False
        self.ws = master.winfo_screenwidth()
        self.hs = master.winfo_screenheight()
        ww = self.ws*0.75
        hw = self.hs*0.50
        self.canvas = Canvas(self.master, width = ww, height = hw, bg = 'black')
        self.canvas.grid()
        self.master.update()
        self.w = self.canvas.winfo_width()
        self.h = self.canvas.winfo_height()
        self.canvas.focus_set()
        self.drawData(self.data_x, self.data_y)
        self.canvas.bind('<KeyPress-space>', self.PlayPause)

    def drawData(self, data_x, data_y):
        x_min, x_max = min(data_x), max(data_x)
        y_min, y_max = min(data_y), max(data_y)
        pixel_x = (data_x-x_min)*self.w/(x_max-x_min)
        pixel_y = -(data_y-y_max)*self.h/(y_max-y_min)
        points = []
        for i in range(len(data_x)):
            points.append(pixel_x[i])
            points.append(pixel_y[i])
        points = tuple(points)
        if self.gate:
            self.canvas.delete('curve')
        else:
            self.gate = True
        self.canvas.create_line(points, fill = 'white', tag = 'curve')

    def updateData(self):
        self.data_x += self.step
        self.data_y = f(self.data_x)
        self.drawData(self.data_x, self.data_y)

    def PlayPause(self, event):
        if self.go:
            self.go = False
        else:
            self.go = True
        while self.go:
            self.updateData()

root = Tk()
GraphPlot(root)
root.mainloop()

Body:
You could add a method to toggle_play_pause, and bind the space key to it. Upon space key press, this method toggles a boolean flag pause that when turned off allows the update to be called.

update will keep calling itself every 10/1000 of a second, until the space key is pressed again, and the pause flag set to True.

import tkinter as tk
import numpy as np

def f(x):
    return np.sin(x)+np.sin(3*x-1)+np.sin(0.5*(x+np.pi))+0.3*np.sin(10*x)

class GraphPlot():
    def __init__(self, master):
        self.master = master

        # Data for the graph and steps to move to the right
        self.data_x = np.linspace(0, 4*np.pi, 1000)
        self.data_y = f(self.data_x)
        self.step = 0.1

        # A switch to delete to clear the canvas each iteration before plotting the next frame
        self.gate = False

        # Setting the Tkinter window and the canvas in place
        self.ws = master.winfo_screenwidth()
        self.hs = master.winfo_screenheight()
        ww = self.ws * 0.75
        hw = self.hs * 0.50
        self.canvas = tk.Canvas(self.master, width=ww, height=hw, bg='black')
        self.canvas.grid()
        self.master.update()
        self.w = self.canvas.winfo_width()
        self.h = self.canvas.winfo_height()
        self.canvas.focus_set()

        # Plot first frame
        self.drawData(self.data_x, self.data_y)

        # Plot next frames each time I press the space bar
        self.canvas.bind('<KeyPress-space>', self.toggle_play_pause)

        self.pause = True
        self._update_call_handle = None

    def drawData(self, data_x, data_y):
        '''This is my function to plot a grpah in a canvas
        canvas without embedding any matplotlib figure'''

        # Setting the axis limits
        x_min, x_max = min(data_x), max(data_x)
        y_min, y_max = min(data_y), max(data_y)

        # Translating data to pixel positions inside the canvas
        pixel_x = (data_x-x_min)*self.w/(x_max-x_min)
        pixel_y = -(data_y-y_max)*self.h/(y_max-y_min)
        points = []
        for i in range(len(data_x)):
            points.append(pixel_x[i])
            points.append(pixel_y[i])
        points = tuple(points)

        # Deleting previous frame before plotting the next frame (except for the first frame)
        if self.gate:
            self.canvas.delete('curve')
        else:
            self.gate = True

        # Plotting
        self.canvas.create_line(points, fill = 'white', tag = 'curve')

    def toggle_play_pause(self, dummy_event):
        self.pause = not self.pause
        if not self.pause:
            self.updateData()

    def updateData(self):
        # Changing data for the next frame
        self.data_x += self.step
        self.data_y = f(self.data_x)

        # Plot new frame
        self.drawData(self.data_x, self.data_y)
        if not self.pause:
            self._update_call_handle = root.after(10, self.updateData)
        else:
            root.after_cancel(self._update_call_handle)
            self._update_call_handle = None

root = tk.Tk()
GraphPlot(root)
root.mainloop()


问:
Are all packages from package.json included in React build?
I created a react app that both server and client shares the same package.json:

```<code>├───build
│   └───static
│       ├───css
│       ├───js
│       └───media
├───server (backend code)
├───src (client code)
├───package.json (shared)
</code>```

My question is very simple, are all packages from package.json included in the final production React build?

For example, I use express for server. Is it included in the React build?

If so, is there any way to avoid it? Or did I choose a wrong architecture?

Edit:

Im using create-react-app, default mode

答:
No* (in the common case).

The most popular react build tooling will use webpack (or other bundlers which do similar things). Webpack receives some "entry point filepaths", from those entry points he crawls for dependencies. Then webpack packs everything into a single output file (or a set of files, depending on the settings).

If you didn't import express from any of your frontend files, it won't go into the bundle.

Body:
I created a react app that both server and client shares the same package.json:

├───build
│   └───static
│       ├───css
│       ├───js
│       └───media
├───server (backend code)
├───src (client code)
├───package.json (shared)

My question is very simple, are all packages from package.json included in the final production React build?

For example, I use express for server. Is it included in the React build?

If so, is there any way to avoid it? Or did I choose a wrong architecture?

Edit:

Im using create-react-app, default mode


问:
Laravel CRUD delete route parameters
Id' like to use a CRUD Controller to handle the admin profile. I created the Controller and edited my routes/web.php like this.

Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'as' => 'admin.', 'middleware' => ['auth:admin']], function(){
    Route::resource('profile', 'ProfileController')->only(['index', 'edit', 'update', 'destroy']);
});
```

<p>This creates the following routes.</p>

```admin/profile -> admin.profile.index
admin/profile/{profile} -> admin.profile.destroy
admin/profile/{profile} -> admin.profile.update
admin/profile/{profile}/edit -> admin.profile.edit
```

Since I get the admin_id through the session I don't need to get it through the URL via the profile parameter. I know that I could just ignore the parameter, but it makes the URL unnecessary long.
Is there a chance to delete the {profile} parameter from the routes, so that my routes are like teacher/profile/edit and not like teacher/profile/12345678/edit?

答:
Yes, you can remove the {profile} part if you call the profile needed first in the controller like such:

```<code>public function edit(){
    $teacher = Auth::user();
    return view('teacher.profile.edit', compact('teacher'));
}
</code>```

And inside the view page (teacher/profile/edit), you can call the data like such:

```<code><form method="post" action="{{ route('teacher.profile.update', $teacher->id) }}">
    @method('PATCH')
    @csrf
    ID: <input type="text" name="id" value={{ $teacher->id}} />
    <button type="submit">Update</button>
</form>
</code>```

I hope this help. Cheers!

Title: Laravel CRUD delete route parameters

Body:
Id' like to use a CRUD Controller to handle the admin profile. I created the Controller and edited my routes/web.php like this.

Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'as' => 'admin.', 'middleware' => ['auth:admin']], function(){
    Route::resource('profile', 'ProfileController')->only(['index', 'edit', 'update', 'destroy']);
});

This creates the following routes.

admin/profile -> admin.profile.index
admin/profile/{profile} -> admin.profile.destroy
admin/profile/{profile} -> admin.profile.update
admin/profile/{profile}/edit -> admin.profile.edit

Since I get the admin_id through the session I don't need to get it through the URL via the profile parameter. I know that I could just ignore the parameter, but it makes the URL unnecessary long.
Is there a chance to delete the {profile} parameter from the routes, so that my routes are like teacher/profile/edit and not like teacher/profile/12345678/edit?

Body:
Yes, you can remove the {profile} part if you call the profile needed first in the controller like such:

public function edit(){
    $teacher = Auth::user();
    return view('teacher.profile.edit', compact('teacher'));
}

And inside the view page (teacher/profile/edit), you can call the data like such:

<form method="post" action="{{ route('teacher.profile.update', $teacher->id) }}">
    @method('PATCH')
    @csrf
    ID: <input type="text" name="id" value={{ $teacher->id}} />
    <button type="submit">Update</button>
</form>

I hope this help. Cheers!


答:
No. According to the go get documentation it will not. If you want to update a local package you have to use the -u flag.

```<code>$ go help get

......
The -u flag instructs get to use the network to update the named packages
and their dependencies. By default, get uses the network to check out
missing packages but does not use it to look for updates to existing packages.
</code>```

Things change a bit if you use Go modules. Then the go.mod file is consulted, but by default it won't fetch the latest version automatically unless you tell it too. For this new behaviour please take a deeper look at the official docs https://github.com/golang/go/wiki/Modules#daily-workflow.

Title: Will go get command update the package in my local machine

Body: Suppose I download a package using go get <Import path of package>. Now after x number of days that package has been updated remotely and now if I run again go get <Import path of package> will it be updated on my local too?

Body:
No. According to the go get documentation it will not. If you want to update a local package you have to use the -u flag.

$ go help get

......
The -u flag instructs get to use the network to update the named packages
and their dependencies. By default, get uses the network to check out
missing packages but does not use it to look for updates to existing packages.

Things change a bit if you use Go modules. Then the go.mod file is consulted, but by default it won't fetch the latest version automatically unless you tell it too. For this new behaviour please take a deeper look at the official docs https://github.com/golang/go/wiki/Modules#daily-workflow.


问:
Adding a column in pandas DataFrame calculated from existing column and API call
Trying to add to my dataframe a column based on an existing column in the DataFrame and an API call, but getting an Error.

Here is my code:

```<code>from geopy.geocoders import Nominatim
geolocator = Nominatim()

# address is a String e.g. 'Berlin, Germany'
# addressdetails=True does the magic and gives you also the details

properties_no_na['latitude_zipcode'] = geolocator.geocode(properties_no_na['zip_code'] + ', NYC', addressdetails=True).latitude
properties_no_na['longitude_zipcode'] = geolocator.geocode(properties_no_na['zip_code'] + ', NYC', addressdetails=True).longitude
</code>```

When I try to execute this, it works and prints the latitude:

```<code>print(geolocator.geocode("brooklyn, NYC", addressdetails=True).latitude)
</code>```

How to apply this to all the rows of my dataframe?

PS:
1) zip_code is a string representing the zip_code of the house, and all rows are filled, no NaNs.
2) To install geopoy:

```<code>pip install geopy
</code>```

Here is a small portion of my df:

答:
I don't really know iiuc.
Did you try e.g. sth like</p>

```<code>properties_no_na['latitude_zipcode'] = properties_no_na['neighborhood'].apply(lambda x: geolocator.geocode(x + ', NYC', addressdetails=True).latitude)
</code>```

Body:
Trying to add to my dataframe a column based on an existing column in the DataFrame and an API call, but getting an Error.

Here is my code:

from geopy.geocoders import Nominatim
geolocator = Nominatim()

# address is a String e.g. 'Berlin, Germany'
# addressdetails=True does the magic and gives you also the details

properties_no_na['latitude_zipcode'] = geolocator.geocode(properties_no_na['zip_code'] + ', NYC', addressdetails=True).latitude
properties_no_na['longitude_zipcode'] = geolocator.geocode(properties_no_na['zip_code'] + ', NYC', addressdetails=True).longitude

When I try to execute this, it works and prints the latitude:

print(geolocator.geocode("brooklyn, NYC", addressdetails=True).latitude)

How to apply this to all the rows of my dataframe?

PS:
1) zip_code is a string representing the zip_code of the house, and all rows are filled, no NaNs.
2) To install geopoy:

pip install geopy

Here is a small portion of my df:

Body:
I don't really know iiuc.
Did you try e.g. sth like

properties_no_na['latitude_zipcode'] = properties_no_na['neighborhood'].apply(lambda x: geolocator.geocode(x + ', NYC', addressdetails=True).latitude)


问:
Rails 3 app server startup time is long
UPDATE 2 This is a known bug/feature with the way Ruby 1.9.2 loads files.  http://twitter.com/#!/rails/status/72801149769621504

update: This started out as a question, but after working on this for a bit I think it might not be fixable.  I figured I would post this in case anyone else is seeing the same thing and is wondering what is going on inside rails and bundler.

Is anyone else seeing long load times in their Rails 3 apps?  I placed timers in environment.rb, application.rb, boot.rb and railties/lib/rails/initializable.rb.  Time is measured in seconds and the elapsed time is the time since the last recorded time.  Production load time takes a bit longer.  Partly because of less hardware and also from eager_load! (and maybe from Thin vs Mongrel).  Looks like Bundler is taking up a big chunk of the load time and I guess that is to be expected.  I tested one of the apps in dev and prod, and one blank app in dev.  I tested 2 app servers just to see if it was Thin causing it.  I am also seeing similar things with Passenger in prod (which makes it unusable b/c of spawning behaviour in 2.2.15).  I tested against edge Rails and the performance in dev was slightly worse 14.5s vs 14.2s.  If I remove my testing dependencies it saves 2-3 seconds, but this does not help when I am running tests.  I guess it is just a bit annoying waiting 5 minutes for all my Thin instances to restart and also waiting 15 seconds before my tests run, but it is an acceptable tradeoff at this point because of productivity I gain with Rails 3.  If anyone has any ideas to help speed things up, I am all ears.  Here are the test results:

Note: my app in Rails 2.3 loaded in less than 3 seconds in dev (although I have converted a little bit of the code to engines and added haml and twitter_oauth gems since the move to rails3)

**All tests conducted with Rails 3RC and Ruby 1.9.2rc2

Prod with Thin - CentOS 5.5, Rackspace cloud server 2GB instance

Test App #1 with 24 gem dependencies

```
start env.rb - Total=0
  start app.rb - 0.00110546 elapsed.  Total=0.001180052
    start boot.rb - 0.000600488 elapsed.  Total=0.00178644
    end boot.rb - 0.7935529 elapsed.  Total=0.795507318
    start require rails/all - 0.000189127 elapsed.  Total=0.795701199
    end require rails/all - <b>1.086998364</b> elapsed.  Total=1.882735263
    start Bundler require - 0.000109708 elapsed.  Total=1.88285043
    end Bundler require - <b>8.955853243</b> elapsed.  Total=10.838746673
  end app.rb - 0.062975913 elapsed.  Total=10.901753753
  # /railties-3.0.0.rc/lib/rails/initializable.rb
  start run initializers - 0.000145906 elapsed.  Total=10.901910186
    load_environment_config - 0.116689774 elapsed.  Total=11.018632298
    initialize_cache - 0.246161343 elapsed.  Total=11.320543397
    active_record.initialize_database - 0.080047485 elapsed.  Total=11.400961893
    bootstrap_hook - 1.034189984 elapsed.  Total=12.451309104
    active_support.initialize_time_zone - 1.969821814 elapsed.  Total=14.448777651
    action_controller.set_configs - 0.594991537 elapsed.  Total=15.044692126
    will_paginate.active_record - 0.324460921 elapsed.  Total=15.386837641
    will_paginate.action_view - <b>1.904889132</b> elapsed.  Total=17.328981523
    add_view_paths - 0.087811847 elapsed.  Total=17.42011881
    load_init_rb - 0.151282681 elapsed.  Total=17.709093173
    load_init_rb - 0.362241273 elapsed.  Total=18.071865548
    load_config_initializers - 0.144051305 elapsed.  Total=18.217433492
    build_middleware_stack - <b>2.569453884</b> elapsed.  Total=20.826842081
    eager_load! - <b>4.165919064</b> elapsed.  Total=24.99280168
    finisher_hook - 0.48795935 elapsed.  Total=25.480807439
    repopulate_roles - 0.504085662 elapsed.  Total=25.984901297
  end run initializers - ~0.00005 elapsed.  Total=25.985617783
end env.rb - ~0.00006 elapsed.  Total=25.985683903
```

Dev with Mongrel - Max OSX 10.5.8, 2.66 Core2duo, 4GB RAM

Test App #1 with 24 gem dependencies

```
start boot.rb (Bundler.setup) - 2.0e-05 elapsed.  Total=3.1e-05
end boot.rb (Bundler.setup) - <b>2.352435</b> elapsed.  Total=2.352915
start app.rb - 0.084945 elapsed.  Total=2.437866
  start require rails/all - 0.000181 elapsed.  Total=2.438049
  end require rails/all - 0.489425 elapsed.  Total=2.927485
  start Bundler.require(:default, Rails.env) - 5.6e-05 elapsed.  Total=2.927544
  end Bundler.require(:default, Rails.env) - <b>5.16162</b> elapsed.  Total=8.089177
end app.rb - 0.025972 elapsed.  Total=8.11516
start env.rb - 0.084153 elapsed.  Total=8.199329
  # /railties-3.0.0.rc/lib/rails/initializable.rb
  start run_initializers - 0.002709 elapsed.  Total=8.202042
    initialize_cache - 0.089231 elapsed.  Total=8.518005
    bootstrap_hook - 0.602342 elapsed.  Total=9.192564
    active_support.initialize_time_zone - <b>0.901676</b> elapsed.  Total=10.10115
    action_controller.set_configs - 0.375864 elapsed.  Total=10.477565
    will_paginate.active_record - 0.207447 elapsed.  Total=10.694479
    will_paginate.action_view - <b>1.041412</b> elapsed.  Total=11.75974
    load_init_rb - 0.051938 elapsed.  Total=11.879547
    load_init_rb - 0.082936 elapsed.  Total=12.001311
    load_init_rb - 0.18798 elapsed.  Total=12.189555
    load_config_initializers - 0.079461 elapsed.  Total=12.269971
    build_middleware_stack - <b>1.390042</b> elapsed.  Total=13.729273
    finisher_hook - 0.082274 elapsed.  Total=13.811648
    repopulate_roles - 0.350287 elapsed.  Total=14.161941
  end run_initializers - 3.0e-06 elapsed.  Total=14.177869
end env.rb - 0.000127 elapsed.  Total=14.178002
```

Dev with Mongrel
Test App #2 with 2 gem dependencies

```
start boot.rb (Bundler.setup) - Total=0
end boot.rb (Bundler.setup) - <b>1.724158</b> elapsed.  Total=1.724199
start app.rb - 0.041006 elapsed.  Total=1.765211
  start require rails - 0.000151 elapsed.  Total=1.765364
  end require rails - 0.360051 elapsed.  Total=2.125426
  start Bundler.require(:default, Rails.env) - 5.5e-05 elapsed.  Total=2.125485
  end Bundler.require(:default, Rails.env) - 0.008396 elapsed.  Total=2.133889
end app.rb - 0.007805 elapsed.  Total=2.141704
start env.rb - 0.16541 elapsed.  Total=2.307128
  start run_initializers - 0.00031 elapsed.  Total=2.307442
    load_active_support - 0.24045 elapsed.  Total=2.579421
    active_support.initialize_time_zone - 0.206237 elapsed.  Total=2.837663
    action_controller.deprecated_routes - 0.210291 elapsed.  Total=3.048634
    build_middleware_stack - 0.220663 elapsed.  Total=3.273035
  end run_initializers - 3.0e-06 elapsed.  Total=3.29339
end env.rb - 8.7e-05 elapsed.  Total=3.293483
```

答: I have 3 rails 3  apps and i am migrating one from 2.3.8, the one on rails 2.3.8 loads in 4 seconds, and the branch that is halfway in rails 3 takes 12 seconds, all the other rails 3 projects take from 20 to 30 seconds to load, it is very depressing when i see a screencast where someone loads his rails app in 3 seconds, i have been pulling my hair ever since i migrated to rails 3 thinking it was my environment. </p>

Title: Rails 3 app server startup time is long

Body:
UPDATE 2 This is a known bug/feature with the way Ruby 1.9.2 loads files.  http://twitter.com/#!/rails/status/72801149769621504

update: This started out as a question, but after working on this for a bit I think it might not be fixable.  I figured I would post this in case anyone else is seeing the same thing and is wondering what is going on inside rails and bundler.

Is anyone else seeing long load times in their Rails 3 apps?  I placed timers in environment.rb, application.rb, boot.rb and railties/lib/rails/initializable.rb.  Time is measured in seconds and the elapsed time is the time since the last recorded time.  Production load time takes a bit longer.  Partly because of less hardware and also from eager_load! (and maybe from Thin vs Mongrel).  Looks like Bundler is taking up a big chunk of the load time and I guess that is to be expected.  I tested one of the apps in dev and prod, and one blank app in dev.  I tested 2 app servers just to see if it was Thin causing it.  I am also seeing similar things with Passenger in prod (which makes it unusable b/c of spawning behaviour in 2.2.15).  I tested against edge Rails and the performance in dev was slightly worse 14.5s vs 14.2s.  If I remove my testing dependencies it saves 2-3 seconds, but this does not help when I am running tests.  I guess it is just a bit annoying waiting 5 minutes for all my Thin instances to restart and also waiting 15 seconds before my tests run, but it is an acceptable tradeoff at this point because of productivity I gain with Rails 3.  If anyone has any ideas to help speed things up, I am all ears.  Here are the test results:

Note: my app in Rails 2.3 loaded in less than 3 seconds in dev (although I have converted a little bit of the code to engines and added haml and twitter_oauth gems since the move to rails3)

**All tests conducted with Rails 3RC and Ruby 1.9.2rc2

Prod with Thin - CentOS 5.5, Rackspace cloud server 2GB instance

Test App #1 with 24 gem dependencies

start env.rb - Total=0
  start app.rb - 0.00110546 elapsed.  Total=0.001180052
    start boot.rb - 0.000600488 elapsed.  Total=0.00178644
    end boot.rb - 0.7935529 elapsed.  Total=0.795507318
    start require rails/all - 0.000189127 elapsed.  Total=0.795701199
    end require rails/all - 1.086998364 elapsed.  Total=1.882735263
    start Bundler require - 0.000109708 elapsed.  Total=1.88285043
    end Bundler require - 8.955853243 elapsed.  Total=10.838746673
  end app.rb - 0.062975913 elapsed.  Total=10.901753753
  # /railties-3.0.0.rc/lib/rails/initializable.rb
  start run initializers - 0.000145906 elapsed.  Total=10.901910186
    load_environment_config - 0.116689774 elapsed.  Total=11.018632298
    initialize_cache - 0.246161343 elapsed.  Total=11.320543397
    active_record.initialize_database - 0.080047485 elapsed.  Total=11.400961893
    bootstrap_hook - 1.034189984 elapsed.  Total=12.451309104
    active_support.initialize_time_zone - 1.969821814 elapsed.  Total=14.448777651
    action_controller.set_configs - 0.594991537 elapsed.  Total=15.044692126
    will_paginate.active_record - 0.324460921 elapsed.  Total=15.386837641
    will_paginate.action_view - 1.904889132 elapsed.  Total=17.328981523
    add_view_paths - 0.087811847 elapsed.  Total=17.42011881
    load_init_rb - 0.151282681 elapsed.  Total=17.709093173
    load_init_rb - 0.362241273 elapsed.  Total=18.071865548
    load_config_initializers - 0.144051305 elapsed.  Total=18.217433492
    build_middleware_stack - 2.569453884 elapsed.  Total=20.826842081
    eager_load! - 4.165919064 elapsed.  Total=24.99280168
    finisher_hook - 0.48795935 elapsed.  Total=25.480807439
    repopulate_roles - 0.504085662 elapsed.  Total=25.984901297
  end run initializers - ~0.00005 elapsed.  Total=25.985617783
end env.rb - ~0.00006 elapsed.  Total=25.985683903

Dev with Mongrel - Max OSX 10.5.8, 2.66 Core2duo, 4GB RAM

Test App #1 with 24 gem dependencies

start boot.rb (Bundler.setup) - 2.0e-05 elapsed.  Total=3.1e-05
end boot.rb (Bundler.setup) - 2.352435 elapsed.  Total=2.352915
start app.rb - 0.084945 elapsed.  Total=2.437866
  start require rails/all - 0.000181 elapsed.  Total=2.438049
  end require rails/all - 0.489425 elapsed.  Total=2.927485
  start Bundler.require(:default, Rails.env) - 5.6e-05 elapsed.  Total=2.927544
  end Bundler.require(:default, Rails.env) - 5.16162 elapsed.  Total=8.089177
end app.rb - 0.025972 elapsed.  Total=8.11516
start env.rb - 0.084153 elapsed.  Total=8.199329
  # /railties-3.0.0.rc/lib/rails/initializable.rb
  start run_initializers - 0.002709 elapsed.  Total=8.202042
    initialize_cache - 0.089231 elapsed.  Total=8.518005
    bootstrap_hook - 0.602342 elapsed.  Total=9.192564
    active_support.initialize_time_zone - 0.901676 elapsed.  Total=10.10115
    action_controller.set_configs - 0.375864 elapsed.  Total=10.477565
    will_paginate.active_record - 0.207447 elapsed.  Total=10.694479
    will_paginate.action_view - 1.041412 elapsed.  Total=11.75974
    load_init_rb - 0.051938 elapsed.  Total=11.879547
    load_init_rb - 0.082936 elapsed.  Total=12.001311
    load_init_rb - 0.18798 elapsed.  Total=12.189555
    load_config_initializers - 0.079461 elapsed.  Total=12.269971
    build_middleware_stack - 1.390042 elapsed.  Total=13.729273
    finisher_hook - 0.082274 elapsed.  Total=13.811648
    repopulate_roles - 0.350287 elapsed.  Total=14.161941
  end run_initializers - 3.0e-06 elapsed.  Total=14.177869
end env.rb - 0.000127 elapsed.  Total=14.178002

Dev with Mongrel
Test App #2 with 2 gem dependencies

start boot.rb (Bundler.setup) - Total=0
end boot.rb (Bundler.setup) - 1.724158 elapsed.  Total=1.724199
start app.rb - 0.041006 elapsed.  Total=1.765211
  start require rails - 0.000151 elapsed.  Total=1.765364
  end require rails - 0.360051 elapsed.  Total=2.125426
  start Bundler.require(:default, Rails.env) - 5.5e-05 elapsed.  Total=2.125485
  end Bundler.require(:default, Rails.env) - 0.008396 elapsed.  Total=2.133889
end app.rb - 0.007805 elapsed.  Total=2.141704
start env.rb - 0.16541 elapsed.  Total=2.307128
  start run_initializers - 0.00031 elapsed.  Total=2.307442
    load_active_support - 0.24045 elapsed.  Total=2.579421
    active_support.initialize_time_zone - 0.206237 elapsed.  Total=2.837663
    action_controller.deprecated_routes - 0.210291 elapsed.  Total=3.048634
    build_middleware_stack - 0.220663 elapsed.  Total=3.273035
  end run_initializers - 3.0e-06 elapsed.  Total=3.29339
end env.rb - 8.7e-05 elapsed.  Total=3.293483


问:
How to save a modified array to a file
So I created an array which is saved in a file. I have the number 4 printed out 100 times in the file. Now everytime the an element in the array is accessed it the value will decrease by 1. So if A[1] = 4 is accessed then it will become A[1] = 3 and be saved on the file. The thing is I can't save the modified array to the file.

I already tried moving the placement of FILE pointer.

```<code>void buildingB4()
{
    system("CLS");
    FILE *input, *output;
    int i, B4[100], room;

    input = fopen("B4.txt", "r");
    if (input == NULL)
    {
        output = fopen("B4.txt", "w");
        for (i = 1; i <= 100; i++)
        {
            B4[i] = 4;
            fprintf(output, "%d\n", B4[i]);
        }
        fclose(output);
        for (i = 1; i <= 100; i++)
        {
            if (i % 10 == 0)
            {
                printf("\n\n");
            }
            printf("B-4-%d(%d)\t", i, B4[i]);
        }
    }
    else
    {

        for (i = 1; i <= 100; i++)
        {
            fscanf(input, "%d\n", &B4[i]);
            if (i % 10 == 0)
            {
                printf("\n\n");
            }
            printf("B-4-%d(%d)\t", i, B4[i]);
        }
        fclose(input);
        printf("\nPlease choose a room:B-4-");
        scanf("%d", &room);
        B4[room] = B4[room] - 1;
        output = fopen("B4.txt", "a");
        fprintf(output, "%d\n", B4[i]);
        studentDetails();
    }
}
</code>```

say if A[1] = 4
and when user input is 1, 1 is saved in a variable called room.
so A[room] = A[room] -1
so the result would be A[1] = 3 and it modify the A[1] saved in the file.

答:
I've found little mistakes in your code and here is your fixed code:

```<code>#define HOME_SIZE 100
void show_rooms(int B[]){
    for (int i = 0; i < HOME_SIZE; i++){
            if (i % 10 == 0){
                printf("\n\n");
            }
            printf("B-4-%3d(%d) ", i + 1, B[i]);
        }
}
void buildingB4()
{
    FILE *input, *output;
    input = fopen("B4.txt", "r");
    unsigned int B[HOME_SIZE], room;
    if (input == NULL){
        fclose(input);
        // Setting all homes to 4.
        for (int i = 0; i < HOME_SIZE; ++i){
            B[i] = 4;
        }
        output = fopen("B4.txt", "w");
        for(int i = 0; i < HOME_SIZE; ++i)
            fprintf(output, "%d\n", B[i]);
        fclose(output);
        show_rooms(B);
    }
    else{
        for (int i = 0; i < HOME_SIZE; ++i){
            fscanf(input, "%d", &B[i]);
        }
        fclose(input);
        show_rooms(B);
        printf("\nPlease choose a room:B-4-");
        scanf("%d", &room);
        if (room > 0 && room <= HOME_SIZE)
            B[room - 1] -= 1;
        output = fopen("B4.txt", "w");
        for(int i = 0; i < HOME_SIZE; ++i)
            fprintf(output, "%d\n", B[i]);
    }
}
</code>```

Notice that :

In C index starts from 0 not 1.

close using file after your work in order to save it properly.

Don't use '%d\n' format for scanf, it will ignore ' ' and '\n' automatically.

Tips for future development :

Try using feof function to know if your file is ended or not instead of using constant size for your inputs.

Title: How to save a modified array to a file

Body:
So I created an array which is saved in a file. I have the number 4 printed out 100 times in the file. Now everytime the an element in the array is accessed it the value will decrease by 1. So if A[1] = 4 is accessed then it will become A[1] = 3 and be saved on the file. The thing is I can't save the modified array to the file.

I already tried moving the placement of FILE pointer.

void buildingB4()
{
    system("CLS");
    FILE *input, *output;
    int i, B4[100], room;

    input = fopen("B4.txt", "r");
    if (input == NULL)
    {
        output = fopen("B4.txt", "w");
        for (i = 1; i <= 100; i++)
        {
            B4[i] = 4;
            fprintf(output, "%d\n", B4[i]);
        }
        fclose(output);
        for (i = 1; i <= 100; i++)
        {
            if (i % 10 == 0)
            {
                printf("\n\n");
            }
            printf("B-4-%d(%d)\t", i, B4[i]);
        }
    }
    else
    {

        for (i = 1; i <= 100; i++)
        {
            fscanf(input, "%d\n", &B4[i]);
            if (i % 10 == 0)
            {
                printf("\n\n");
            }
            printf("B-4-%d(%d)\t", i, B4[i]);
        }
        fclose(input);
        printf("\nPlease choose a room:B-4-");
        scanf("%d", &room);
        B4[room] = B4[room] - 1;
        output = fopen("B4.txt", "a");
        fprintf(output, "%d\n", B4[i]);
        studentDetails();
    }
}

say if A[1] = 4
and when user input is 1, 1 is saved in a variable called room.
so A[room] = A[room] -1
so the result would be A[1] = 3 and it modify the A[1] saved in the file.

Body:
I've found little mistakes in your code and here is your fixed code:

#define HOME_SIZE 100
void show_rooms(int B[]){
    for (int i = 0; i < HOME_SIZE; i++){
            if (i % 10 == 0){
                printf("\n\n");
            }
            printf("B-4-%3d(%d) ", i + 1, B[i]);
        }
}
void buildingB4()
{
    FILE *input, *output;
    input = fopen("B4.txt", "r");
    unsigned int B[HOME_SIZE], room;
    if (input == NULL){
        fclose(input);
        // Setting all homes to 4.
        for (int i = 0; i < HOME_SIZE; ++i){
            B[i] = 4;
        }
        output = fopen("B4.txt", "w");
        for(int i = 0; i < HOME_SIZE; ++i)
            fprintf(output, "%d\n", B[i]);
        fclose(output);
        show_rooms(B);
    }
    else{
        for (int i = 0; i < HOME_SIZE; ++i){
            fscanf(input, "%d", &B[i]);
        }
        fclose(input);
        show_rooms(B);
        printf("\nPlease choose a room:B-4-");
        scanf("%d", &room);
        if (room > 0 && room <= HOME_SIZE)
            B[room - 1] -= 1;
        output = fopen("B4.txt", "w");
        for(int i = 0; i < HOME_SIZE; ++i)
            fprintf(output, "%d\n", B[i]);
    }
}

Notice that :

In C index starts from 0 not 1.

close using file after your work in order to save it properly.

Don't use '%d\n' format for scanf, it will ignore ' ' and '\n' automatically.

Tips for future development :

Try using feof function to know if your file is ended or not instead of using constant size for your inputs.


问:
jQuery form submit: Any way to know what element triggered the submit?
I'm using asp.net MVC and when I submit a form, a previous developer had embedded some jQuery validation.

```<code>$('form').submit(function() {
    ...code done here to validate form fields
});
</code>```

The problem is that both the "Save" and "Cancel" buttons on the form fire this submit jQuery function. I don't want the validation logic to fire if the "Cancel" input button was fired (id="cancel" name="cancel" value="cancel").
Is there a way that, within this submit function, I can retrieve the ID, name or value of which input button was pressed to submit the form?

答:
EDIT

This only works in FF and not in Chrome (and I so, I imagine, not in other WebKit based browsers either) so I'm just leaving this here as a browser specific workaround, an interesting note but not as the answer.

@Neal's suggestion of NOT making the cancel button of type submit is probably the cleanest way. However, if you MUST do it the way you are doing it now:

```<code>$('form').submit(function(e){
    if(e.originalEvent.explicitOriginalTarget.id === 'cancel'){
        //don't validate
    }
    else{
        //validate
    }
});
</code>```

Body:
I'm using asp.net MVC and when I submit a form, a previous developer had embedded some jQuery validation.

$('form').submit(function() {
    ...code done here to validate form fields
});

The problem is that both the "Save" and "Cancel" buttons on the form fire this submit jQuery function. I don't want the validation logic to fire if the "Cancel" input button was fired (id="cancel" name="cancel" value="cancel").
Is there a way that, within this submit function, I can retrieve the ID, name or value of which input button was pressed to submit the form?

Body:
EDIT

This only works in FF and not in Chrome (and I so, I imagine, not in other WebKit based browsers either) so I'm just leaving this here as a browser specific workaround, an interesting note but not as the answer.

@Neal's suggestion of NOT making the cancel button of type submit is probably the cleanest way. However, if you MUST do it the way you are doing it now:

$('form').submit(function(e){
    if(e.originalEvent.explicitOriginalTarget.id === 'cancel'){
        //don't validate
    }
    else{
        //validate
    }
});


问:
Please explain 'switch' in the .toggleClass() API?
Here is the API for the .toggleClass() method of the Jquery library.  I am unsure about how to implement the switch portion.  Is the switch portion supposed to result in boolean value, and if it is, then it is either implemented or not?

So if the code was :

```<code>`$('selector').toggleClass('class-to-be-toggled' , ($(this).hasClass('white')))`
</code>```

and the ($(this).hasClass('white')) evaluated to true, then the .toggleClass() would execute, and if it evaluate to false, then the .toggleClass() would not execute?

Or am i misunderstanding the purpose of switch.

答:
The second parameter to .toggleClass() is a tristate parameter.

$x.toggleClass('c', true) to add class c

$x.toggleClass('c', false) to remove class c

$x.toggleClass('c') to invert whether c is there (add if it was, remove if it wasn't)

$x.toggleClass('class', undefined) also inverts

That fourth alternative is not documented in .toggleClass() but it's guaranteed to work because that's how optional function parameters work.

The distinction in jQuery source code appears to be typeof switch == 'boolean'.
That treats Boolean(0) like false by the way, so that would also remove the class.
Besides omitting the switch parameter,
it seems you could pass null or 42 to get some inverting toggly action.
But of course you shouldn't code on undocumented features.
I'd suggest passing undefined if you want to explicitly toggle.

Body:
Here is the API for the .toggleClass() method of the Jquery library.  I am unsure about how to implement the switch portion.  Is the switch portion supposed to result in boolean value, and if it is, then it is either implemented or not?

So if the code was :

`$('selector').toggleClass('class-to-be-toggled' , ($(this).hasClass('white')))`

and the ($(this).hasClass('white')) evaluated to true, then the .toggleClass() would execute, and if it evaluate to false, then the .toggleClass() would not execute?

Or am i misunderstanding the purpose of switch.


问:
Convert .dbc files into .csv with python
I'm writing a python script to convert .DBC files (from Datasus) into .CSV.

I've searched a lot some libs to help me but didn't get success with any of them. Do someone know an option/package which could be useful in this conversion task?

答:
I really don't understand why some members give -1 to the question, but don't really answer it.

Well, I've not found out a good lib to convert .DBC to .CSV.
But I could do it using Python + R and I'm sharing here how I achieved it.

The Python script below gets R path and executes the dbc2csv.R file sending three args: the raw file path, converted file path, and the file name that will be converted.

```<code>import subprocess
import commands

def dbc2csv(raw_filename):
dbc2csv_path = "/path/to/script/dbc2csv.R " + raw_files_dir + " " + converted_files_dir + " " + raw_filename

try:
    r_script_path = commands.getstatusoutput('which Rscript')[1]
    subprocess.call(r_script_path + " --vanilla " + dbc2csv_path, shell=True)
    return True
except:
    print("(Rscript) Error converting file: " + raw_filename)

return False
</code>```

The R script dbc2csv.R bellow is actually who will convert.

```<code>#install.packages("read.dbc") You need this package
library("read.dbc")

dbc2dbf <- function(rawDir, convertedDir, file) {
    # reads dbc file
    x <- read.dbc(paste(rawDir, file, sep=""))
    # write it to csv
    write.csv(x, file=paste(convertedDir, file, ".csv", sep=""))
}

args = commandArgs(trailingOnly=TRUE)
try(dbc2dbf(args[1], args[2], args[3]), TRUE)
</code>```

We do know it would be better if we could convert using just Python.
But this approach will work fine.

Body:
I really don't understand why some members give -1 to the question, but don't really answer it.

Well, I've not found out a good lib to convert .DBC to .CSV.
But I could do it using Python + R and I'm sharing here how I achieved it.

The Python script below gets R path and executes the dbc2csv.R file sending three args: the raw file path, converted file path, and the file name that will be converted.

import subprocess
import commands

def dbc2csv(raw_filename):
dbc2csv_path = "/path/to/script/dbc2csv.R " + raw_files_dir + " " + converted_files_dir + " " + raw_filename

try:
    r_script_path = commands.getstatusoutput('which Rscript')[1]
    subprocess.call(r_script_path + " --vanilla " + dbc2csv_path, shell=True)
    return True
except:
    print("(Rscript) Error converting file: " + raw_filename)

return False

The R script dbc2csv.R bellow is actually who will convert.

#install.packages("read.dbc") You need this package
library("read.dbc")

dbc2dbf <- function(rawDir, convertedDir, file) {
    # reads dbc file
    x <- read.dbc(paste(rawDir, file, sep=""))
    # write it to csv
    write.csv(x, file=paste(convertedDir, file, ".csv", sep=""))
}

args = commandArgs(trailingOnly=TRUE)
try(dbc2dbf(args[1], args[2], args[3]), TRUE)

We do know it would be better if we could convert using just Python.
But this approach will work fine.


问:
How to get the specific word fron str.contains
I have a pandas data frame with ID and text string.
I am trying categorize the record with str.contains
I need the word from the text string the str.contains code has identified in different columns.I am using python 3 and pandas
My df is as follows:</p>

```<code>ID  Text
1   The cricket world cup 2019 has begun
2   I am eagrly waiting for the cricket worldcup 2019
3   I will try to watch all the mathes my favourite teams playing in the cricketworldcup 2019
4   I love cricket to watch and badminton to play

searchfor = ['cricket','world cup','2019']
 df['text'].str.contains('|'.join(searchfor))

ID  Text                                    phrase1 phrase2    phrase3
1   The cricket world cup 2019 has begun    cricket  world cup 2019
2   I am eagrly waiting for the
cricket worldcup 2019                           cricket world cup   2019
3   I will try to watch all the mathes my
favourite teams playing in the
cricketworldcup 2019                           cricket  world cup   2019
4   I love cricket to watch and badminton
to play                                        cricket
</code>```

答:
The trick is to use str.findall instead of str.contains to get the list of all matched phrases. Then it is just a matter of munging the dataframe to the format you want.

Here is your starting point:

```<code>df = pd.DataFrame(
    [
        'The cricket world cup 2019 has begun',
        'I am eagrly waiting for the cricket worldcup 2019',
        'I will try to watch all the mathes my favourite teams playing in the cricketworldcup 2019',
        'I love cricket to watch and badminton to play',
    ],
    index=pd.Index(range(1, 5), name="ID"),
    columns=["Text"]
)
searchfor = ['cricket','world cup','2019']
</code>```

And here is an example solution:

```<code>pattern = "(" + "|".join(searchfor) + ")"
matches = (
    df.Text.str.findall(pattern)
    .apply(pd.Series)
    .stack()
    .reset_index(-1, drop=True)
    .to_frame("phrase")
    .assign(match=True)
)

#        phrase  match
# ID
# 1     cricket   True
# 1   world cup   True
# 1        2019   True
# 2     cricket   True
# 2        2019   True
# 3     cricket   True
# 3        2019   True
# 4     cricket   True
</code>```

You can also reformat the dataframe to have a separate column for each phrase:

```<code>matches.pivot(columns="phrase", values="match").fillna(False)

# phrase   2019  cricket  world cup
# ID
# 1        True     True       True
# 2        True     True      False
# 3        True     True      False
# 4       False     True      False
</code>```

Body:
I have a pandas data frame with ID and text string.
I am trying categorize the record with str.contains
I need the word from the text string the str.contains code has identified in different columns.I am using python 3 and pandas
My df is as follows:

ID  Text
1   The cricket world cup 2019 has begun
2   I am eagrly waiting for the cricket worldcup 2019
3   I will try to watch all the mathes my favourite teams playing in the cricketworldcup 2019
4   I love cricket to watch and badminton to play

searchfor = ['cricket','world cup','2019']
 df['text'].str.contains('|'.join(searchfor))

ID  Text                                    phrase1 phrase2    phrase3
1   The cricket world cup 2019 has begun    cricket  world cup 2019
2   I am eagrly waiting for the
cricket worldcup 2019                           cricket world cup   2019
3   I will try to watch all the mathes my
favourite teams playing in the
cricketworldcup 2019                           cricket  world cup   2019
4   I love cricket to watch and badminton
to play                                        cricket

Body:
The trick is to use str.findall instead of str.contains to get the list of all matched phrases. Then it is just a matter of munging the dataframe to the format you want.

Here is your starting point:

df = pd.DataFrame(
    [
        'The cricket world cup 2019 has begun',
        'I am eagrly waiting for the cricket worldcup 2019',
        'I will try to watch all the mathes my favourite teams playing in the cricketworldcup 2019',
        'I love cricket to watch and badminton to play',
    ],
    index=pd.Index(range(1, 5), name="ID"),
    columns=["Text"]
)
searchfor = ['cricket','world cup','2019']

And here is an example solution:

pattern = "(" + "|".join(searchfor) + ")"
matches = (
    df.Text.str.findall(pattern)
    .apply(pd.Series)
    .stack()
    .reset_index(-1, drop=True)
    .to_frame("phrase")
    .assign(match=True)
)

#        phrase  match
# ID
# 1     cricket   True
# 1   world cup   True
# 1        2019   True
# 2     cricket   True
# 2        2019   True
# 3     cricket   True
# 3        2019   True
# 4     cricket   True

You can also reformat the dataframe to have a separate column for each phrase:

matches.pivot(columns="phrase", values="match").fillna(False)

# phrase   2019  cricket  world cup
# ID
# 1        True     True       True
# 2        True     True      False
# 3        True     True      False
# 4       False     True      False


问:
Generate a new .txt file every 24 hour
I'm trying to make a visitor counter with php that will create yy-mm-dd.txt everyday and contain the number of visitors that day and after 12 AM it will create a new yy-mm-dd.txt file.
As example today is 2019-06-02 so the text file will be 2019-06-02.txt and in the next day, 2019-06-03.txt file will be automatically created.

Here is what I tried but it is not creating new 2019-06-03.txt file after 12 AM. It keeps the same 2019-06-02.txt file

```<code><?php

    $date = date('Y-m-d');

    $fp = fopen('dates/'.$date.'.txt', "r");

       $count = fread($fp, 1024);

   fclose($fp);

       $count = $count + 1;

       $fp = fopen('dates/'.$date.'.txt', "w");

                 fwrite($fp, $count);

     fclose($fp);

 ?>
</code>```

How to fix it?

答:
Better use file_get_contents then file_put_contents:

```<code><?php
$count = 1;
$content = file_get_contents(date('Y-m-d').'txt');
if($content !== FALSE){
   $count+=(int)$content;
}
file_put_contents(date('Y-m-d').'txt', $count);
?>
</code>```

Title: Generate a new .txt file every 24 hour

Body:
I'm trying to make a visitor counter with php that will create yy-mm-dd.txt everyday and contain the number of visitors that day and after 12 AM it will create a new yy-mm-dd.txt file.
As example today is 2019-06-02 so the text file will be 2019-06-02.txt and in the next day, 2019-06-03.txt file will be automatically created.

Here is what I tried but it is not creating new 2019-06-03.txt file after 12 AM. It keeps the same 2019-06-02.txt file

<?php

    $date = date('Y-m-d');

    $fp = fopen('dates/'.$date.'.txt', "r");

       $count = fread($fp, 1024);

   fclose($fp);

       $count = $count + 1;

       $fp = fopen('dates/'.$date.'.txt', "w");

                 fwrite($fp, $count);

     fclose($fp);

 ?>

How to fix it?

Body:
Better use file_get_contents then file_put_contents:

<?php
$count = 1;
$content = file_get_contents(date('Y-m-d').'txt');
if($content !== FALSE){
   $count+=(int)$content;
}
file_put_contents(date('Y-m-d').'txt', $count);
?>


问:
Out-of-memory-error on Minecraft Server with 16G RAM
Please excuse my inexperience, this is my first time on the site.
I have a Dell PowerEdge r710 with 2 Xeon L5630 CPUs and 16G RAM installed. I'm trying to host a Minecraft 1.7.10 Forge Server that runs perfectly fine on my Desktop, but refuses to run properly on the server.

This machine is running Java 8, and runs perfectly otherwise. When running the application without the mods, it loads up without a hitch. As I add more mods, it gets worse. As far as my (very, very limited) knowledge goes, the order of JVM arguments doesn't matter, and didn't on my Desktop, but in order to get the application to even run I had to change the order in my .bat file. With all mods installed, the Out Of Memory Error occurs with a chunk loading error when around 41% spawn loaded.

This is the .bat file that I've made to start the server:

```<code>java -jar minecraft_server.jar -Xms512M -Xmx8192M  nogui -XX:+HeapDumpOnOutOfMemory
</code>```

This should load up perfectly fine, everything is compatible and tested on another machine, but the exact same setup will not run on the r710, saying Out Of Memory with more than double the desktop's allocated memory.

答:
First you should use Task Manager or a similar utility to make sure that Java process indeed is using more then the amount you allocated with your arguments. Then I would recommend reading through this lovely post written by Cpw and posted on Reddit. If it doesn't help you with your current situation it should at least give you a bit more information on Minecraft's memory footprint.

In a normal situation where you would be running Minecraft as a local server from your computer I would suggest taking a look at how much memory your GPU is taking up. Since you are running a server this is not relevant, but might still be useful to someone who stumbles upon this post so I will leave it here:

Your graphics card is probably the biggest address hog. Today's graphics adapters often contain a gigabyte or more of RAM, and every one of those bytes needs an address. To be fair, I doubt that many of those multi-gigabyte graphics cards are in 32-bit PCs, but even a 512mb video card will take a sizeable bite out of 4GB.

I am not quite familiar with running dedicated servers but another important thing that is worth mentioning is that in case you are on a 32-bit operating system you will only be able to take advantage of 4GB of your RAM due to architecture constraints.

Every byte of RAM requires its own address, and the processor limits the length of those addresses. A 32-bit processor uses addresses that are 32 bits long. There are only 4,294,967,296, or 4GB, possible 32-bit addresses.

If all else fails you should try to seek help on one of the available Discord channels dedicated to Minecraft modding. This should be a rule in general actually, especially for general purpose problems that are difficult for others to reproduce. Here is a small list of three Discord communities dedicated to Minecraft modding that I have experience with:

Modded Minecraft - The one with most traffic so it can be a bit more difficult for your question to get noticed on busy days, but definitely the best moderated one from this list.

Modding Help - The smallest of the three. I don't have much experience with this one.

Mod Dev Cafe - This one has a decent size and a pretty good response rate, but be prepared for the usual facepalms and other unpleasantness common to younger admins and moderators. However if you are willing to look past that this is a good choice.

Body:
Please excuse my inexperience, this is my first time on the site.
I have a Dell PowerEdge r710 with 2 Xeon L5630 CPUs and 16G RAM installed. I'm trying to host a Minecraft 1.7.10 Forge Server that runs perfectly fine on my Desktop, but refuses to run properly on the server.

This machine is running Java 8, and runs perfectly otherwise. When running the application without the mods, it loads up without a hitch. As I add more mods, it gets worse. As far as my (very, very limited) knowledge goes, the order of JVM arguments doesn't matter, and didn't on my Desktop, but in order to get the application to even run I had to change the order in my .bat file. With all mods installed, the Out Of Memory Error occurs with a chunk loading error when around 41% spawn loaded.

This is the .bat file that I've made to start the server:

java -jar minecraft_server.jar -Xms512M -Xmx8192M  nogui -XX:+HeapDumpOnOutOfMemory

This should load up perfectly fine, everything is compatible and tested on another machine, but the exact same setup will not run on the r710, saying Out Of Memory with more than double the desktop's allocated memory.