问:
On Wildfly 11 the Microsoft SQL Server driver incorrectly trys to connect to localhost
We want to switch from Wildfly 9 to Wildfly 11. We are using the Microsoft SQL Server driver in version 4.2.

We use a Microsoft SQL Server and embed the driver like this:

```<code><driver name="sqljdbc" module="com.microsoft.sqlserver.jdbc">
    <driver-class>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver-class>
    <datasource-class>com.microsoft.sqlserver.jdbc.SQLServerDataSource</datasource-class>
</driver>
</code>```

The data source is configured as the following:

```<code><datasource jndi-name="java:jboss/datasources/OurDbDS" pool-name="OurDbDS" enabled="true" use-java-context="true">
    <connection-url>jdbc:sqlserver://our.host.com:1433;DatabaseName=OurDb</connection-url>
    <driver>sqljdbc</driver>
    <pool>
        <min-pool-size>1</min-pool-size>
        <max-pool-size>4</max-pool-size>
    </pool>
    <security>
        <user-name>username</user-name>
        <password>password</password>
    </security>
    <validation>
        <check-valid-connection-sql>select 1</check-valid-connection-sql>
    </validation>
</datasource>
</code>```

When deploying our application on Wildfly 9 everything works. When it is deployed on Wildfly 11 this error occurs:

```<code>17:10:52,218 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 5) MSC000001: Failed to start service jboss.persistenceunit."some-company-util-app-our-app-auth-application-1.5.0-SNAPSHOT.war#our-app": org.jboss.msc.service.StartException in service jboss.persistenceunit."some-company-util-app-our-app-auth-application-1.5.0-SNAPSHOT.war#our-app": javax.persistence.PersistenceException: [PersistenceUnit: our-app] Unable to build Hibernate SessionFactory
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:195)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:125)
    at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:640)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:209)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
    at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: our-app] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:953)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:883)
    at org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.build(TwoPhaseBootstrapImpl.java:44)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:167)
    ... 7 more
Caused by: org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
    at org.hibernate.resource.transaction.backend.jta.internal.DdlTransactionIsolatorJtaImpl.<init>(DdlTransactionIsolatorJtaImpl.java:44)
    at org.hibernate.tool.schema.internal.Helper.buildDefaultDdlTransactionIsolator(Helper.java:145)
    at org.hibernate.tool.schema.internal.HibernateSchemaManagementTool.getDdlTransactionIsolator(HibernateSchemaManagementTool.java:180)
    at org.hibernate.tool.schema.internal.AbstractSchemaValidator.doValidation(AbstractSchemaValidator.java:59)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:65)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:476)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:422)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:880)
    ... 9 more
Caused by: java.sql.SQLException: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:jboss/datasources/OurDbDS
    at org.jboss.jca.adapters.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:146)
    at org.jboss.as.connector.subsystems.datasources.WildFlyDataSource.getConnection(WildFlyDataSource.java:64)
    at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180)
    at org.hibernate.resource.transaction.backend.jta.internal.DdlTransactionIsolatorJtaImpl.<init>(DdlTransactionIsolatorJtaImpl.java:41)
    ... 17 more
Caused by: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:jboss/datasources/OurDbDS
    at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:690)
    at org.jboss.jca.core.connectionmanager.tx.TxConnectionManagerImpl.getManagedConnection(TxConnectionManagerImpl.java:430)
    at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.allocateConnection(AbstractConnectionManager.java:789)
    at org.jboss.jca.adapters.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:138)
    ... 21 more
Caused by: javax.resource.ResourceException: IJ031084: Unable to create connection
    at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:345)
    at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getLocalManagedConnection(LocalManagedConnectionFactory.java:352)
    at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createManagedConnection(LocalManagedConnectionFactory.java:287)
    at org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.createConnectionEventListener(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:1327)
    at org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.getConnection(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:499)
    at org.jboss.jca.core.connectionmanager.pool.AbstractPool.getSimpleConnection(AbstractPool.java:632)
    at org.jboss.jca.core.connectionmanager.pool.AbstractPool.getConnection(AbstractPool.java:604)
    at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:624)
    ... 24 more
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:189)
    at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:240)
    at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2243)
    at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:491)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1313)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:995)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:831)
    at com.microsoft.sqlserver.jdbc.SQLServerDataSource.getConnectionInternal(SQLServerDataSource.java:627)
    at com.microsoft.sqlserver.jdbc.SQLServerDataSource.getConnection(SQLServerDataSource.java:63)
    at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:314)
    ... 31 more

17:10:52,235 ERROR [org.jboss.as.controller.management-operation] (management-handler-thread - 2) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "some-company-util-app-our-app-auth-application-1.5.0-SNAPSHOT.war")]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"some-company-util-app-our-app-auth-application-1.5.0-SNAPSHOT.war#our-app\"" => "javax.persistence.PersistenceException: [PersistenceUnit: our-app] Unable to build Hibernate SessionFactory
    Caused by: javax.persistence.PersistenceException: [PersistenceUnit: our-app] Unable to build Hibernate SessionFactory
    Caused by: org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution
    Caused by: java.sql.SQLException: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:jboss/datasources/OurDbDS
    Caused by: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:jboss/datasources/OurDbDS
    Caused by: javax.resource.ResourceException: IJ031084: Unable to create connection
    Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: \"Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.\"."}}
17:10:52,239 ERROR [org.jboss.as.server] (management-handler-thread - 2) WFLYSRV0021: Deploy of deployment "some-company-util-app-our-app-auth-application-1.5.0-SNAPSHOT.war" was rolled back with the following failure message:
{"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"some-company-util-app-our-app-auth-application-1.5.0-SNAPSHOT.war#our-app\"" => "javax.persistence.PersistenceException: [PersistenceUnit: our-app] Unable to build Hibernate SessionFactory
    Caused by: javax.persistence.PersistenceException: [PersistenceUnit: our-app] Unable to build Hibernate SessionFactory
    Caused by: org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution
    Caused by: java.sql.SQLException: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:jboss/datasources/OurDbDS
    Caused by: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:jboss/datasources/OurDbDS
    Caused by: javax.resource.ResourceException: IJ031084: Unable to create connection
    Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: \"Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.\"."}}
17:10:52,260 INFO  [org.jboss.as.jpa] (ServerService Thread Pool -- 65) WFLYJPA0011: Stopping Persistence Unit (phase 1 of 2) Service 'some-company-util-app-our-app-auth-application-1.5.0-SNAPSHOT.war#our-app'
17:10:52,533 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-2) WFLYSRV0028: Stopped deployment some-company-util-app-our-app-auth-application-1.5.0-SNAPSHOT.war (runtime-name: some-company-util-app-our-app-auth-application-1.5.0-SNAPSHOT.war) in 290ms
[2017-12-04 05:10:52,590] Artifact some-company-util-app-our-app-auth-application:war: Error during artifact deployment. See server log for details.
[2017-12-04 05:10:52,590] Artifact some-company-util-app-our-app-auth-application:war: java.lang.Exception: {"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"some-company-util-app-our-app-auth-application-1.5.0-SNAPSHOT.war#our-app\"" => "javax.persistence.PersistenceException: [PersistenceUnit: our-app] Unable to build Hibernate SessionFactory
    Caused by: javax.persistence.PersistenceException: [PersistenceUnit: our-app] Unable to build Hibernate SessionFactory
    Caused by: org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution
    Caused by: java.sql.SQLException: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:jboss/datasources/OurDbDS
    Caused by: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:jboss/datasources/OurDbDS
    Caused by: javax.resource.ResourceException: IJ031084: Unable to create connection
    Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: \"Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.\"."}}
</code>```

Why does the driver want to connect to localhost although a connection-url is provided?

答:
Removing

```<code><datasource-class>com.microsoft.sqlserver.jdbc.SQLServerDataSource</datasource-class>
</code>```

from the driver section fixed the error.

Body:
We want to switch from Wildfly 9 to Wildfly 11. We are using the Microsoft SQL Server driver in version 4.2.

We use a Microsoft SQL Server and embed the driver like this:

<driver name="sqljdbc" module="com.microsoft.sqlserver.jdbc">
    <driver-class>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver-class>
    <datasource-class>com.microsoft.sqlserver.jdbc.SQLServerDataSource</datasource-class>
</driver>

The data source is configured as the following:

<datasource jndi-name="java:jboss/datasources/OurDbDS" pool-name="OurDbDS" enabled="true" use-java-context="true">
    <connection-url>jdbc:sqlserver://our.host.com:1433;DatabaseName=OurDb</connection-url>
    <driver>sqljdbc</driver>
    <pool>
        <min-pool-size>1</min-pool-size>
        <max-pool-size>4</max-pool-size>
    </pool>
    <security>
        <user-name>username</user-name>
        <password>password</password>
    </security>
    <validation>
        <check-valid-connection-sql>select 1</check-valid-connection-sql>
    </validation>
</datasource>

When deploying our application on Wildfly 9 everything works. When it is deployed on Wildfly 11 this error occurs:

17:10:52,218 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 5) MSC000001: Failed to start service jboss.persistenceunit."some-company-util-app-our-app-auth-application-1.5.0-SNAPSHOT.war#our-app": org.jboss.msc.service.StartException in service jboss.persistenceunit."some-company-util-app-our-app-auth-application-1.5.0-SNAPSHOT.war#our-app": javax.persistence.PersistenceException: [PersistenceUnit: our-app] Unable to build Hibernate SessionFactory
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:195)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:125)
    at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:640)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:209)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
    at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: our-app] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:953)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:883)
    at org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.build(TwoPhaseBootstrapImpl.java:44)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:167)
    ... 7 more
Caused by: org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
    at org.hibernate.resource.transaction.backend.jta.internal.DdlTransactionIsolatorJtaImpl.<init>(DdlTransactionIsolatorJtaImpl.java:44)
    at org.hibernate.tool.schema.internal.Helper.buildDefaultDdlTransactionIsolator(Helper.java:145)
    at org.hibernate.tool.schema.internal.HibernateSchemaManagementTool.getDdlTransactionIsolator(HibernateSchemaManagementTool.java:180)
    at org.hibernate.tool.schema.internal.AbstractSchemaValidator.doValidation(AbstractSchemaValidator.java:59)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:65)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:476)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:422)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:880)
    ... 9 more
Caused by: java.sql.SQLException: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:jboss/datasources/OurDbDS
    at org.jboss.jca.adapters.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:146)
    at org.jboss.as.connector.subsystems.datasources.WildFlyDataSource.getConnection(WildFlyDataSource.java:64)
    at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180)
    at org.hibernate.resource.transaction.backend.jta.internal.DdlTransactionIsolatorJtaImpl.<init>(DdlTransactionIsolatorJtaImpl.java:41)
    ... 17 more
Caused by: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:jboss/datasources/OurDbDS
    at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:690)
    at org.jboss.jca.core.connectionmanager.tx.TxConnectionManagerImpl.getManagedConnection(TxConnectionManagerImpl.java:430)
    at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.allocateConnection(AbstractConnectionManager.java:789)
    at org.jboss.jca.adapters.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:138)
    ... 21 more
Caused by: javax.resource.ResourceException: IJ031084: Unable to create connection
    at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:345)
    at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getLocalManagedConnection(LocalManagedConnectionFactory.java:352)
    at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createManagedConnection(LocalManagedConnectionFactory.java:287)
    at org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.createConnectionEventListener(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:1327)
    at org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.getConnection(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:499)
    at org.jboss.jca.core.connectionmanager.pool.AbstractPool.getSimpleConnection(AbstractPool.java:632)
    at org.jboss.jca.core.connectionmanager.pool.AbstractPool.getConnection(AbstractPool.java:604)
    at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:624)
    ... 24 more
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:189)
    at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:240)
    at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2243)
    at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:491)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1313)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:995)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:831)
    at com.microsoft.sqlserver.jdbc.SQLServerDataSource.getConnectionInternal(SQLServerDataSource.java:627)
    at com.microsoft.sqlserver.jdbc.SQLServerDataSource.getConnection(SQLServerDataSource.java:63)
    at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:314)
    ... 31 more

17:10:52,235 ERROR [org.jboss.as.controller.management-operation] (management-handler-thread - 2) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "some-company-util-app-our-app-auth-application-1.5.0-SNAPSHOT.war")]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"some-company-util-app-our-app-auth-application-1.5.0-SNAPSHOT.war#our-app\"" => "javax.persistence.PersistenceException: [PersistenceUnit: our-app] Unable to build Hibernate SessionFactory
    Caused by: javax.persistence.PersistenceException: [PersistenceUnit: our-app] Unable to build Hibernate SessionFactory
    Caused by: org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution
    Caused by: java.sql.SQLException: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:jboss/datasources/OurDbDS
    Caused by: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:jboss/datasources/OurDbDS
    Caused by: javax.resource.ResourceException: IJ031084: Unable to create connection
    Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: \"Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.\"."}}
17:10:52,239 ERROR [org.jboss.as.server] (management-handler-thread - 2) WFLYSRV0021: Deploy of deployment "some-company-util-app-our-app-auth-application-1.5.0-SNAPSHOT.war" was rolled back with the following failure message:
{"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"some-company-util-app-our-app-auth-application-1.5.0-SNAPSHOT.war#our-app\"" => "javax.persistence.PersistenceException: [PersistenceUnit: our-app] Unable to build Hibernate SessionFactory
    Caused by: javax.persistence.PersistenceException: [PersistenceUnit: our-app] Unable to build Hibernate SessionFactory
    Caused by: org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution
    Caused by: java.sql.SQLException: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:jboss/datasources/OurDbDS
    Caused by: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:jboss/datasources/OurDbDS
    Caused by: javax.resource.ResourceException: IJ031084: Unable to create connection
    Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: \"Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.\"."}}
17:10:52,260 INFO  [org.jboss.as.jpa] (ServerService Thread Pool -- 65) WFLYJPA0011: Stopping Persistence Unit (phase 1 of 2) Service 'some-company-util-app-our-app-auth-application-1.5.0-SNAPSHOT.war#our-app'
17:10:52,533 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-2) WFLYSRV0028: Stopped deployment some-company-util-app-our-app-auth-application-1.5.0-SNAPSHOT.war (runtime-name: some-company-util-app-our-app-auth-application-1.5.0-SNAPSHOT.war) in 290ms
[2017-12-04 05:10:52,590] Artifact some-company-util-app-our-app-auth-application:war: Error during artifact deployment. See server log for details.
[2017-12-04 05:10:52,590] Artifact some-company-util-app-our-app-auth-application:war: java.lang.Exception: {"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"some-company-util-app-our-app-auth-application-1.5.0-SNAPSHOT.war#our-app\"" => "javax.persistence.PersistenceException: [PersistenceUnit: our-app] Unable to build Hibernate SessionFactory
    Caused by: javax.persistence.PersistenceException: [PersistenceUnit: our-app] Unable to build Hibernate SessionFactory
    Caused by: org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution
    Caused by: java.sql.SQLException: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:jboss/datasources/OurDbDS
    Caused by: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:jboss/datasources/OurDbDS
    Caused by: javax.resource.ResourceException: IJ031084: Unable to create connection
    Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: \"Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.\"."}}

Why does the driver want to connect to localhost although a connection-url is provided?

Body:
Removing

<datasource-class>com.microsoft.sqlserver.jdbc.SQLServerDataSource</datasource-class>

from the driver section fixed the error.


来源: stackexchange

问:
Best way to represent a fraction in Java?
I'm trying to work with fractions in Java.

I want to implement arithmetic functions.  For this, I will first require a way to normalize the functions.  I know I can't add 1/6 and 1/2 until I have a common denominator. I will have to add 1/6 and 3/6.  A naive approach would have me add 2/12 and 6/12 and then reduce.  How can I achieve a common denominator with the least performance penalty?  What algorithm is best for this?

Version 8 (thanks to hstoerr):

Improvements include:

the equals() method is now consistent with the compareTo() method

```<code>final class Fraction extends Number {
    private int numerator;
    private int denominator;

    public Fraction(int numerator, int denominator) {
        if(denominator == 0) {
            throw new IllegalArgumentException("denominator is zero");
        }
        if(denominator < 0) {
            numerator *= -1;
            denominator *= -1;
        }
        this.numerator = numerator;
        this.denominator = denominator;
    }

    public Fraction(int numerator) {
        this.numerator = numerator;
        this.denominator = 1;
    }

    public int getNumerator() {
        return this.numerator;
    }

    public int getDenominator() {
        return this.denominator;
    }

    public byte byteValue() {
        return (byte) this.doubleValue();
    }

    public double doubleValue() {
        return ((double) numerator)/((double) denominator);
    }

    public float floatValue() {
        return (float) this.doubleValue();
    }

    public int intValue() {
        return (int) this.doubleValue();
    }

    public long longValue() {
        return (long) this.doubleValue();
    }

    public short shortValue() {
        return (short) this.doubleValue();
    }

    public boolean equals(Fraction frac) {
        return this.compareTo(frac) == 0;
    }

    public int compareTo(Fraction frac) {
        long t = this.getNumerator() * frac.getDenominator();
        long f = frac.getNumerator() * this.getDenominator();
        int result = 0;
        if(t>f) {
            result = 1;
        }
        else if(f>t) {
            result = -1;
        }
        return result;
    }
}
</code>```

I have removed all previous versions.  My thanks to:

Dave Ray

cletus

duffymo

James

Milhous

Oscar Reyes

Jason S

Francisco Canedo

Outlaw Programmer

Beska

答:
I'm trying to work with proper fractions in Java.

Apache Commons Math has had a Fraction class for quite some time. Most times the answer to, "Boy I wish Java had something like X in the core library!" can be found under the umbrella of the Apache Commons library.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to work with fractions in Java.

I want to implement arithmetic functions.  For this, I will first require a way to normalize the functions.  I know I can't add 1/6 and 1/2 until I have a common denominator. I will have to add 1/6 and 3/6.  A naive approach would have me add 2/12 and 6/12 and then reduce.  How can I achieve a common denominator with the least performance penalty?  What algorithm is best for this?

Version 8 (thanks to hstoerr):

Improvements include:

the equals() method is now consistent with the compareTo() method

final class Fraction extends Number {
    private int numerator;
    private int denominator;

    public Fraction(int numerator, int denominator) {
        if(denominator == 0) {
            throw new IllegalArgumentException("denominator is zero");
        }
        if(denominator < 0) {
            numerator *= -1;
            denominator *= -1;
        }
        this.numerator = numerator;
        this.denominator = denominator;
    }

    public Fraction(int numerator) {
        this.numerator = numerator;
        this.denominator = 1;
    }

    public int getNumerator() {
        return this.numerator;
    }

    public int getDenominator() {
        return this.denominator;
    }

    public byte byteValue() {
        return (byte) this.doubleValue();
    }

    public double doubleValue() {
        return ((double) numerator)/((double) denominator);
    }

    public float floatValue() {
        return (float) this.doubleValue();
    }

    public int intValue() {
        return (int) this.doubleValue();
    }

    public long longValue() {
        return (long) this.doubleValue();
    }

    public short shortValue() {
        return (short) this.doubleValue();
    }

    public boolean equals(Fraction frac) {
        return this.compareTo(frac) == 0;
    }

    public int compareTo(Fraction frac) {
        long t = this.getNumerator() * frac.getDenominator();
        long f = frac.getNumerator() * this.getDenominator();
        int result = 0;
        if(t>f) {
            result = 1;
        }
        else if(f>t) {
            result = -1;
        }
        return result;
    }
}

I have removed all previous versions.  My thanks to:

Dave Ray

cletus

duffymo

James

Milhous

Oscar Reyes

Jason S

Francisco Canedo

Outlaw Programmer

Beska

OwnerDisplayName: yawmark

ContentLicense: CC BY-SA 2.5


问:
Is there a keyboard shortcut to restart the current console in cmder?
It seems like there is with ConEmu https://conemu.github.io/en/KeyboardShortcuts.html "Win+~" but a way to restart the current console in cmder would be great.

Cheers

答:
Go to Settings - Main - Keys & Macro
Then select "Recreate active console" from the list and set hotkey for it.
This action will show a dialog with three buttons: Restart, Terminate, Cancel. Restart is a default button and you can choose it by just pressing ENTER key.</p>


问:
Send array or object from php to Elasticsearch
I want to send an array of data (if it can´t be done with arrays I wouldn´t mind converting it to object) to my Elasticsearch index. I used to send my array to a database in MySQL and then load it to Elasticsearch using logstash.
I don´t need the database anymore so I was hoping to accomplish this without it, but I couldn,t find good documentation/examples for it in PHP. Any help is apreciated.

This is how I generate the array ($values[]), it has 3 parameters $exec_time (decimal), $name (text) and $date (datetime):

```<code>for($i=0; $i<50;++$i){

  $date = date('Y-m-d H:i:s');

  if($name == "local")
        $i = $i + 4;

  $ch = $_SESSION['cURL'];
  $time_pre = microtime(true);
  $data = curl_exec($ch);
  $time_pro = microtime(true);
  $exec_time = $time_pro - $time_pre;

  $values[$i] = "('$exec_time', '$name', '$date')";
}
</code>```

答:
You may use elasticsearch-php, the official PHP client for Elasticsearch.

(See the documentation).

Here's another way to do it, using only curl:

```<code>use Curl\Curl; // composer require php-curl-class/php-curl-class

$curl = new Curl();
$curl->setHeader('Content-Type', 'application/json');
$response = $curl->post('http://127.0.0.1:9200/index/type', array(
  'exec_time' => ...
  'name' => ...
  'date' => ...
));
$curl->close();
</code>```

Body:
I want to send an array of data (if it can´t be done with arrays I wouldn´t mind converting it to object) to my Elasticsearch index. I used to send my array to a database in MySQL and then load it to Elasticsearch using logstash.
I don´t need the database anymore so I was hoping to accomplish this without it, but I couldn,t find good documentation/examples for it in PHP. Any help is apreciated.

This is how I generate the array ($values[]), it has 3 parameters $exec_time (decimal), $name (text) and $date (datetime):

for($i=0; $i<50;++$i){

  $date = date('Y-m-d H:i:s');

  if($name == "local")
        $i = $i + 4;

  $ch = $_SESSION['cURL'];
  $time_pre = microtime(true);
  $data = curl_exec($ch);
  $time_pro = microtime(true);
  $exec_time = $time_pro - $time_pre;

  $values[$i] = "('$exec_time', '$name', '$date')";
}

Body:
You may use elasticsearch-php, the official PHP client for Elasticsearch.

(See the documentation).

Here's another way to do it, using only curl:

use Curl\Curl; // composer require php-curl-class/php-curl-class

$curl = new Curl();
$curl->setHeader('Content-Type', 'application/json');
$response = $curl->post('http://127.0.0.1:9200/index/type', array(
  'exec_time' => ...
  'name' => ...
  'date' => ...
));
$curl->close();


问:
Matlab: Add folder and subfolders persistent to path
I have a Matlab directory in my Code folder like this:
~/Code/Matlab/

I want the whole content of this folder (and its subfolders) added permanently to the Matlab-path. So that, when I add a new file/ folder into this folder or its subfolders it gets added automatically to the path.

I know how to add a folder permanent to the path but when I add subfolders/ files to it, they are getting not added.

Is this possible and if yes how?

答:
You need to use genpath for the subfolders, i.e.

```<code>addpath(genpath('YourFolder'));
savepath
</code>```

Then, all the files in those folders (even newly added ones) will be permanently available.

ContentLicense: CC BY-SA 4.0

Body:
You need to use genpath for the subfolders, i.e.

addpath(genpath('YourFolder'));
savepath

Then, all the files in those folders (even newly added ones) will be permanently available.


问:
DB or XML Question
XML seems to be another way to store information in a much smaller scale? While DB can handle all sorts. I'm interested in knowing what are the pro's and con's to the each. Is one of them better in a scenario? I'm sure each has there best case scenario.

Thank you in advance.

答:
Well... XML is a file that anyone can read, since it's text.

A database must be accessed through an API, and conforms to certain database-ey structures.

You can make XML that's like a database, or make it different, too.

You can probably prove that informationally they're equivalent, XML schema to Database schema.

In practice you'll want to write an appropriate API to your particular XML structure. But others could read the schema and do their own...

Databases shine because they usually have an API that lots of agents can access safely simultaneously. XML, by itself, is just a text file.

Title: DB or XML Question


问:
Is optimize select max(date) sql query?
This query is too slow. Is it possible to optimize it?</p>

```<code>SELECT
    CONVERT(CHAR(10), MAX(dat), 101) AS MaxDate
FROM
    X_Prices price
INNER JOIN
    RMetal cat ON cat.SubCat = price.Subcat AND cat.Category = price.Category
WHERE
    cat.Country = 'India'
    AND cat.Section = 1
    AND cat.active = 1
    AND cat.inactive = 0
    AND price.Dat < GETDATE() - 60
</code>```

答:
Apply index on </p>

```<code> Country , Section , active , inactive column of RMetal
table And Category, SubCat, date column of X_Prices table
</code>```

Title: Is optimize select max(date) sql query?

Body:
This query is too slow. Is it possible to optimize it?

SELECT
    CONVERT(CHAR(10), MAX(dat), 101) AS MaxDate
FROM
    X_Prices price
INNER JOIN
    RMetal cat ON cat.SubCat = price.Subcat AND cat.Category = price.Category
WHERE
    cat.Country = 'India'
    AND cat.Section = 1
    AND cat.active = 1
    AND cat.inactive = 0
    AND price.Dat < GETDATE() - 60

Body:
Apply index on

 Country , Section , active , inactive column of RMetal
table And Category, SubCat, date column of X_Prices table


问:
Difference in XSD Validation Errors between .net and other technologies
I have the following schema that I use to validate XMLs in my c# application.
The following code is the example of what I am doing. But what I found out is there is a difference in validations as opposed to validations in other technologies. I am not sure if its related to regex.

```<code><xsd:schema targetNamespace="http://tempuri.org/XMLSchema.xsd"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/XMLSchema.xsd"
    xmlns:mstns="http://tempuri.org/XMLSchema.xsd"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
>
  <xsd:simpleType name="DateCCYYType">
    <xsd:annotation>
      <xsd:documentation>A type that is used for any century/year combination field.</xsd:documentation>
    </xsd:annotation>
    <xsd:restriction base="xsd:string">
      <xsd:maxLength value="4"/>
      <xsd:pattern value="(^$|[1-2][0-9][0-9][0-9])"/>
    </xsd:restriction>
  </xsd:simpleType>
  <xsd:complexType name="PersonalDetails">
    <xsd:sequence>
      <xsd:element name="yearJoined" type="mstns:DateCCYYType"></xsd:element>
      <xsd:element name="yearReleased" type="mstns:DateCCYYType"></xsd:element>
    </xsd:sequence>
  </xsd:complexType>
  <xsd:element name="PersonalDetails" type="mstns:PersonalDetails"></xsd:element>
</xsd:schema>
</code>```

The class file is as follows

```<code>public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            /*textBox1 Contains the xml text
            <urn:PersonalDetails xmlns:urn="http://tempuri.org/XMLSchema.xsd">
                <urn:yearJoined></urn:yearJoined>
                <urn:yearReleased>5000</urn:yearReleased>
            </urn:PersonalDetails>
             */
            StringReader reader = new StringReader(textBox1.Text);
            XmlTextReader xmlReader = new XmlTextReader(@"C:\visual studio 2015\Projects\WindowsFormsApplication1\SampleSchema.xsd");
            Exception xsdException = new Exception();
            try
            {
                bool isValid = IsXmlValidForSchema(reader, xmlReader, ref xsdException);
                if (isValid)
                {
                    MessageBox.Show("Success");
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        public static void ValidateXml(
            StringReader srXML,
            XmlTextReader xtrSchema)
        {

            XmlSchemaSet xssValidate = null;
            try
            {
                xssValidate = new XmlSchemaSet();
                xssValidate.Add(null, xtrSchema);
                xssValidate.Compile();
                XPathDocument xpdValidate = new XPathDocument(srXML);
                XPathNavigator editor = xpdValidate.CreateNavigator();
                if (!editor.CheckValidity(xssValidate, ValidateEventHandler))
                {
                    throw new System.Xml.Schema.XmlSchemaValidationException();
                }
            }
            finally
            {
                if (xssValidate != null) xssValidate = null;
            }
        }

        public static bool IsXmlValidForSchema(
            StringReader xmlReader,
            XmlTextReader schemaReader, ref Exception xsdException)
        {
            bool result = true;
            try
            {
                ValidateXml(xmlReader, schemaReader);
            }
            catch (XmlSchemaValidationException ex)
            {

                xsdException = ex;
                result = false;
            }
            return result;
        }

        private static void ValidateEventHandler(object sender, ValidationEventArgs e)
        {
            if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
            {
                XmlSchemaException schemaException = new XmlSchemaException(e.Message, e.Exception);
                throw schemaException;
            }
        }

    }
</code>```

If you use the xml in the commented block, it validates fine and does not throw error for the emptiness of yearJoined. However if I validate this using other validators like XMLSPY or any online validators, these are shown as errors.
I can fix this in .Net by using minLength. But why is this conflict? Is there a way to correct it.

答:
Microsoft's XSD processor is non-conformant in its use of regular expressions: generally its regular expressions follow the .NET conventions rather than the W3C conventions.

In this particular example the problem is the characters ^ and $ which are ordinary characters, not meta-characters, in conformant XSD regular expressions.

Body:
I have the following schema that I use to validate XMLs in my c# application.
The following code is the example of what I am doing. But what I found out is there is a difference in validations as opposed to validations in other technologies. I am not sure if its related to regex.

<xsd:schema targetNamespace="http://tempuri.org/XMLSchema.xsd"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/XMLSchema.xsd"
    xmlns:mstns="http://tempuri.org/XMLSchema.xsd"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
>
  <xsd:simpleType name="DateCCYYType">
    <xsd:annotation>
      <xsd:documentation>A type that is used for any century/year combination field.</xsd:documentation>
    </xsd:annotation>
    <xsd:restriction base="xsd:string">
      <xsd:maxLength value="4"/>
      <xsd:pattern value="(^$|[1-2][0-9][0-9][0-9])"/>
    </xsd:restriction>
  </xsd:simpleType>
  <xsd:complexType name="PersonalDetails">
    <xsd:sequence>
      <xsd:element name="yearJoined" type="mstns:DateCCYYType"></xsd:element>
      <xsd:element name="yearReleased" type="mstns:DateCCYYType"></xsd:element>
    </xsd:sequence>
  </xsd:complexType>
  <xsd:element name="PersonalDetails" type="mstns:PersonalDetails"></xsd:element>
</xsd:schema>

The class file is as follows

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            /*textBox1 Contains the xml text
            <urn:PersonalDetails xmlns:urn="http://tempuri.org/XMLSchema.xsd">
                <urn:yearJoined></urn:yearJoined>
                <urn:yearReleased>5000</urn:yearReleased>
            </urn:PersonalDetails>
             */
            StringReader reader = new StringReader(textBox1.Text);
            XmlTextReader xmlReader = new XmlTextReader(@"C:\visual studio 2015\Projects\WindowsFormsApplication1\SampleSchema.xsd");
            Exception xsdException = new Exception();
            try
            {
                bool isValid = IsXmlValidForSchema(reader, xmlReader, ref xsdException);
                if (isValid)
                {
                    MessageBox.Show("Success");
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        public static void ValidateXml(
            StringReader srXML,
            XmlTextReader xtrSchema)
        {

            XmlSchemaSet xssValidate = null;
            try
            {
                xssValidate = new XmlSchemaSet();
                xssValidate.Add(null, xtrSchema);
                xssValidate.Compile();
                XPathDocument xpdValidate = new XPathDocument(srXML);
                XPathNavigator editor = xpdValidate.CreateNavigator();
                if (!editor.CheckValidity(xssValidate, ValidateEventHandler))
                {
                    throw new System.Xml.Schema.XmlSchemaValidationException();
                }
            }
            finally
            {
                if (xssValidate != null) xssValidate = null;
            }
        }

        public static bool IsXmlValidForSchema(
            StringReader xmlReader,
            XmlTextReader schemaReader, ref Exception xsdException)
        {
            bool result = true;
            try
            {
                ValidateXml(xmlReader, schemaReader);
            }
            catch (XmlSchemaValidationException ex)
            {

                xsdException = ex;
                result = false;
            }
            return result;
        }

        private static void ValidateEventHandler(object sender, ValidationEventArgs e)
        {
            if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
            {
                XmlSchemaException schemaException = new XmlSchemaException(e.Message, e.Exception);
                throw schemaException;
            }
        }

    }

If you use the xml in the commented block, it validates fine and does not throw error for the emptiness of yearJoined. However if I validate this using other validators like XMLSPY or any online validators, these are shown as errors.
I can fix this in .Net by using minLength. But why is this conflict? Is there a way to correct it.


问:
Replace all None's in a Pandas data frame with a tuple of None's
So I am working on some code for an NLP application. An interesting solution on Stackoverflow creates a dataframe from lists of unequal lengths. Taking the code from that solution with tuples in the input:

```<code>import pandas as pd
import itertools

aa = [('aa1',4), ('aa2',3), ('aa3',2), ('aa4',2), ('aa5',1)]
bb = [('bb1',8), ('bb2',6), ('bb3',4), ('bb4',4)]
cc = [('cc1',3), ('cc2',2), ('cc3',1)]
nest = [aa, bb, cc]

df = pd.DataFrame((_ for _ in itertools.zip_longest(*nest)), columns=['aa', 'bb', 'cc'])
df
</code>```

you get a dataframe which looks like this:

A subsequent step requires all elements in the data frame to be tuples.

I have tried this:

```<code>df.replace({None : (None,None)})
</code>```

While it seems to run without error, it does not carry out any replacement.
Any ideas how to accomplish this?

答:
One way to do it would be using pandas.DataFrame.apply() and pandas.Series.map() like this:

```<code>df.apply(lambda ds: ds.map(lambda x: x if x != None else (None, None)))
</code>```

Body:
So I am working on some code for an NLP application. An interesting solution on Stackoverflow creates a dataframe from lists of unequal lengths. Taking the code from that solution with tuples in the input:

import pandas as pd
import itertools

aa = [('aa1',4), ('aa2',3), ('aa3',2), ('aa4',2), ('aa5',1)]
bb = [('bb1',8), ('bb2',6), ('bb3',4), ('bb4',4)]
cc = [('cc1',3), ('cc2',2), ('cc3',1)]
nest = [aa, bb, cc]

df = pd.DataFrame((_ for _ in itertools.zip_longest(*nest)), columns=['aa', 'bb', 'cc'])
df

you get a dataframe which looks like this:

A subsequent step requires all elements in the data frame to be tuples.

I have tried this:

df.replace({None : (None,None)})

While it seems to run without error, it does not carry out any replacement.
Any ideas how to accomplish this?

Body:
One way to do it would be using pandas.DataFrame.apply() and pandas.Series.map() like this:

df.apply(lambda ds: ds.map(lambda x: x if x != None else (None, None)))


问:
How to check if the exact vector is a subset of another vector of a list
I skimmed similar posts and I have tried them but I still could not solve my problem.

I have a list of vector such as following

```<code>y2 <- c(0,0,NA,0,0,0,0)
y <- c(0,0,0,NA,NA,0)
x <- c(0,0,0,0)
li <-list(y2,y,x)
</code>```

I am trying to drop the vector from the list li, if an exact vector is a subset of another one.

For example, in my case I should have y2 and y as result and have x dropped from the list since x is an exact subset of y2.

I wrote the following script but it just gives the y2 as result, and ignores y:

```<code>UniquePath <- function(PATHS)
{
  for(j in length(PATHS):1)
  {
    for(i in 1:length(PATHS))
    {
      if((i!=j)&(isTRUE(all(is.element(PATHS[[j]],PATHS[[i]])))))
      {
        PATHS<-PATHS[-j]
        break
      }
      else
      {
        next
      }
    }
  }
  return(PATHS)
}
</code>```

答:
My approach would be (assuming there are no ";" in your string)

```<code># make li unique
li <- unique(li)
# collapse each unique list element to a length-1 string surrounded by ";"
x <- sapply(li, function(x) paste0(";", paste(x, collapse = ";"), ";"))
# check each element, if this is found somewhere in any other element
li[sapply(seq_along(x), function(i) !any(grepl(x[i], x[-i], fixed = TRUE)))]
# [[1]]
# [1]  0  0 NA  0  0  0  0
#
# [[2]]
# [1]  0  0  0 NA NA  0
</code>```

However, it seems that OP should make up a larger example and clarify some of the questions brought up in comments to other answers.

Note: in this answer I define x as a subset of y if and only if the exact sequence of x is present in y without any other elements inbetween. That's how I understood the question.

Body:
I skimmed similar posts and I have tried them but I still could not solve my problem.

I have a list of vector such as following

y2 <- c(0,0,NA,0,0,0,0)
y <- c(0,0,0,NA,NA,0)
x <- c(0,0,0,0)
li <-list(y2,y,x)

I am trying to drop the vector from the list li, if an exact vector is a subset of another one.

For example, in my case I should have y2 and y as result and have x dropped from the list since x is an exact subset of y2.

I wrote the following script but it just gives the y2 as result, and ignores y:

UniquePath <- function(PATHS)
{
  for(j in length(PATHS):1)
  {
    for(i in 1:length(PATHS))
    {
      if((i!=j)&(isTRUE(all(is.element(PATHS[[j]],PATHS[[i]])))))
      {
        PATHS<-PATHS[-j]
        break
      }
      else
      {
        next
      }
    }
  }
  return(PATHS)
}

Body:
My approach would be (assuming there are no ";" in your string)

# make li unique
li <- unique(li)
# collapse each unique list element to a length-1 string surrounded by ";"
x <- sapply(li, function(x) paste0(";", paste(x, collapse = ";"), ";"))
# check each element, if this is found somewhere in any other element
li[sapply(seq_along(x), function(i) !any(grepl(x[i], x[-i], fixed = TRUE)))]
# [[1]]
# [1]  0  0 NA  0  0  0  0
#
# [[2]]
# [1]  0  0  0 NA NA  0

However, it seems that OP should make up a larger example and clarify some of the questions brought up in comments to other answers.

Note: in this answer I define x as a subset of y if and only if the exact sequence of x is present in y without any other elements inbetween. That's how I understood the question.


问:
how to use transaction in sequelize using nodejs
Below code throw "TypeError: sequelize.transaction is not a function" Error

```<code>sequelize.transaction(transaction => {
          myDb.myTable.findAll({attributes:['IMAGEPATH'],where:{ID : customerId}})
          .then((result) => {

          ....

          }).then((commitResult) =>{
                //commit
          }).catch((rollbackErr) =>{
                //rollback

          })
</code>```

答:
It looks like you're trying to reference the transaction function on the definition as opposed to the instance i.e.

```<code>const sequelize = require('sequelize');
sequelize.transaction(...); // doesn't exist
</code>```

You need to create a sequelize instance and use the transaction function on this

```<code>const Sequelize = require('sequelize');
const db = new Sequelize(...);
db.transaction(...); // works
</code>```

See the docs.

Body:
Below code throw "TypeError: sequelize.transaction is not a function" Error

sequelize.transaction(transaction => {
          myDb.myTable.findAll({attributes:['IMAGEPATH'],where:{ID : customerId}})
          .then((result) => {

          ....

          }).then((commitResult) =>{
                //commit
          }).catch((rollbackErr) =>{
                //rollback

          })

Body:
It looks like you're trying to reference the transaction function on the definition as opposed to the instance i.e.

const sequelize = require('sequelize');
sequelize.transaction(...); // doesn't exist

You need to create a sequelize instance and use the transaction function on this

const Sequelize = require('sequelize');
const db = new Sequelize(...);
db.transaction(...); // works

See the docs.


问:
Readable key value pair data-structure in java
I have a key value arrays

```<code>String[] fields      = {"firstName", "middleName", "id"};
String[] fieldValues = {"first name", "middle name", "student id"};
</code>```

I have a method that compares two beans and returns a array of String with different field values.

```<code> public static String[] beanCompare(Object A, Object B,
                                          String[] fields, String[] fieldValue);
</code>```

Example If I pass a Studentbean with different firstName and id.
It will return

["first name", "student id"].

I need to compare 100's of beans.

The return value updates an activity log table. Let say, the firstName field is updated. We display

the first name has been updated

in the UI. It's for auditing.
 Is there a readable and maintainable way to represent such key-value pair?

答:
Correct me if I'm wrong, but it seems that (passing field names and field values this way) you're trying to build custom objects dynamically.

If that's your purpose, then you're in full XY problem, since you've figured out this solution to your problem, and then you're trying to tune up this solution, while you should go back to the problem, which has a standard, engineered, best practice solution: the Builder Pattern.

If you have many fields on an object, but you need to use only a portion of them in some cases and another portion in other cases, then use a Builder, set only the fields you need, then invoke the build() method, and get your object without the need to do what you're doing or permute all the constructors.

Here is an example of this pattern in Java.

Body:
I have a key value arrays

String[] fields      = {"firstName", "middleName", "id"};
String[] fieldValues = {"first name", "middle name", "student id"};

I have a method that compares two beans and returns a array of String with different field values.

 public static String[] beanCompare(Object A, Object B,
                                          String[] fields, String[] fieldValue);

Example If I pass a Studentbean with different firstName and id.
It will return

["first name", "student id"].

I need to compare 100's of beans.

The return value updates an activity log table. Let say, the firstName field is updated. We display

the first name has been updated

in the UI. It's for auditing.
 Is there a readable and maintainable way to represent such key-value pair?


问:
Processing large xml files
I am having a large xml file which contains many sub elements. I want to able to run some xpath queries. I tried using vtd-xml in java, but I get outofmemory error sometimes, because the xml is so large to fit into memory. Is there an alternative way of processing such large xml's.</p>

答: SAXParser is very efficient when working with large files</p>

Title: Processing large xml files


问:
JQuery Select Input Fields Except Hidden
I have a row in a table which contains a checkbox and some other form fields (text boxes, hidden fields, select lists). When the checkbox is checked I want to disable all form fields in that row except for the hidden fields. I have this working for the most part, but I can't seem to ignore the hidden fields.

What is the best way to select all form fields in a table row but ignore hidden fields in the selection?

答:
Just add a filter of visible  which means it will take only input element which are visible to users.

This worked for me I am adding description for 30 char.

$("input:visible")


问:
Why in JHipster DTOs are generated in the service layer and not in the REST layer?
We've started a JHipster project and used DTOs. At the beginning I wasn't fan, but then, this allowed us to really customize our DTOs for our REST layer: perfect.

But now we are adding JMS to the project and we realize that our message listeners need to access our service layer... but the services returns DTOs that are suited for the REST layer, not the messaging layer.

Why does JHipster generate the DTOs in the service layer ? Why not in the REST layer ? This way, both REST and JMS layer (and something else later) could access the service layer that only deals with entities. Then, both REST and JMS will have their own DTOs suited for their own needs.

Any idea why this was done on the first place ?
Thanks

答:
In JHipster, you have in fact DTOs and VMs:

DTOs (Data Transfer Objects) are in the service layer: they are here to get data out of the transactional layer. The idea is that inside the service layer you have JPA entities, which have relationships (lazy loaded with Hibernate), and that the service layer returns DTOs which are not managed by Hibernate (no lazy loading anymore). There might not be a 1-to-1 relationship between entities and DTOs: maybe DTOs aggregate several entities, maybe they have more fields (or less fields!), that all depends on your business model.

VMs (View Models) are in view layer. This wording comes from Angular, where we often have "vm" objects. The idea is to have objects which are specific to your view layer, so it's easier, more secured and more performant to code the client application. There could be several VMs for one DTOs, as the DTO's data might be used in several different screens. Typically VMs are what is being transferred in JSON from the Java back-end to the JavaScript front-end.

None of those layers are mandatory with JHipster. You will typically have:

Just entities for simple CRUDs

Entities and DTOs for business code

Entities and VMs when there is a specific, complex view

Entities, DTOS and VMs when everything is complex


问:
How to group archive post by year Wordpress
I have a custom post archive I want to group each each custom post by year.
This is my example view for my template. I have already an idea but I want the mos efficient way to create my template.

Heres my template view

```<code>-----------------
|      2016     |
|    Post Here  |
|    Post Here  |
|    Post Here  |
-----------------
|      2015     |
|    Post Here  |
|    Post Here  |
|    Post Here  |
-----------------
|      2014     |
|    Post Here  |
|    Post Here  |
|    Post Here  |
</code>```

I want to make this as dynamic as I can.
Any suggestion are highly appreciated.

答:
I don't like recommending a plugin, but this plugin does exactly what you need, and it is the easiest way to go.

OK, that out of the way, you should download and install the Simple Yearly Archive plugin. I quote from the plugin page

And also you can find shortcode for this plugin from official website
https://www.schloebe.de/wordpress/simple-yearly-archive-plugin/

Body:
I have a custom post archive I want to group each each custom post by year.
This is my example view for my template. I have already an idea but I want the mos efficient way to create my template.

Heres my template view

-----------------
|      2016     |
|    Post Here  |
|    Post Here  |
|    Post Here  |
-----------------
|      2015     |
|    Post Here  |
|    Post Here  |
|    Post Here  |
-----------------
|      2014     |
|    Post Here  |
|    Post Here  |
|    Post Here  |

I want to make this as dynamic as I can.
Any suggestion are highly appreciated.


问:
Yii2 - list every post - coding error
I am new in Yii2 and I made a site where i can write posts, view them, delete them etc...

I want to list every post from a DB on one page as a "timeline"

My code does not list any error simply just show the very first record only.

Here is my code from (views) index.php

```<code>        <?php

use yii\helpers\Html;
use yii\widgets\ListView;

/* @var $this yii\web\View */
/* @var $searchModel frontend\models\search\TweetSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'My tweets';

?>
<div class="tweet-model-index">

    <h1 class="text-center"><?= Html::encode($this->title) ?></h1>

    <p class="text-center">
        <?= Html::a('New Tweet', ['create'], ['class' => 'btn btn-success']) ?>
    </p>

    <?php

    $con = \Yii::$app->db;

    $sql = $con->createCommand("SELECT * FROM tweet ORDER BY created_at DESC");

    $tweets = $sql->queryAll();

    if(!$tweets)
        echo '<h2> This is empty </h2>';
     else{
           foreach($tweets as $tweet){
       ?>

    <hr>
    <div class="container-fluid">
        <div class="col-md-8 col-md-offset-2">
            <h2 class="text-left">
                <?php echo $tweet['tweet_title']; ?>
                <br><small>Author: <b><?php echo $tweet['author_id'];?> </b>Created at: <b><?php echo date(($tweet['created_at']));?></b>
                    <br>Updated at: <b><?php echo date(($tweet['updated_at']));?>
                </small>
            </h2>

                <p class="text-left">
                <?= Html::a('Update', ['update', 'id' => $tweet['tweet_id']], ['class' => 'btn btn-primary']) ?>
                <?= Html::a('View', ['view', 'id' => $tweet['tweet_id']], ['class' => 'btn btn-primary']) ?>
                <?= Html::a('Delete', ['delete', 'id' => $tweet['tweet_id']], [
                                        'class' => 'btn btn-danger',
                                        'data' => [
                                        'confirm' => 'Are you sure you want to delete this item?',
                                        'method' => 'post',
                                        ],
                                    ]) ?>
                </p>

        </div>

    </div>

</div>
<?php endforeach; ?>
<?php endif; ?>
</code>```

May i ask You guys, how can I count the views on each post?

I tried this on my TweetController but doesn't work.

```<code>public function actionView($id)
{
    $this->render('view',array(
        'model'=>$this->loadModel($id));
}
</code>```

答:
Start using braces!

```<code>else
    foreach($tweets as $tweet);
?>
</code>```

to this:

```<code>else {
    foreach($tweets as $tweet) {
?>
</code>```

or even better in VIEWS:

```<code>else:
    foreach($tweets as $tweet):
?>

.....
.....

<?php endforeach; ?>
<?php endif; ?>
</code>```

Title: Yii2 - list every post - coding error

Body:
I am new in Yii2 and I made a site where i can write posts, view them, delete them etc...

I want to list every post from a DB on one page as a "timeline"

My code does not list any error simply just show the very first record only.

Here is my code from (views) index.php

        <?php

use yii\helpers\Html;
use yii\widgets\ListView;

/* @var $this yii\web\View */
/* @var $searchModel frontend\models\search\TweetSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'My tweets';

?>

<?= Html::encode($this->title) ?>

        <?= Html::a('New Tweet', ['create'], ['class' => 'btn btn-success']) ?>

    <?php

    $con = \Yii::$app->db;

    $sql = $con->createCommand("SELECT * FROM tweet ORDER BY created_at DESC");

    $tweets = $sql->queryAll();

    if(!$tweets)
        echo '
 This is empty
';
     else{
           foreach($tweets as $tweet){
       ?>

                <?php echo $tweet['tweet_title']; ?>

Author: <?php echo $tweet['author_id'];?> Created at: <?php echo date(($tweet['created_at']));?>

Updated at: <?php echo date(($tweet['updated_at']));?>

                <?= Html::a('Update', ['update', 'id' => $tweet['tweet_id']], ['class' => 'btn btn-primary']) ?>
                <?= Html::a('View', ['view', 'id' => $tweet['tweet_id']], ['class' => 'btn btn-primary']) ?>
                <?= Html::a('Delete', ['delete', 'id' => $tweet['tweet_id']], [
                                        'class' => 'btn btn-danger',
                                        'data' => [
                                        'confirm' => 'Are you sure you want to delete this item?',
                                        'method' => 'post',
                                        ],
                                    ]) ?>

<?php endforeach; ?>
<?php endif; ?>

May i ask You guys, how can I count the views on each post?

I tried this on my TweetController but doesn't work.

public function actionView($id)
{
    $this->render('view',array(
        'model'=>$this->loadModel($id));
}

Body:
Start using braces!

else
    foreach($tweets as $tweet);
?>

to this:

else {
    foreach($tweets as $tweet) {
?>

or even better in VIEWS:

else:
    foreach($tweets as $tweet):
?>

.....
.....

<?php endforeach; ?>
<?php endif; ?>


问:
Draw bean machine
I'm trying to draw Bean Machine as follow:

```<code>@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    int width = getWidth();
    int height = getHeight();

    int xCenter = getWidth() / 2;
    int yCenter = getHeight() / 2;

    g.drawLine(xCenter + 20, yCenter, xCenter + 20, yCenter + 20); // right horizontal line
    g.drawLine(xCenter, yCenter, xCenter, yCenter + 20); //left horizontal line
    g.drawLine(xCenter + 20, yCenter + 20, xCenter + 70, yCenter + 110); // right line
    g.drawLine(xCenter, yCenter + 20, xCenter - 50, yCenter + 110); //left line
    g.drawLine(xCenter - 50, yCenter + 110, xCenter + 70, yCenter + 110);//base line

    //draw nails
    for (int i = 1; i <= nails; i++) {
        for (int j = 0; j < i; j++) {
            g.fillOval(xCenter  + i, yCenter + 20 * j, (int)(0.09 * xCenter) / 3, (int)(0.09 * yCenter) / 3);
        }
    }
}
</code>```

I'm facing issue with drawing ovals (Ovals represent nails as know), I dun know how to do it correctly,

Here is what I get.

The expected output is know for all I though.

答:
There are several issues here:

fillOval(xCenter  + i needs to be fillOval(xCenter + 20 * i. This explains why every row gets a little longer than the other, because your nails are squished together and overlap each other.

Right now, you have more nails on top. If you let the outer loop count backwards, you can turn the pyramid around.

Your nails look like squares because they are too small to have rounded corners.

When fixing the x coordinate of fillOval and making th dots larger (0.29 instead of 0.09), it looks like this:

Title: Draw bean machine

Body:
I'm trying to draw Bean Machine as follow:

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    int width = getWidth();
    int height = getHeight();

    int xCenter = getWidth() / 2;
    int yCenter = getHeight() / 2;

    g.drawLine(xCenter + 20, yCenter, xCenter + 20, yCenter + 20); // right horizontal line
    g.drawLine(xCenter, yCenter, xCenter, yCenter + 20); //left horizontal line
    g.drawLine(xCenter + 20, yCenter + 20, xCenter + 70, yCenter + 110); // right line
    g.drawLine(xCenter, yCenter + 20, xCenter - 50, yCenter + 110); //left line
    g.drawLine(xCenter - 50, yCenter + 110, xCenter + 70, yCenter + 110);//base line

    //draw nails
    for (int i = 1; i <= nails; i++) {
        for (int j = 0; j < i; j++) {
            g.fillOval(xCenter  + i, yCenter + 20 * j, (int)(0.09 * xCenter) / 3, (int)(0.09 * yCenter) / 3);
        }
    }
}

I'm facing issue with drawing ovals (Ovals represent nails as know), I dun know how to do it correctly,

Here is what I get.

The expected output is know for all I though.


问:
How to get the paragraph Number from Word Document in VSTO
Suppose we have a paragraph in a document as below:

Orange

Apple

Mango

I need to retrieve the Numbered List for each entities in the paragraph. For Orange- 1, Apple-2 and Mango-3
I have already used the below code to find out the list of Paragraphs in the document.
Word.Paragraphs para = ActiveDocument.Paragraphs;

From para  object I need to find out the Numbering of the list for each entities.

答:
I'm not 100% I understand your question but it appears you are using a numbered list style on the 3 paragraphs and you would like to get the values of the numbered list style? (1, 2 and 3)

A word Paragraph has in VBA/VSTO/etc.. a Range object
On the Range object you will find the ListFormat object which gives you the info you need.

So if you have in your first paragraph:
1. Orange
then you can use:

```<code>ActiveDocument.Paragraphs[1].Range.ListFormat.ListString
</code>```

This will give you the "1."
And

```<code>ActiveDocument.Paragraphs[1].Range.ListFormat.ListValue
</code>```

This will give you the 1

Good luck

Body:
I'm not 100% I understand your question but it appears you are using a numbered list style on the 3 paragraphs and you would like to get the values of the numbered list style? (1, 2 and 3)

A word Paragraph has in VBA/VSTO/etc.. a Range object
On the Range object you will find the ListFormat object which gives you the info you need.

So if you have in your first paragraph:
1. Orange
then you can use:

ActiveDocument.Paragraphs[1].Range.ListFormat.ListString

This will give you the "1."
And

ActiveDocument.Paragraphs[1].Range.ListFormat.ListValue

This will give you the 1

Good luck


问:
tkinter: Is it possible to use native Tcl/Tk tklib's ctext widget?
I have come across an interesting widget (source code) which seems to support syntax highlighting and a bunch of other stuff. I would like to use it in my tkinter app, however I'm not sure if that's entirely possible. I know that you can use tkinter.eval() to evaluate raw Tcl/Tk code, but I'm not sure what am I supposed to do after I evaluate the entire source code/place it somewhere - how can I instantiate the widget and actually use it?

答:
I happen to have the source for ctext (which is part of tklib) so I can let my Tcl library know about the additional package location using TCLLIBPATH environment variable. Then it can just be loaded. However, you will need to do some interfacing to python

```<code>pat@uknml7167 ~ $ TCLLIBPATH=/opt/src/tklib/modules python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tkinter as tk
>>> root = tk.Tk()
>>> root.tk.call('package','require','ctext')
'3.3'
</code>```

So the short answer is 'yes'.

There is a bit of an example for tkribbon on this site. I'm sure there are better examples of using a native Tk package around.

A quick demo based on the above:

```<code>class Ctext(tk.Widget):
    def __init__(self, master):
        tk.Widget.__init__(self, master, 'ctext')

ctext = Ctext(root)
ctext.pack(expand=True, fill='both')
</code>```

A tkinter wrapper class has been uploaded to github along with a small demo script.

Body:
I happen to have the source for ctext (which is part of tklib) so I can let my Tcl library know about the additional package location using TCLLIBPATH environment variable. Then it can just be loaded. However, you will need to do some interfacing to python

pat@uknml7167 ~ $ TCLLIBPATH=/opt/src/tklib/modules python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tkinter as tk
>>> root = tk.Tk()
>>> root.tk.call('package','require','ctext')
'3.3'

So the short answer is 'yes'.

There is a bit of an example for tkribbon on this site. I'm sure there are better examples of using a native Tk package around.

A quick demo based on the above:

class Ctext(tk.Widget):
    def __init__(self, master):
        tk.Widget.__init__(self, master, 'ctext')

ctext = Ctext(root)
ctext.pack(expand=True, fill='both')

A tkinter wrapper class has been uploaded to github along with a small demo script.


问:
How to store Bytes/Slice(UInt8) as a string in Crystal?
I'm encoding an Object into Bytes (ie Slice(UInt8)) via MessagePack. How would I store this in a datastore client (eg Crystal-Redis) that only accepts Strings?

答:
Both Crystal and Redis should be able to handle strings with non-valid UTF-8 bytes, so you could just directly create a String from the slice and store this to Redis and vice versa.

This is of course not entirely safe: you should make sure to avoid invoking any string methods that expect a valid UTF-8 string.
But apart from that, this direct method should be perfectly fine. Is is faster and more memory-efficient than using a string encoding.

```<code>redis.set key, String.new(slice)
redis.get(key).to_slice
</code>```

Body:
Both Crystal and Redis should be able to handle strings with non-valid UTF-8 bytes, so you could just directly create a String from the slice and store this to Redis and vice versa.

This is of course not entirely safe: you should make sure to avoid invoking any string methods that expect a valid UTF-8 string.
But apart from that, this direct method should be perfectly fine. Is is faster and more memory-efficient than using a string encoding.

redis.set key, String.new(slice)
redis.get(key).to_slice


问:
python-xarray: open_dataarray Segmentation fault on HPC

I'm struggling to understand why reading in a NetCDF file using open_dataarray in the HPC I use produces a Segmentation fault (core dumped). However, when I read in the file using open_dataarray on my Mac it works fine.

From looking into this further it is the NPac file (the sub-section) which I created which seems to have issues. Here is the steps I took to generate the file:

WaveWatchIII outputs a file

Extract July: $ncks -d time,0,30 in.nc out.nc Can open out.nc in HPC

Extract variable: $ncks -v hs in.nc out.nc Can open out.nc in HPC

Extract domain: $ncks -d longitude,100.0,290.0 -d latitude,0.0,65.0 in.nc out.nc Cannot open out.nc on HPC but can open out.nc on Mac.

This is the first time i've seen this issue and I believe it is due to properties of the domain of the NetCDF file. I'm guessing it may have something to do with versions as well? I do most of the heavy lifting on the HPC and use my Mac for testing and understanding so it would be nice to get this working on the HPC.

The NetCDF file can be downloaded here

```<code>ncdump -h ww3.Hs.July.NPac.nc
netcdf ww3.Hs.July.NPac {
dimensions:
    time = UNLIMITED ; // (31 currently)
    latitude = 66 ;
    longitude = 191 ;
variables:
    short hs(time, latitude, longitude) ;
            hs:long_name = "significant height of wind and swell waves" ;
            hs:standard_name = "sea_surface_wave_significant_height" ;
            hs:globwave_name = "significant_wave_height" ;
            hs:units = "m" ;
            hs:_FillValue = -32767s ;
            hs:scale_factor = 0.002f ;
            hs:add_offset = 0.f ;
            hs:valid_min = 0 ;
            hs:valid_max = 32000 ;
    float latitude(latitude) ;
            latitude:units = "degree_north" ;
            latitude:long_name = "latitude" ;
            latitude:standard_name = "latitude" ;
            latitude:valid_min = -90.f ;
            latitude:valid_max = 90.f ;
            latitude:axis = "Y" ;
    float longitude(longitude) ;
            longitude:units = "degree_east" ;
            longitude:long_name = "longitude" ;
            longitude:standard_name = "longitude" ;
            longitude:valid_min = -180.f ;
            longitude:valid_max = 180.f ;
            longitude:axis = "X" ;
    double time(time) ;
            time:long_name = "julian day (UT)" ;
            time:standard_name = "time" ;
            time:units = "days since 1850-01-01T00:00:00Z" ;
            time:conventions = "relative julian days with decimal part (as parts of the day )" ;
            time:axis = "T" ;

// global attributes:
            :WAVEWATCH_III_version_number = "4.18b" ;
            :WAVEWATCH_III_switches = "NC4 F90 NOGRB NOPA LRB4 SHRD PR3 UQ FLX0 LN1 ST4 STAB0 NL1 BT1 DB1 MLIM TR0 BS0 IC0 REF0 XX0 WNT1 WNX1 CRT1 CRX1 O0 O1 O2 O3 O4 O5 O6 O7 O11 O14 TRKNC" ;
            :SDS4\ namelist\ parameter\ WHITECAPWIDTH = 0.3f ;
            :product_name = "ww3.199307.nc" ;
            :area = "Indian Ocean Pacfic 1 degree" ;
            :latitude_resolution = "   1.0000000" ;
            :longitude_resolution = "   1.0000000" ;
            :southernmost_latitude = "-70.0000000" ;
            :northernmost_latitude = "65.0000000" ;
            :westernmost_longitude = "20.0000000" ;
            :easternmost_longitude = "295.0000000" ;
            :minimum_altitude = "-12000 m" ;
            :maximum_altitude = "9000 m" ;
            :altitude_resolution = "n/a" ;
            :start_date = "1993-07-01T00:00:00Z" ;
            :stop_date = "1993-07-31T00:00:00Z" ;
            :history = "Sat Dec  2 17:53:06 2017: ncks -O -d longitude,100.0,290.0 -d latitude,0.0,65.0 /projects/rsmas/kirtman/rxb826/WW3exps/IO_Pac_CCSM4/CCSM4_19930701_19940630_1a1/work/ww3.Hs.July.nc /projects/rsmas/kirtman/rxb826/WW3exps/IO_Pac_CCSM4/CCSM4_19930701_19940630_1a1/work/ww3.Hs.July.NPac.nc\nSat Dec  2 17:53:06 2017: ncks -O -v hs /projects/rsmas/kirtman/rxb826/WW3exps/IO_Pac_CCSM4/CCSM4_19930701_19940630_1a1/work/ww3.July.nc /projects/rsmas/kirtman/rxb826/WW3exps/IO_Pac_CCSM4/CCSM4_19930701_19940630_1a1/work/ww3.Hs.July.nc\nSat Dec  2 17:53:05 2017: ncks -O -d time,0,30 /projects/rsmas/kirtman/rxb826/WW3exps/IO_Pac_CCSM4/CCSM4_19930701_19940630_1a1/work/ww3.19930701_19940630.nc /projects/rsmas/kirtman/rxb826/WW3exps/IO_Pac_CCSM4/CCSM4_19930701_19940630_1a1/work/ww3.July.nc\nFri Nov  4 13:50:57 2016: ncrcat -O -o tmp.nc ww3.199307.nc ww3.199308.nc ww3.199309.nc ww3.199310.nc ww3.199311.nc ww3.199312.nc ww3.199401.nc ww3.199402.nc ww3.199403.nc ww3.199404.nc ww3.199405.nc ww3.199406.nc" ;
            :nco_openmp_thread_number = 1 ;
            :NCO = "4.3.7" ;
</code>```

On the HPC:

```<code>$ nc-config --version
netCDF 4.2.1.1

>>> xr.show_versions()
INSTALLED VERSIONS
------------------
commit: None
python: 3.6.3.final.0
python-bits: 64
OS: Linux
OS-release: 2.6.32-431.el6.x86_64
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8

xarray: 0.10.0
pandas: 0.20.2
numpy: 1.13.1
scipy: 0.19.1
netCDF4: 1.2.4
h5netcdf: None
Nio: None
bottleneck: 1.2.1
cyordereddict: None
dask: 0.16.0
matplotlib: 2.0.2
cartopy: 0.15.1
seaborn: None
setuptools: 27.2.0
pip: 9.0.1
conda: 4.3.30
pytest: None
IPython: None
sphinx: None

>>> xr.open_dataarray('ww3.Hs.July.NPac.nc')
Segmentation fault (core dumped)
</code>```

On my Mac:

```<code>$ nc-config --version
netCDF 4.4.1

xr.show_versions()
INSTALLED VERSIONS
------------------
commit: None
python: 3.6.3.final.0
python-bits: 64
OS: Darwin
OS-release: 17.2.0
machine: x86_64
processor: i386
byteorder: little
LC_ALL: en_US.UTF-8
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8

xarray: 0.10.0
pandas: 0.20.1
numpy: 1.12.1
scipy: 1.0.0
netCDF4: 1.2.4
h5netcdf: None
Nio: None
bottleneck: 1.2.1
cyordereddict: None
dask: 0.16.0
matplotlib: 2.1.0
cartopy: 0.15.1
seaborn: 0.8.1
setuptools: 36.2.7
pip: 9.0.1
conda: 4.3.29
pytest: 3.2.0
IPython: 6.2.1
sphinx: 1.5.6

In [10]:xr.open_dataarray('ww3.Hs.July.NPac.nc')
Out[10]:
<xarray.DataArray 'hs' (time: 31, latitude: 66, longitude: 191)>
[390786 values with dtype=float64]
Coordinates:
  * latitude   (latitude) float32 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 ...
  * longitude  (longitude) float32 100.0 101.0 102.0 103.0 104.0 105.0 106.0 ...
  * time       (time) datetime64[ns] 2013-07-01 2013-07-02 2013-07-03 ...
Attributes:
    long_name:      significant height of wind and swell waves
    standard_name:  sea_surface_wave_significant_height
    globwave_name:  significant_wave_height
    units:          m
    valid_min:      0
    valid_max:      32000
</code>```

答:
Apologies. It looks like my ncks command wasn't completing property. Nothing to do with xarray just strange my Mac wasn't throwing up an error. Stranger still that giving out.nc a different file name seems to fix it

```<code>$ncks -O -d longitude,100.0,290.0 -d latitude,0.0,65.0 ww3.Hs.July.nc ww3.Hs.July.NPac.nc
$python
>>>import xarray as xr
>>>xr.open_dataarray('ww3.Hs.July.NPac.nc')
Segmentation fault (core dumped)

$ncks -O -d longitude,100.0,290.0 -d latitude,0.0,65.0 ww3.Hs.July.nc ww3.Hs.July.NPac1.nc
$python
>>>import xarray as xr
>>>xr.open_dataarray('ww3.Hs.July.NPac1.nc')
<xarray.DataArray 'hs' (time: 31, latitude: 66, longitude: 191)>
[390786 values with dtype=float64]
Coordinates:
  * latitude   (latitude) float32 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 ...
  * longitude  (longitude) float32 100.0 101.0 102.0 103.0 104.0 105.0 106.0 ...
  * time       (time) datetime64[ns] 1993-07-01 1993-07-02 1993-07-03 ...
Attributes:
    long_name:      significant height of wind and swell waves
    standard_name:  sea_surface_wave_significant_height
    globwave_name:  significant_wave_height
    units:          m
    valid_min:      0
    valid_max:      32000
</code>```

Body:
I'm struggling to understand why reading in a NetCDF file using open_dataarray in the HPC I use produces a Segmentation fault (core dumped). However, when I read in the file using open_dataarray on my Mac it works fine.

From looking into this further it is the NPac file (the sub-section) which I created which seems to have issues. Here is the steps I took to generate the file:

WaveWatchIII outputs a file

Extract July: $ncks -d time,0,30 in.nc out.nc Can open out.nc in HPC

Extract variable: $ncks -v hs in.nc out.nc Can open out.nc in HPC

Extract domain: $ncks -d longitude,100.0,290.0 -d latitude,0.0,65.0 in.nc out.nc Cannot open out.nc on HPC but can open out.nc on Mac.

This is the first time i've seen this issue and I believe it is due to properties of the domain of the NetCDF file. I'm guessing it may have something to do with versions as well? I do most of the heavy lifting on the HPC and use my Mac for testing and understanding so it would be nice to get this working on the HPC.

The NetCDF file can be downloaded here

ncdump -h ww3.Hs.July.NPac.nc
netcdf ww3.Hs.July.NPac {
dimensions:
    time = UNLIMITED ; // (31 currently)
    latitude = 66 ;
    longitude = 191 ;
variables:
    short hs(time, latitude, longitude) ;
            hs:long_name = "significant height of wind and swell waves" ;
            hs:standard_name = "sea_surface_wave_significant_height" ;
            hs:globwave_name = "significant_wave_height" ;
            hs:units = "m" ;
            hs:_FillValue = -32767s ;
            hs:scale_factor = 0.002f ;
            hs:add_offset = 0.f ;
            hs:valid_min = 0 ;
            hs:valid_max = 32000 ;
    float latitude(latitude) ;
            latitude:units = "degree_north" ;
            latitude:long_name = "latitude" ;
            latitude:standard_name = "latitude" ;
            latitude:valid_min = -90.f ;
            latitude:valid_max = 90.f ;
            latitude:axis = "Y" ;
    float longitude(longitude) ;
            longitude:units = "degree_east" ;
            longitude:long_name = "longitude" ;
            longitude:standard_name = "longitude" ;
            longitude:valid_min = -180.f ;
            longitude:valid_max = 180.f ;
            longitude:axis = "X" ;
    double time(time) ;
            time:long_name = "julian day (UT)" ;
            time:standard_name = "time" ;
            time:units = "days since 1850-01-01T00:00:00Z" ;
            time:conventions = "relative julian days with decimal part (as parts of the day )" ;
            time:axis = "T" ;

// global attributes:
            :WAVEWATCH_III_version_number = "4.18b" ;
            :WAVEWATCH_III_switches = "NC4 F90 NOGRB NOPA LRB4 SHRD PR3 UQ FLX0 LN1 ST4 STAB0 NL1 BT1 DB1 MLIM TR0 BS0 IC0 REF0 XX0 WNT1 WNX1 CRT1 CRX1 O0 O1 O2 O3 O4 O5 O6 O7 O11 O14 TRKNC" ;
            :SDS4\ namelist\ parameter\ WHITECAPWIDTH = 0.3f ;
            :product_name = "ww3.199307.nc" ;
            :area = "Indian Ocean Pacfic 1 degree" ;
            :latitude_resolution = "   1.0000000" ;
            :longitude_resolution = "   1.0000000" ;
            :southernmost_latitude = "-70.0000000" ;
            :northernmost_latitude = "65.0000000" ;
            :westernmost_longitude = "20.0000000" ;
            :easternmost_longitude = "295.0000000" ;
            :minimum_altitude = "-12000 m" ;
            :maximum_altitude = "9000 m" ;
            :altitude_resolution = "n/a" ;
            :start_date = "1993-07-01T00:00:00Z" ;
            :stop_date = "1993-07-31T00:00:00Z" ;
            :history = "Sat Dec  2 17:53:06 2017: ncks -O -d longitude,100.0,290.0 -d latitude,0.0,65.0 /projects/rsmas/kirtman/rxb826/WW3exps/IO_Pac_CCSM4/CCSM4_19930701_19940630_1a1/work/ww3.Hs.July.nc /projects/rsmas/kirtman/rxb826/WW3exps/IO_Pac_CCSM4/CCSM4_19930701_19940630_1a1/work/ww3.Hs.July.NPac.nc\nSat Dec  2 17:53:06 2017: ncks -O -v hs /projects/rsmas/kirtman/rxb826/WW3exps/IO_Pac_CCSM4/CCSM4_19930701_19940630_1a1/work/ww3.July.nc /projects/rsmas/kirtman/rxb826/WW3exps/IO_Pac_CCSM4/CCSM4_19930701_19940630_1a1/work/ww3.Hs.July.nc\nSat Dec  2 17:53:05 2017: ncks -O -d time,0,30 /projects/rsmas/kirtman/rxb826/WW3exps/IO_Pac_CCSM4/CCSM4_19930701_19940630_1a1/work/ww3.19930701_19940630.nc /projects/rsmas/kirtman/rxb826/WW3exps/IO_Pac_CCSM4/CCSM4_19930701_19940630_1a1/work/ww3.July.nc\nFri Nov  4 13:50:57 2016: ncrcat -O -o tmp.nc ww3.199307.nc ww3.199308.nc ww3.199309.nc ww3.199310.nc ww3.199311.nc ww3.199312.nc ww3.199401.nc ww3.199402.nc ww3.199403.nc ww3.199404.nc ww3.199405.nc ww3.199406.nc" ;
            :nco_openmp_thread_number = 1 ;
            :NCO = "4.3.7" ;

On the HPC:

$ nc-config --version
netCDF 4.2.1.1

>>> xr.show_versions()
INSTALLED VERSIONS
------------------
commit: None
python: 3.6.3.final.0
python-bits: 64
OS: Linux
OS-release: 2.6.32-431.el6.x86_64
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8

xarray: 0.10.0
pandas: 0.20.2
numpy: 1.13.1
scipy: 0.19.1
netCDF4: 1.2.4
h5netcdf: None
Nio: None
bottleneck: 1.2.1
cyordereddict: None
dask: 0.16.0
matplotlib: 2.0.2
cartopy: 0.15.1
seaborn: None
setuptools: 27.2.0
pip: 9.0.1
conda: 4.3.30
pytest: None
IPython: None
sphinx: None

>>> xr.open_dataarray('ww3.Hs.July.NPac.nc')
Segmentation fault (core dumped)

On my Mac:

$ nc-config --version
netCDF 4.4.1

xr.show_versions()
INSTALLED VERSIONS
------------------
commit: None
python: 3.6.3.final.0
python-bits: 64
OS: Darwin
OS-release: 17.2.0
machine: x86_64
processor: i386
byteorder: little
LC_ALL: en_US.UTF-8
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8

xarray: 0.10.0
pandas: 0.20.1
numpy: 1.12.1
scipy: 1.0.0
netCDF4: 1.2.4
h5netcdf: None
Nio: None
bottleneck: 1.2.1
cyordereddict: None
dask: 0.16.0
matplotlib: 2.1.0
cartopy: 0.15.1
seaborn: 0.8.1
setuptools: 36.2.7
pip: 9.0.1
conda: 4.3.29
pytest: 3.2.0
IPython: 6.2.1
sphinx: 1.5.6

In [10]:xr.open_dataarray('ww3.Hs.July.NPac.nc')
Out[10]:
<xarray.DataArray 'hs' (time: 31, latitude: 66, longitude: 191)>
[390786 values with dtype=float64]
Coordinates:
  * latitude   (latitude) float32 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 ...
  * longitude  (longitude) float32 100.0 101.0 102.0 103.0 104.0 105.0 106.0 ...
  * time       (time) datetime64[ns] 2013-07-01 2013-07-02 2013-07-03 ...
Attributes:
    long_name:      significant height of wind and swell waves
    standard_name:  sea_surface_wave_significant_height
    globwave_name:  significant_wave_height
    units:          m
    valid_min:      0
    valid_max:      32000

Body:
Apologies. It looks like my ncks command wasn't completing property. Nothing to do with xarray just strange my Mac wasn't throwing up an error. Stranger still that giving out.nc a different file name seems to fix it

$ncks -O -d longitude,100.0,290.0 -d latitude,0.0,65.0 ww3.Hs.July.nc ww3.Hs.July.NPac.nc
$python
>>>import xarray as xr
>>>xr.open_dataarray('ww3.Hs.July.NPac.nc')
Segmentation fault (core dumped)

$ncks -O -d longitude,100.0,290.0 -d latitude,0.0,65.0 ww3.Hs.July.nc ww3.Hs.July.NPac1.nc
$python
>>>import xarray as xr
>>>xr.open_dataarray('ww3.Hs.July.NPac1.nc')
<xarray.DataArray 'hs' (time: 31, latitude: 66, longitude: 191)>
[390786 values with dtype=float64]
Coordinates:
  * latitude   (latitude) float32 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 ...
  * longitude  (longitude) float32 100.0 101.0 102.0 103.0 104.0 105.0 106.0 ...
  * time       (time) datetime64[ns] 1993-07-01 1993-07-02 1993-07-03 ...
Attributes:
    long_name:      significant height of wind and swell waves
    standard_name:  sea_surface_wave_significant_height
    globwave_name:  significant_wave_height
    units:          m
    valid_min:      0
    valid_max:      32000


问:
How to use Geolocation Plugin getCurrentPostion based on GPS
when I use Geolocation Plugin getCurrentPostion , it has problem
sometimes it get location based on WIFI, but i want to get postion based on GPS (if on handy)
how to do this settings?
any hints well be more than welcom!

import { Geolocation } from ‘@ionic-native/geolocation’;

…

constructor(private geolocation: Geolocation) {}

…

this.geolocation.getCurrentPosition().then((resp) => {
// resp.coords.latitude
// resp.coords.longitude
}).catch((error) => {
console.log(‘Error getting location’, error);
});

let watch = this.geolocation.watchPosition();
watch.subscribe((data) => {
// data can be a set of coordinates, or an error (if an error occurred).
// data.coords.latitude
// data.coords.longitude
});```

答:
it was working well on my handy but just recently it start to use wifi for currentlocation instead of gps. i am not aware of what i did to my handy.
i will try to enahble highaccuracy on api to see if it helps</p>


问:
clang-format add inconsistent line break in function declaration
I like to use clang-format on a large code base for C/C++.

I don't understand why clang-format is sometimes giving me this inconsistent format

```<code>virtual void someReallyLongFunctionName(
    float* aaaaa, float* aaaaaaaaaaaaa, float* bbbbb, float* bbbbb, float* bbbbbbb, int* ccccc, int* cccccc,
    int* ccccc, float* cccccccc, float* cccccccc, float* ccccccc, float* ccccccccc, float* cccccc, float* ccccccccc,
    float* ccccccccccc, float* c, float* ccc, float* ccccc, float* ccccc, int* cccc, float* dddddddddddddddddddddd,
    float* ddddd, float* dddd, float* ffffffffffff, int* fffffff, float* fffffff, float* ffffffffffffffffffffff,
    int* ffffff, int* fffff, int* fffffffffffffff, int ffsddffffffffff, float* aaaaaaaaaaaaaaaa,
    float* aaaaaaaaaaaa, int* aaaaaaaaaaaa, logical* aaaaa, float* bbbbbbbbb) const = 0;

virtual void shortName(float* aaaaa, float* aaaaaaaaaaaaa, float* bbbbb, float* bbbbb, float* bbbbbbb, int* ccccc,
                       int* cccccc, int* ccccc, float* cccccccc, float* cccccccc, float* ccccccc, float* ccccccccc,
                       float* cccccc, float* ccccccccc, float* ccccccccccc, float* c, float* ccc, float* ccccc,
                       float* ccccc, int* cccc, float* dddddddddddddddddddddd, float* ddddd, float* dddd,
                       float* ffffffffffff, int* fffffff, float* fffffff, float* ffffffffffffffffffffff,
                       int* ffffff, int* fffff, int* fffffffffffffff, int ffsddffffffffff, float* aaaaaaaaaaaaaaaa,
                       float* aaaaaaaaaaaa, int* aaaaaaaaaaaa, logical* aaaaa, float* bbbbbbbbb) const = 0
</code>```

I used clang-format -style="{BasedOnStyle: Google, ColumnLimit: 120, IndentWidth: 4}", version 4.0.0.

Which switch or penalty value can I use to enforce that also someReallyLongFunctionName looks like this

```<code>virtual void someReallyLongFunctionName(float* aaaaa, float* aaaaaaaaaaaaa, ...
</code>```

and no additional line break is introduced.

I know that the interface is violating the c++ core guidelines. Nevertheless, this legacy code shall be formated consistently.

答: AlignAfterOpenBracket: DontAlign is enforcing the desired behaviour.

Body:
I like to use clang-format on a large code base for C/C++.

I don't understand why clang-format is sometimes giving me this inconsistent format

virtual void someReallyLongFunctionName(
    float* aaaaa, float* aaaaaaaaaaaaa, float* bbbbb, float* bbbbb, float* bbbbbbb, int* ccccc, int* cccccc,
    int* ccccc, float* cccccccc, float* cccccccc, float* ccccccc, float* ccccccccc, float* cccccc, float* ccccccccc,
    float* ccccccccccc, float* c, float* ccc, float* ccccc, float* ccccc, int* cccc, float* dddddddddddddddddddddd,
    float* ddddd, float* dddd, float* ffffffffffff, int* fffffff, float* fffffff, float* ffffffffffffffffffffff,
    int* ffffff, int* fffff, int* fffffffffffffff, int ffsddffffffffff, float* aaaaaaaaaaaaaaaa,
    float* aaaaaaaaaaaa, int* aaaaaaaaaaaa, logical* aaaaa, float* bbbbbbbbb) const = 0;

virtual void shortName(float* aaaaa, float* aaaaaaaaaaaaa, float* bbbbb, float* bbbbb, float* bbbbbbb, int* ccccc,
                       int* cccccc, int* ccccc, float* cccccccc, float* cccccccc, float* ccccccc, float* ccccccccc,
                       float* cccccc, float* ccccccccc, float* ccccccccccc, float* c, float* ccc, float* ccccc,
                       float* ccccc, int* cccc, float* dddddddddddddddddddddd, float* ddddd, float* dddd,
                       float* ffffffffffff, int* fffffff, float* fffffff, float* ffffffffffffffffffffff,
                       int* ffffff, int* fffff, int* fffffffffffffff, int ffsddffffffffff, float* aaaaaaaaaaaaaaaa,
                       float* aaaaaaaaaaaa, int* aaaaaaaaaaaa, logical* aaaaa, float* bbbbbbbbb) const = 0

I used clang-format -style="{BasedOnStyle: Google, ColumnLimit: 120, IndentWidth: 4}", version 4.0.0.

Which switch or penalty value can I use to enforce that also someReallyLongFunctionName looks like this

virtual void someReallyLongFunctionName(float* aaaaa, float* aaaaaaaaaaaaa, ...

and no additional line break is introduced.

I know that the interface is violating the c++ core guidelines. Nevertheless, this legacy code shall be formated consistently.


问:
Linq update a row in db
I have this function:

```<code>//change user password
void chgPass(string username, string old_password, string new_password)
{
    var result = (from l in this.dbLogin.SLN
                 where l.user_id.Equals(username)
                 where l.password.Equals(old_password)
                 select l).First();

    result.password= new_password;

    dbLogin.SubmitChanges();
}
</code>```

I call it like this:

```<code>this.loginClient.chgPassAsync(user, old_password, new_password);
</code>```

Can someone tell me why no changes are maded when I run this... in debuge mode I can see that password field is changed, but when I look in db password isn't changed.

答:
Does your SLN table has a primary key? if not then try to set one, according to my test LINQ wont update an entity without having PK in the table it belongs to

please check this too

Title: Linq update a row in db

Body:
I have this function:

//change user password
void chgPass(string username, string old_password, string new_password)
{
    var result = (from l in this.dbLogin.SLN
                 where l.user_id.Equals(username)
                 where l.password.Equals(old_password)
                 select l).First();

    result.password= new_password;

    dbLogin.SubmitChanges();
}

I call it like this:

this.loginClient.chgPassAsync(user, old_password, new_password);

Can someone tell me why no changes are maded when I run this... in debuge mode I can see that password field is changed, but when I look in db password isn't changed.


问:
Best option for i18n with create-react-app (react / router / redux / typescript)
I used create-react-app-ts to create a new React app. What is the best option for adding i18n?

I looked at react-intl but it looks quite heavy to work with. Then I looked at linguiJS which promises to make it easier, but I can not find examples of how to use it with create-react-app. Also I'm not sure it's a good idea to have both formatting (of numbers etc), pluralization and translation in one module... I would prefer to use separate libraries...

Please share your thoughts. What is the best (easiest/prettiest) way to get i18n in react apps.

Thanks

答:
with redux just use both providers (if not using react-i18next without provider - which i like more):

```<code>export default function App({ store }) {
  return (
    <I18nextProvider i18n={i18n}>
      <Provider store={store}>
        <YourRootComponent />
      </Provider>
    </I18nextProvider>
  );
}
</code>```

And compose both the translate hoc and redux connect in your component:

```<code>export default compose(
  translate('namespace', { wait: true }),
  connect(mapStateToProps, mapDispatchToProps),
)(YourComponent);
</code>```

Body:
with redux just use both providers (if not using react-i18next without provider - which i like more):

export default function App({ store }) {
  return (
    <I18nextProvider i18n={i18n}>
      <Provider store={store}>
        <YourRootComponent />
      </Provider>
    </I18nextProvider>
  );
}

And compose both the translate hoc and redux connect in your component:

export default compose(
  translate('namespace', { wait: true }),
  connect(mapStateToProps, mapDispatchToProps),
)(YourComponent);