问:
Possible to exclude subfolder from https rewrite?
I have a webiste that runs https. Now some programmers need a subfoder that has no https.

This is what i have in my web.config right now:

```<code><rule name="HTTP Redirect to HTTPS" enabled="true" stopProcessing="true">
    <match url="(.*)" ignoreCase="false" />
    <conditions>
        <add input="{HTTPS}" pattern="off" />
    </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
</rule>
</code>```

We need the folder "wp-content\rest" to be excluded from this https redirect.

In hope someone can help me with this one.

答:
You need to add an additional condition into your rule:

```<code><rule name="HTTP Redirect to HTTPS" enabled="true" stopProcessing="true">
    <match url="(.*)" ignoreCase="false" />
    <conditions>
        <add input="{HTTPS}" pattern="off" />
        <add input="{REQUEST_URI}" pattern="^/wp-content/rest" negate="true" />
    </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
</rule>
</code>```

Then this rule will disable redirects to all urls like that http://www.example.com/wp-content/rest*

Body:
I have a webiste that runs https. Now some programmers need a subfoder that has no https.

This is what i have in my web.config right now:

<rule name="HTTP Redirect to HTTPS" enabled="true" stopProcessing="true">
    <match url="(.*)" ignoreCase="false" />
    <conditions>
        <add input="{HTTPS}" pattern="off" />
    </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
</rule>

We need the folder "wp-content\rest" to be excluded from this https redirect.

In hope someone can help me with this one.

Body:
You need to add an additional condition into your rule:

<rule name="HTTP Redirect to HTTPS" enabled="true" stopProcessing="true">
    <match url="(.*)" ignoreCase="false" />
    <conditions>
        <add input="{HTTPS}" pattern="off" />
        <add input="{REQUEST_URI}" pattern="^/wp-content/rest" negate="true" />
    </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
</rule>

Then this rule will disable redirects to all urls like that http://www.example.com/wp-content/rest*


来源: stackexchange

问:
Driver:com.mysql.jdbc.Driver@2b7374f8 returned null for URL
I am a beginner in JAVA.
I am trying to connect remote mySQL database to my Java code.

I am getting following error:

```<code>    2017-07-09 17:29:04.283 ERROR 38768 --- [lication.main()] org.hibernate.tool.hbm2ddl.SchemaUpdate  : HHH000319: Could not get database metadata

java.sql.SQLException: Driver:com.mysql.jdbc.Driver@2b7374f8 returned null for URL:jdbc:mysql:sg2plcpnl9557.produc.sin1.secure.net:3312/abc
    at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:326)
    at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:200)
    at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:699)
    at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:633)
    at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:484)
    at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:142)
    at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:115)
    at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:102)
    at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:126)
    at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:139)
    at org.hibernate.tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.prepare(SuppliedConnectionProviderConnectionHelper.java:51)
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:219)
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:203)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:522)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1859)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:425)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:849)
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
    at com.home.Application.main(Application.java:10)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.boot.maven.RunMojo$LaunchRunner.run(RunMojo.java:418)
    at java.lang.Thread.run(Thread.java:745)

2017-07-09 17:29:04.284 ERROR 38768 --- [lication.main()] org.hibernate.tool.hbm2ddl.SchemaUpdate  : HHH000299: Could not complete schema update

java.sql.SQLException: Driver:com.mysql.jdbc.Driver@2b7374f8 returned null for URL:jdbc:mysql:sg2plcpnl9557.produc.sin1.secure.net:3312/abc
    at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:326)
    at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:200)
    at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:699)
    at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:633)
    at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:484)
    at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:142)
    at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:115)
    at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:102)
    at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:126)
    at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:139)
    at org.hibernate.tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.prepare(SuppliedConnectionProviderConnectionHelper.java:51)
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:219)
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:203)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:522)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1859)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:425)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:849)
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
    at com.home.Application.main(Application.java:10)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.boot.maven.RunMojo$LaunchRunner.run(RunMojo.java:418)
    at java.lang.Thread.run(Thread.java:745)
</code>```

This is my properties file:

```<code>    server.port=8090
#Basic Spring Boot Config for Oracle
spring.datasource.url= jdbc:mysql:sg2plcpnl9557.produc.sin1.secure.net:3312/abc
spring.datasource.username=abc
spring.datasource.password=12345
spring.datasource.driverClassName=com.mysql.jdbc.Driver
#spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#hibernate config
#spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
</code>```

and my dependency in pom.xml is:

```<code><dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
</dependency>
</code>```

答:
Your JDBC url is not in a format recognized by the MySQL Connector/J driver, so it is rejected by returning null as described in java.sql.Driver.connect:

Attempts to make a database connection to the given URL. The driver
  should return "null" if it realizes it is the wrong kind of driver to
  connect to the given URL. This will be common, as when the JDBC driver
  manager is asked to connect to a given URL it passes the URL to each
  loaded driver in turn.

As documented in the MySQL Connector/J documentation, the format of the URL for the MySQL Connector/J driver is:

jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]] »
[?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]
```
</blockquote>

<p>Your URL should at minimum be:</p>

<pre class="lang-none prettyprint-override"><code>jdbc:mysql://sg2plcpnl9557.produc.sin1.secure.net:3312/abc
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am a beginner in JAVA.
I am trying to connect remote mySQL database to my Java code.

I am getting following error:

    2017-07-09 17:29:04.283 ERROR 38768 --- [lication.main()] org.hibernate.tool.hbm2ddl.SchemaUpdate  : HHH000319: Could not get database metadata

java.sql.SQLException: Driver:com.mysql.jdbc.Driver@2b7374f8 returned null for URL:jdbc:mysql:sg2plcpnl9557.produc.sin1.secure.net:3312/abc
    at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:326)
    at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:200)
    at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:699)
    at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:633)
    at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:484)
    at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:142)
    at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:115)
    at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:102)
    at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:126)
    at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:139)
    at org.hibernate.tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.prepare(SuppliedConnectionProviderConnectionHelper.java:51)
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:219)
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:203)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:522)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1859)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:425)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:849)
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
    at com.home.Application.main(Application.java:10)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.boot.maven.RunMojo$LaunchRunner.run(RunMojo.java:418)
    at java.lang.Thread.run(Thread.java:745)

2017-07-09 17:29:04.284 ERROR 38768 --- [lication.main()] org.hibernate.tool.hbm2ddl.SchemaUpdate  : HHH000299: Could not complete schema update

java.sql.SQLException: Driver:com.mysql.jdbc.Driver@2b7374f8 returned null for URL:jdbc:mysql:sg2plcpnl9557.produc.sin1.secure.net:3312/abc
    at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:326)
    at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:200)
    at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:699)
    at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:633)
    at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:484)
    at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:142)
    at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:115)
    at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:102)
    at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:126)
    at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:139)
    at org.hibernate.tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.prepare(SuppliedConnectionProviderConnectionHelper.java:51)
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:219)
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:203)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:522)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1859)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:425)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:849)
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
    at com.home.Application.main(Application.java:10)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.boot.maven.RunMojo$LaunchRunner.run(RunMojo.java:418)
    at java.lang.Thread.run(Thread.java:745)

This is my properties file:

    server.port=8090
#Basic Spring Boot Config for Oracle
spring.datasource.url= jdbc:mysql:sg2plcpnl9557.produc.sin1.secure.net:3312/abc
spring.datasource.username=abc
spring.datasource.password=12345
spring.datasource.driverClassName=com.mysql.jdbc.Driver
#spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#hibernate config
#spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

and my dependency in pom.xml is:

<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
</dependency>

Body:
Your JDBC url is not in a format recognized by the MySQL Connector/J driver, so it is rejected by returning null as described in java.sql.Driver.connect:

Attempts to make a database connection to the given URL. The driver
  should return "null" if it realizes it is the wrong kind of driver to
  connect to the given URL. This will be common, as when the JDBC driver
  manager is asked to connect to a given URL it passes the URL to each
  loaded driver in turn.

As documented in the MySQL Connector/J documentation, the format of the URL for the MySQL Connector/J driver is:

jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]] »
[?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]

Your URL should at minimum be:

jdbc:mysql://sg2plcpnl9557.produc.sin1.secure.net:3312/abc


问:
scala play framework json conversion
I have two case classes A and B. I need to create Json object conditionally

Json.toJson(if (cond) A else B)

if (cond) Json.toJson(A) else Json.toJson(B)

Statement 1 does not compile but statement 2 does. What is the reason behind this?

答:
The signature of toJson(...) is:

```<code> toJson[T](o: T)(implicit tjs: Writes[T]): JsValue
</code>```

That means that there must be an implicit Writes in scope for the type of argument T.

Now, the type of the expression if (cond) A else B is the common super type of the respective types of values A and B.

For types that don't explicitly inherit from the same base class the common super type will be Scala's Any. There is no implicit Writes for Any (because what is the JSON representation of anything?) so you'll get an "implicit not found" error at compile time.

On the other hand, each branch of the conditional in statement 2 evaluates to JsValue, so that is the value of the expression.

Title: scala play framework json conversion

Body:
The signature of toJson(...) is:

 toJson[T](o: T)(implicit tjs: Writes[T]): JsValue

That means that there must be an implicit Writes in scope for the type of argument T.

Now, the type of the expression if (cond) A else B is the common super type of the respective types of values A and B.

For types that don't explicitly inherit from the same base class the common super type will be Scala's Any. There is no implicit Writes for Any (because what is the JSON representation of anything?) so you'll get an "implicit not found" error at compile time.

On the other hand, each branch of the conditional in statement 2 evaluates to JsValue, so that is the value of the expression.


问:
Progress-bar MVVM?
I am having a little bit of trouble getting a ProgressBar to work. When I start it up, nothing happens and I can't see why?

I thought that this would start the task worker.RunWorkerAsync();

The below example should be able to be copied and pasted into a new solution and be run for testing if needed.

The XAML,

```<code><Grid Margin="20">
    <ProgressBar
        Height="60"
        Minimum="0"
        Maximum="100"
        Value="{Binding Progress, Mode=OneWay}"
        Visibility="{Binding ProgressVisibility}"/>
</Grid>
</code>```

My code,

```<code>public partial class MainWindow : Window
{
    public ProggressbarViewModel PsVm { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        PsVm = new ProggressbarViewModel();
    }

    public class ProggressbarViewModel
    {
        public ProggressbarViewModel()
        {
            var worker = new BackgroundWorker();
            worker.DoWork += DoWork;
            worker.ProgressChanged += ProgressChanged;
            worker.RunWorkerAsync();
        }

        private int _progress;

        public int Progress
        {
            get { return _progress; }
            set
            {
                if (_progress == value) return;
                _progress = value;
                OnPropertyChanged();
            }
        }

        private void DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 0; i < 100; i++)
            {
                Thread.Sleep(100);
                _progress = i;
                OnPropertyChanged();
            }
        }

        private void ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            Progress = e.ProgressPercentage;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
</code>```

Any help would be much appreciated.

EDIT: The question is is similar possibly a duplicate in that sense, however the linked answer did not solve my problem, like it states in the Duplicate banner.

答:
When you're not explicitly indicating source object for your bindings (by means of Binding.Source or Binding.RelativeSource properties), the framework uses (possibly inherited) value of DataContext of the target object as the source. The problem is that you don't assign your view-model to the DataContext property of any control. Thus, the source for the bindings resolves to null and nothing is showing on your progress bar.

To resolve your issue you should assign your view model to the DataContext of your MainWindow:

```<code>public MainWindow()
{
    InitializeComponent();
    PsVm = new ProggressbarViewModel();
    DataContext = PsVm;
}
</code>```

If however you're planning on using different DataContext for your window, you can bind DataContext of ProgressBar:

```<code><ProgressBar
    DataContext="{Binding Path=PsVm,
                          RelativeSource={RelativeSource AncestorType=local:MainWindow}}"
    (...) />
</code>```

You could also modify particular bindings by prepending PsVm. to the value of Path and using RelativeSource, e.g.:

```<code> Value="{Binding Path=PsVm.Progress,
                 RelativeSource={RelativeSource AncestorType=local:MainWindow},
                 Mode=OneWay}"
</code>```

In that case however you'd have to modify each binding, so previous solutions are quicker and/or simpler.

As a side note, you might also want to change the way you're reporting progress - note that OnPropertyChanged in your DoWork method is not called from UI thread. The proper way to do it would be:

```<code>private void DoWork(object sender, DoWorkEventArgs e)
{
    var worker = (BackgroundWorker)sender;
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(100);
        worker.ReportProgress(i); //This will raise BackgroundWorker.ProgressChanged
    }
}
</code>```

Also, in order to support progress reporting, you should set WorkerReportsProgress to true on your worker, e.g.:

```<code>var worker = new BackgroundWorker { WorkerReportsProgress = true };
</code>```

Title: Progress-bar MVVM?

Body:
I am having a little bit of trouble getting a ProgressBar to work. When I start it up, nothing happens and I can't see why?

I thought that this would start the task worker.RunWorkerAsync();

The below example should be able to be copied and pasted into a new solution and be run for testing if needed.

The XAML,

<Grid Margin="20">
    <ProgressBar
        Height="60"
        Minimum="0"
        Maximum="100"
        Value="{Binding Progress, Mode=OneWay}"
        Visibility="{Binding ProgressVisibility}"/>
</Grid>

My code,

public partial class MainWindow : Window
{
    public ProggressbarViewModel PsVm { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        PsVm = new ProggressbarViewModel();
    }

    public class ProggressbarViewModel
    {
        public ProggressbarViewModel()
        {
            var worker = new BackgroundWorker();
            worker.DoWork += DoWork;
            worker.ProgressChanged += ProgressChanged;
            worker.RunWorkerAsync();
        }

        private int _progress;

        public int Progress
        {
            get { return _progress; }
            set
            {
                if (_progress == value) return;
                _progress = value;
                OnPropertyChanged();
            }
        }

        private void DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 0; i < 100; i++)
            {
                Thread.Sleep(100);
                _progress = i;
                OnPropertyChanged();
            }
        }

        private void ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            Progress = e.ProgressPercentage;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Any help would be much appreciated.

EDIT: The question is is similar possibly a duplicate in that sense, however the linked answer did not solve my problem, like it states in the Duplicate banner.

Body:
When you're not explicitly indicating source object for your bindings (by means of Binding.Source or Binding.RelativeSource properties), the framework uses (possibly inherited) value of DataContext of the target object as the source. The problem is that you don't assign your view-model to the DataContext property of any control. Thus, the source for the bindings resolves to null and nothing is showing on your progress bar.

To resolve your issue you should assign your view model to the DataContext of your MainWindow:

public MainWindow()
{
    InitializeComponent();
    PsVm = new ProggressbarViewModel();
    DataContext = PsVm;
}

If however you're planning on using different DataContext for your window, you can bind DataContext of ProgressBar:

<ProgressBar
    DataContext="{Binding Path=PsVm,
                          RelativeSource={RelativeSource AncestorType=local:MainWindow}}"
    (...) />

You could also modify particular bindings by prepending PsVm. to the value of Path and using RelativeSource, e.g.:

 Value="{Binding Path=PsVm.Progress,
                 RelativeSource={RelativeSource AncestorType=local:MainWindow},
                 Mode=OneWay}"

In that case however you'd have to modify each binding, so previous solutions are quicker and/or simpler.

As a side note, you might also want to change the way you're reporting progress - note that OnPropertyChanged in your DoWork method is not called from UI thread. The proper way to do it would be:

private void DoWork(object sender, DoWorkEventArgs e)
{
    var worker = (BackgroundWorker)sender;
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(100);
        worker.ReportProgress(i); //This will raise BackgroundWorker.ProgressChanged
    }
}

Also, in order to support progress reporting, you should set WorkerReportsProgress to true on your worker, e.g.:

var worker = new BackgroundWorker { WorkerReportsProgress = true };


答:
Fix you connection first:

The correct one is:

```<code>spring.datasource.url=jdbc:mysql://sg2plcpnl9557.produc.sin1.secure.net:3312/abc
</code>```

Title: Driver:com.mysql.jdbc.Driver@2b7374f8 returned null for URL

Body:
Fix you connection first:

The correct one is:

spring.datasource.url=jdbc:mysql://sg2plcpnl9557.produc.sin1.secure.net:3312/abc


问:
How to get Year and Month of a DATE using Oracle
How can I get the year and month of a date in the where clause using Oracle.

I used to be working with SQL server and it was as simple as YEAR(FIELDNAME) and MONTH(FIELDNAME).

I have tried the following:

```<code>SELECT *
FROM myschema.mytablename
WHERE   EXTRACT(YEAR FROM  myDATE)  = 2017
</code>```

however it gives ORA-30076 Error

答:
Your query should work, but a better alternative would be

```<code>SELECT *
  FROM YOUR_TABLE
  WHERE MY_DATE BETWEEN TO_DATE('01-JAN-2017', 'DD-MON-YYYY')
                    AND TO_DATE('01-JAN-2018', 'DD-MON-YYYY') - INTERVAL '1' SECOND
</code>```

Best of luck.

Body:
How can I get the year and month of a date in the where clause using Oracle.

I used to be working with SQL server and it was as simple as YEAR(FIELDNAME) and MONTH(FIELDNAME).

I have tried the following:

SELECT *
FROM myschema.mytablename
WHERE   EXTRACT(YEAR FROM  myDATE)  = 2017

however it gives ORA-30076 Error

Body:
Your query should work, but a better alternative would be

SELECT *
  FROM YOUR_TABLE
  WHERE MY_DATE BETWEEN TO_DATE('01-JAN-2017', 'DD-MON-YYYY')
                    AND TO_DATE('01-JAN-2018', 'DD-MON-YYYY') - INTERVAL '1' SECOND

Best of luck.


问:
How to compile F# library from another F# program
I want to make my Application configuration as F# file wich will be compiled to dll. (like XMonad configuration with xmonad.hs on haskell). I found it more interesting and just better way then using XML serialization.

So is there any way how can I compile single file (or more) to Library with some configuration like

```<code>module RNExcel.Repository

open RNExcel.Model

    type ExpenseReportRepository() =
        member x.GetAll() =
            seq{ yield {Name="User1"
                        Role="someRole"
                        Password = "123321"
                        ExpenseLineItems =
                            [{ExpenseType="Item1"
                              ExpenseAmount="50"};
                             {ExpenseType="Item2"
                              ExpenseAmount="50"}]}
                 yield {Name="User2"
                        Role="Estimator"
                        Password = "123123"
                        ExpenseLineItems =
                            [{ExpenseType="Item1"
                              ExpenseAmount="50"};
                             {ExpenseType="Item2"
                              ExpenseAmount="125"}]}    }
</code>```

my idea was to run shell .... and msbuild the project , but I don't think it will works for every user with .net 4

答:
I think that using CodeDOM provider from the PowerPack as Ben suggested is a way to go. I'd just like to add a few things (and it didn't fit into the comment box).

To parse and compile the F# code with the configuration, you need just to compile the source file that the users write using F# PowerPack. The compilation part of PowerPack is complete and works just fine. It invokes the F# compiler under the cover and gives you the compiled assembly back. The only problem is that the users of your application will need to have F# compiler installed (and not just the redist).

The incomplete part of F# CodeDOM provider is generating F# code from CodeDOM trees (because the trees were not designed to support F#), but that's not needed in this case.

ContentLicense: CC BY-SA 2.5

Body:
I want to make my Application configuration as F# file wich will be compiled to dll. (like XMonad configuration with xmonad.hs on haskell). I found it more interesting and just better way then using XML serialization.

So is there any way how can I compile single file (or more) to Library with some configuration like

module RNExcel.Repository

open RNExcel.Model

    type ExpenseReportRepository() =
        member x.GetAll() =
            seq{ yield {Name="User1"
                        Role="someRole"
                        Password = "123321"
                        ExpenseLineItems =
                            [{ExpenseType="Item1"
                              ExpenseAmount="50"};
                             {ExpenseType="Item2"
                              ExpenseAmount="50"}]}
                 yield {Name="User2"
                        Role="Estimator"
                        Password = "123123"
                        ExpenseLineItems =
                            [{ExpenseType="Item1"
                              ExpenseAmount="50"};
                             {ExpenseType="Item2"
                              ExpenseAmount="125"}]}    }

my idea was to run shell .... and msbuild the project , but I don't think it will works for every user with .net 4


问:
FileProvider and secondary external storage
How can I serve files from the SECONDARY external storage using the FileProvider?

The current implementation of the FileProvider handles only the first directory returned by ContextCompat.getExternalFilesDirs

```<code>...
} else if (TAG_EXTERNAL_FILES.equals(tag)) {
   File[] externalFilesDirs = ContextCompat.getExternalFilesDirs(context, null);
   if (externalFilesDirs.length > 0) {
       target = externalFilesDirs[0];
   }
}
...
</code>```

It seems, that there is no way to define a <path> entry for the FileProvider, that matches the secondary external storage path...

答:
So I ended up doing the following:

Try to create to Uri via FileProvider, If it fails due to:

```<code>java.lang.IllegalArgumentException: Failed to find configured root that contains
</code>```

I'm just creating a regular Uri.

Here's my code:

```<code>try {
        uri = FileProvider.getUriForFile(context,
                MY_AUTHORITY_STRING,
                imageFile);
    } catch (Exception e) {
        CLog.d(TAG, e);
        uri = Uri.fromFile(imageFile);
    }
</code>```

I don't know why, but it's working, the FileProvider can't access the file (As it's in secondary external storage) and then the uri is created successfully in the catch clause.

Weird Google...very weird.

Body:
How can I serve files from the SECONDARY external storage using the FileProvider?

The current implementation of the FileProvider handles only the first directory returned by ContextCompat.getExternalFilesDirs

...
} else if (TAG_EXTERNAL_FILES.equals(tag)) {
   File[] externalFilesDirs = ContextCompat.getExternalFilesDirs(context, null);
   if (externalFilesDirs.length > 0) {
       target = externalFilesDirs[0];
   }
}
...

It seems, that there is no way to define a <path> entry for the FileProvider, that matches the secondary external storage path...

Body:
So I ended up doing the following:

Try to create to Uri via FileProvider, If it fails due to:

java.lang.IllegalArgumentException: Failed to find configured root that contains

I'm just creating a regular Uri.

Here's my code:

try {
        uri = FileProvider.getUriForFile(context,
                MY_AUTHORITY_STRING,
                imageFile);
    } catch (Exception e) {
        CLog.d(TAG, e);
        uri = Uri.fromFile(imageFile);
    }

I don't know why, but it's working, the FileProvider can't access the file (As it's in secondary external storage) and then the uri is created successfully in the catch clause.

Weird Google...very weird.


问:
Angular CLI and TypeScript outDir
I've just worked through the Angular CLI Heroes tutorial here.  I've followed all tutorials and completed the HTTP tutorial.

All great learning about Angular 4 and TypeScript but one thing that struck me throughout the course was the javascript being compiled into the src folder.  It would be nice if there was some "next steps" tutorial about packaging things up for a deployment - but that is potentially outside the scope of Angular.

I want to change this but not 100% sure on everything I need to do.

Ideally it would be to compile to separate folder and include all files necessary to run the website.

I've looked at the tsconfig.json file and added an outDir setting:

```<code>{
  "compilerOptions": {
    "target": "es5",
    "outDir": "../dist/app",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  }
}
</code>```

When I run npm start the code seems to build to the dist folder, but when the application runs, all I get in the browser is Cannot GET /

I am missing a few things including index.html - but I don't know what files I need exactly.  So my questions are:

What files outside of my compiled app folder are required to run the website?

Can I modify the project files to achieve this using Angular CLI?

答:
@Andez,

Angular CLI should have taken care of all of this for you.  Take a look at ng build and it should have taken care of your two questions.

ng  build will take care of this and the content specified in the "apps" key of angular-cli.json will be included in the dist folder

angular-cli.json is the file you need to modify to include all the artefacts you want in the dist folder.

Hope above points you in the right direction

SOJ

Title: Angular CLI and TypeScript outDir

Body:
I've just worked through the Angular CLI Heroes tutorial here.  I've followed all tutorials and completed the HTTP tutorial.

All great learning about Angular 4 and TypeScript but one thing that struck me throughout the course was the javascript being compiled into the src folder.  It would be nice if there was some "next steps" tutorial about packaging things up for a deployment - but that is potentially outside the scope of Angular.

I want to change this but not 100% sure on everything I need to do.

Ideally it would be to compile to separate folder and include all files necessary to run the website.

I've looked at the tsconfig.json file and added an outDir setting:

{
  "compilerOptions": {
    "target": "es5",
    "outDir": "../dist/app",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  }
}

When I run npm start the code seems to build to the dist folder, but when the application runs, all I get in the browser is Cannot GET /

I am missing a few things including index.html - but I don't know what files I need exactly.  So my questions are:

What files outside of my compiled app folder are required to run the website?

Can I modify the project files to achieve this using Angular CLI?


问:
Image file missing exif data
Using intent to take a photo, which is later uploaded to a server.
Image is first saved to sdcard like so:

```<code>/**
 * Creating file uri to store image/video
 */
public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

/**
 * returning image / video
 */
private static File getOutputMediaFile(int type) {

    // External sdcard location
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            Config.IMAGE_DIRECTORY_NAME);

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(TAG, "Oops! Failed create "
                    + Config.IMAGE_DIRECTORY_NAME + " directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
    } else if (type == MEDIA_TYPE_VIDEO) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "VID_" + timeStamp + ".mp4");
    } else {
        return null;
    }

    return mediaFile;
}
</code>```

The saved image has no exif data. Is it due to the uri? (photos taken with the default camera app has exif data so it has to be an issue in my app).

Edit: Code used to launch default camera app:

```<code>/**
 * Launching camera app to capture image
 */
private void captureImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

    // start the image capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
</code>```

url stored:

```<code>/**
 * Here we store the file url as it will be null after returning from camera
 * app
 */
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // save file url in bundle as it will be null on screen orientation
    // changes
    outState.putParcelable("file_uri", fileUri);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    // get the file url
    fileUri = savedInstanceState.getParcelable("file_uri");
}
</code>```

Source: http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/

答:
photos taken with the default camera app has exif data so it has to be an issue in my app

Not necessarily. From the code that you have shown, it would appear to be a bug in that particular camera app. Not all camera app developers test ACTION_IMAGE_CAPTURE very well. Unless you are modifying the image sometime after the picture is taken but before you run your EXIF test, the camera app is not adding EXIF tags to pictures taken via ACTION_IMAGE_CAPTURE. These things happen.

You might install some camera apps and see how they behave with ACTION_IMAGE_CAPTURE. Open Camera, for example, supports ACTION_IMAGE_CAPTURE, though I have not tested its EXIF behavior when started with ACTION_IMAGE_CAPTURE.

Title: Image file missing exif data

Body:
Using intent to take a photo, which is later uploaded to a server.
Image is first saved to sdcard like so:

/**
 * Creating file uri to store image/video
 */
public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

/**
 * returning image / video
 */
private static File getOutputMediaFile(int type) {

    // External sdcard location
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            Config.IMAGE_DIRECTORY_NAME);

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(TAG, "Oops! Failed create "
                    + Config.IMAGE_DIRECTORY_NAME + " directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
    } else if (type == MEDIA_TYPE_VIDEO) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "VID_" + timeStamp + ".mp4");
    } else {
        return null;
    }

    return mediaFile;
}

The saved image has no exif data. Is it due to the uri? (photos taken with the default camera app has exif data so it has to be an issue in my app).

Edit: Code used to launch default camera app:

/**
 * Launching camera app to capture image
 */
private void captureImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

    // start the image capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}

url stored:

/**
 * Here we store the file url as it will be null after returning from camera
 * app
 */
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // save file url in bundle as it will be null on screen orientation
    // changes
    outState.putParcelable("file_uri", fileUri);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    // get the file url
    fileUri = savedInstanceState.getParcelable("file_uri");
}

Source: http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/


问:
Calling a function in a separate function file - matlab
From what I understood of matlab, if you want to define a function and use it in your "main file" you need to write the function in a separate file and to call it at the beginning of your "main file" with addpath('...\myfunction.m').

Now let's say I define a function f1 in a file f1.m that I use in main.m, if I want to define a function f2 (in another file) that needs to call f1, can I use addpath()...\f1.m in my f2.m file ? Or what is the best way of calling f1 in f2 ?

答: Save all your files in the folder where matlab is opened, and you wont need addpath to explicitly tell matlab to search in the told directories for files</p>


问:
get all the latest entries from table linq
I have two tables like below: (date format : mm/dd/yyyy)

Parameter master table:

```<code>   Id  Parameter
    1      ST
    2      GP
    3     Interest
    4      CC
</code>```

And Second TaxValue table :

```<code>Date     ParameterId   Value
1/1/2017    1          4
2/1/2017    1          4.5
1/15/2017   2          15
3/20/2017   2          20
3/21/2017   3          18
4/28/2017   3          20
1/1/2017    4          10
</code>```

I want to write a linq query to get all the latest parameters values from the date specified.

Desired Result: (if I want to get latest entries for today)

```<code>Date     Parameter   Value
2/1/2017    ST          4.5
3/20/2017   GP          20
4/28/2017   Interest    20
1/1/2017    CC          10
</code>```

Please help!!

答:
You can do a join on the latest TaxValue record like this:</p>

```<code>var qry = (from pm in parameterMaster

           from tax in taxValue.Where(t => t.ParameterId == pm.Id)
                               .OrderByDescending(t => t.Date)
                               .Take(1)
                               .DefaultIfEmpty()
           select new {
                date = tax.Date,
                parameter = pm.Name,
                value = tax.Value
           });

var results = qry.ToList();
</code>```

Body:
I have two tables like below: (date format : mm/dd/yyyy)

Parameter master table:

   Id  Parameter
    1      ST
    2      GP
    3     Interest
    4      CC

And Second TaxValue table :

Date     ParameterId   Value
1/1/2017    1          4
2/1/2017    1          4.5
1/15/2017   2          15
3/20/2017   2          20
3/21/2017   3          18
4/28/2017   3          20
1/1/2017    4          10

I want to write a linq query to get all the latest parameters values from the date specified.

Desired Result: (if I want to get latest entries for today)

Date     Parameter   Value
2/1/2017    ST          4.5
3/20/2017   GP          20
4/28/2017   Interest    20
1/1/2017    CC          10

Please help!!

Body:
You can do a join on the latest TaxValue record like this:

var qry = (from pm in parameterMaster

           from tax in taxValue.Where(t => t.ParameterId == pm.Id)
                               .OrderByDescending(t => t.Date)
                               .Take(1)
                               .DefaultIfEmpty()
           select new {
                date = tax.Date,
                parameter = pm.Name,
                value = tax.Value
           });

var results = qry.ToList();


问:
Is there anything else to do Audio in 92khz to 192khz?
I spend lot of time researching/finding a best developer friendly framework or libraries for cross platform to deal with solid/accurate/lipsync sort of audio solution. Still could not find one which can be used for cross platform.

I tried GStreamer (was the best one) but it is best for linux as it covers CELT/Vorbis/Speex (encoder/decoder), GStreamer does the great job for Linux. But porting Gstreamer to Windows and Mac platform is not friendly, and lot of restrictions, and facing lot of problems, where i found myself its not the best way to build better application, the way i know about audio.

Is there any audio libraries or framework which can handle lowest latency for any cross platform ? No matter what language it is C/ADA/LUA/Python/Java..., to study from that libraries. To build my own freedom of audio quality over internet for musicians/conversation peer 2 peer in RTP method to have maximum range of 192 khz.

Expecting experts, advise.

```<code>My project is:
1. Peer 1 - playing electrical guiter from UK (london)
2. Peer 2 - playing drums from USA (new york)
3. Peer 3 - playing bass guiter from UK (luton)
</code>```

And Peer 4 is listening, and doing recording in Holland (amsterdam)

Thanks in advance.

答:
murgaLua comes with a binding to proteaAudio if you want to have something to be up and running quickly...
It's cross platform Windows-Mac-Linux ;)</p>

Body:
I spend lot of time researching/finding a best developer friendly framework or libraries for cross platform to deal with solid/accurate/lipsync sort of audio solution. Still could not find one which can be used for cross platform.

I tried GStreamer (was the best one) but it is best for linux as it covers CELT/Vorbis/Speex (encoder/decoder), GStreamer does the great job for Linux. But porting Gstreamer to Windows and Mac platform is not friendly, and lot of restrictions, and facing lot of problems, where i found myself its not the best way to build better application, the way i know about audio.

Is there any audio libraries or framework which can handle lowest latency for any cross platform ? No matter what language it is C/ADA/LUA/Python/Java..., to study from that libraries. To build my own freedom of audio quality over internet for musicians/conversation peer 2 peer in RTP method to have maximum range of 192 khz.

Expecting experts, advise.

My project is:
1. Peer 1 - playing electrical guiter from UK (london)
2. Peer 2 - playing drums from USA (new york)
3. Peer 3 - playing bass guiter from UK (luton)

And Peer 4 is listening, and doing recording in Holland (amsterdam)

Thanks in advance.


问:
How to connect mysql tables
I have two tables in same database, one for pictures and the other table for picture comments. How can i write a sql command to get all the comments belonging to each particular picture?</p>

答:
The below code should work. Like I said, this is pretty basic problem and I feel you have some problem related to this. Post what code you tried and edit the question. You can use WHERE clause to further filter.

```<code>SELECT  picture_table.pic_owner,  picture_table.pic_insert_date, picture_comment_table.pic_commentor_name, picture_comment_table.pic_comments FROM
picture_table LEFT JOIN  picture_comment_table
ON picture_table.pic_id = picture_comment_table.pic_id
</code>```

Title: How to connect mysql tables

Body:
The below code should work. Like I said, this is pretty basic problem and I feel you have some problem related to this. Post what code you tried and edit the question. You can use WHERE clause to further filter.

SELECT  picture_table.pic_owner,  picture_table.pic_insert_date, picture_comment_table.pic_commentor_name, picture_comment_table.pic_comments FROM
picture_table LEFT JOIN  picture_comment_table
ON picture_table.pic_id = picture_comment_table.pic_id


问:
Switch to new browser opened after click on a button [Python][Selenium]
I have a situation where I click on a button that opens up a new browser Window. Is there any way to connect to the newly opened  window? And work with it, then return back to original browser (first window).

Thank you.

After some thorough investigation on the net I managed to get some of the code working

```<code>Currentwindow = driver.window_handles
Likebutton = driver.find_element_by_css_selector(".single_like_button .btn3").click()
newwindow = driver.window_handles
newwindow = list(set(newwindow) - set(Currentwindow))[0]
driver.switch_to.window(newwindow)
driver.find_element_by_id("watch-like").click()
driver.implicitly_wait(5)
driver.close()
</code>```

Problem is the command driver.implicitly_wait(5) doesn't work for some reason and the page automatically closes which is not something I want.
How do I get it working?

答:
too late for you , but maybe this will help someone

```<code>driver.implicitly_wait(5)
</code>```

this command wait , while the page is loaded or 5 sec.
If it will be loaded in 1 sec , then

```<code>driver.close()
</code>```

Run after 1 second .
If it be loaded in 7 sec , then

```<code>driver.close()
</code>```

Run after 5 sec

You may use

```<code>import time

time.sleep(5)
</code>```

It will wait exactly 5 sec anyway

Body:
I have a situation where I click on a button that opens up a new browser Window. Is there any way to connect to the newly opened  window? And work with it, then return back to original browser (first window).

Thank you.

After some thorough investigation on the net I managed to get some of the code working

Currentwindow = driver.window_handles
Likebutton = driver.find_element_by_css_selector(".single_like_button .btn3").click()
newwindow = driver.window_handles
newwindow = list(set(newwindow) - set(Currentwindow))[0]
driver.switch_to.window(newwindow)
driver.find_element_by_id("watch-like").click()
driver.implicitly_wait(5)
driver.close()

Problem is the command driver.implicitly_wait(5) doesn't work for some reason and the page automatically closes which is not something I want.
How do I get it working?

Body:
too late for you , but maybe this will help someone

driver.implicitly_wait(5)

this command wait , while the page is loaded or 5 sec.
If it will be loaded in 1 sec , then

driver.close()

Run after 1 second .
If it be loaded in 7 sec , then

driver.close()

Run after 5 sec

You may use

import time

time.sleep(5)

It will wait exactly 5 sec anyway


问:
What is the difference between "VC++" and "C++"?
Someone asked me how familiar I am with VC++ and how familiar I am with C++.  What is the difference?</p>

答:
In some cases, they refer to its corresponding C++ implementation and its compilers.

C++ refers to standard headers/functions and its GCC C++ compiler.

VC++ refers to Microsoft implementation of C++ standard and its VC++
  compiler.

They are not compatible with each other. Linux network/threading functions, numeric data types are different than its Windows counterpart. You can't compile Linux C++ code directly in Windows without using third-party GCC ports such as Cygwin/MinGW.

Most academic/research tools and libraries are written in C++ (GCC), and one will have the hard time to compile those in VC++.

OwnerDisplayName: MrDatabase

LastEditorDisplayName: Aardvark

ContentLicense: CC BY-SA 4.0


问:
Export to *.txt with specific Font
I need to export from sql server to *.txt. But i want my export to be with specific Font.Example I need my txt file to have Terminal Font.

Here is my code:

```<code>SqlCommand cmd = new SqlCommand("Select Code,Name,Price", con);
SqlDataReader read = cmd.ExecuteReader();
using (StreamWriter sw = new StreamWriter("C://test.txt")) {

while (read.Read())
{
    //Code
    string CodeString = (read["Code"].ToString());
    sw.Write(CodeString);

    //Name
    string NameString = (read["Name"].ToString());
    sw.Write(NameString);

    //Price
    string PriceString = (read["Price"].ToString());
    sw.Write(PriceString);
}

sw.Close();
read.Close();
</code>```

答:
A TXT file is just text (ASCII or UTF8 by default) and does not support fonts or other styling (underline, bold, etc)

Probably the simplest format would be to use RTF (Rich Text Format) which does have simpler styling items available, including font, bold, underline, & colors; and is open format with known specifications. Windows 95 and up came with the program WordPad which is an RTF editor.

To learn the codes needed, which are made up of escaped codes like C; you can either write a simple file in WordPad (or other program) and then open that file in NotePad (or other text editor). If that is too cumbersome for you, you could try this RTF Tutorial

Title: Export to *.txt with specific Font

Body:
I need to export from sql server to *.txt. But i want my export to be with specific Font.Example I need my txt file to have Terminal Font.

Here is my code:

SqlCommand cmd = new SqlCommand("Select Code,Name,Price", con);
SqlDataReader read = cmd.ExecuteReader();
using (StreamWriter sw = new StreamWriter("C://test.txt")) {

while (read.Read())
{
    //Code
    string CodeString = (read["Code"].ToString());
    sw.Write(CodeString);

    //Name
    string NameString = (read["Name"].ToString());
    sw.Write(NameString);

    //Price
    string PriceString = (read["Price"].ToString());
    sw.Write(PriceString);
}

sw.Close();
read.Close();


问:
How do I link the data-key attribute of two elements using javascript?
I'd been following the #javascript30 course in which he links the data-key of a div with the data-key of an audio using javascript and a keydown event as follows

html

```<code><div data-key = "65" class = "key">
<kbd> A </kbd> <br> <span> Boom </span>
</div>

<audio data-key = "65" src = "sounds/boom.wav" id = "boom"> </audio>
</code>```

javascript

```<code>function playSound(e)
{
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
audio.play();
}
</code>```

Now I want to play the audio when I click on the div but I don't know how to start. I've attempted this, but it says Uncaught ReferenceError: key is not defined. So how do I get it to play the audio on a click event?

NOTE: I have eight different audio files for eight different divs. Corresponding pairs have the same data-key.

```<code>$(".key").click(function()
{
const audio = document.getElementById(`${this.data-key}`)
console.log(audio);
audio.play();
});
</code>```

答:
You have to get the value of the data-key attribute.  Using a template literal which gives you the ${} syntax in your selector, you can do this using Vanilla JS or jQuery with both examples below.  I'd recommend reading up on valid DOM selectors as well as basic dom element attribute access.

A DOM element attribute is not a top-level property of the element. It lives in a NamedNodeMap in the attributes property of the element.

$(".key").click(function(e) {
  const audio = document.querySelector(`audio[data-key="${this.attributes['data-key'].value}"]`);
  console.log(audio);
  audio.play();
  // or using jQuery
  // const audio = $(`audio[data-key="${$(this).attr('data-key')');
  // audio[0].play();

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-key="65" class="key">
  <kbd> A </kbd> <br> <span> Boom </span>
</div>

<audio data-key="65" src="http://freewavesamples.com/files/Alesis-Sanctuary-QCard-AcoustcBas-C2.wav" id="boom"> </audio></code>```

Body:
I'd been following the #javascript30 course in which he links the data-key of a div with the data-key of an audio using javascript and a keydown event as follows

html

 A
  Boom

<audio data-key = "65" src = "sounds/boom.wav" id = "boom"> </audio>

javascript

function playSound(e)
{
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
audio.play();
}

Now I want to play the audio when I click on the div but I don't know how to start. I've attempted this, but it says Uncaught ReferenceError: key is not defined. So how do I get it to play the audio on a click event?

NOTE: I have eight different audio files for eight different divs. Corresponding pairs have the same data-key.

$(".key").click(function()
{
const audio = document.getElementById(`${this.data-key}`)
console.log(audio);
audio.play();
});

Body:
You have to get the value of the data-key attribute.  Using a template literal which gives you the ${} syntax in your selector, you can do this using Vanilla JS or jQuery with both examples below.  I'd recommend reading up on valid DOM selectors as well as basic dom element attribute access.

A DOM element attribute is not a top-level property of the element. It lives in a NamedNodeMap in the attributes property of the element.

$(".key").click(function(e) {
  const audio = document.querySelector(`audio[data-key="${this.attributes['data-key'].value}"]`);
  console.log(audio);
  audio.play();
  // or using jQuery
  // const audio = $(`audio[data-key="${$(this).attr('data-key')');
  // audio[0].play();

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-key="65" class="key">
  <kbd> A </kbd> <br> <span> Boom </span>
</div>

<audio data-key="65" src="http://freewavesamples.com/files/Alesis-Sanctuary-QCard-AcoustcBas-C2.wav" id="boom"> </audio>


问:
How to determine the types of the whitespaces when reading from a file in java?
I want to read a file's contents and split every time that I reach to a whitespace and do "action 1" on the splitted string if there was an "space" before it, "action 2" if there was a "tab" before it and "action 3" if there was a "newline" before it.

Actions are not important. My question is how can i read the file such that i can determine the type of the whitespace i read?

Thanks in advance!

答: Try str.split("/n") for newline, str.split("/t") for tabs and  str.split(" ") for spaces. For example String [] result = "before tab [ TAB ] after tab".split("/t") if result.length >= 2 than you found tab character, so you know that there is tab character after result[0] or before result[1]( same with space, new line e.g)


问:
spline interpolation and its (exact) derivatives
Suppose I have the following data and commands:

```<code>clc;clear;
t = [0:0.1:1];
t_new = [0:0.01:1];
y = [1,2,1,3,2,2,4,5,6,1,0];
p = interp1(t,y,t_new,'spline');
plot(t,y,'o',t_new,p)
</code>```

You can see they work quite fine, in the sense interpolating function matches the data points at the nodes fine. But my problem is, I need to compute the exact derivative of y (i.e., p function) w.r.t. time and plot it against the t vector. How can it be done? I shall not use diff commands, because I need to make sure the derivative function has the same length as t vector. Thanks a lot.

答:
Method A: Using the derivative

This method calculates the actual derivative of the polynomial. If you have the curve fitting toolbox you can use:

```<code>% calculate the polynominal
pp = interp1(t,y,'spline','pp')
% take the first order derivative of it
pp_der=fnder(pp,1);
% evaluate the derivative at points t (or any other points you wish)
slopes=ppval(pp_der,t);
</code>```

If you don't have the curve fitting toolbox you can replace the fnderline with:

```<code>% piece-wise polynomial
[breaks,coefs,l,k,d] = unmkpp(pp);
% get its derivative
pp_der = mkpp(breaks,repmat(k-1:-1:1,d*l,1).*coefs(:,1:k-1),d);
</code>```

Source: This mathworks question. Thanks to  m7913d for linking it.

Appendix:

Note that

```<code>p = interp1(t,y,t_new,'spline');
</code>```

is a shortcut for

```<code>% get the polynomial
pp = interp1(t,y,'spline','pp');
% get the height of the polynomial at query points t_new
p=ppval(pp,t_new);
</code>```

To get the derivative we obviously need the polynomial and can't just work with the new interpolated points. To avoid interpolating the points twice which can take quite long for a lot of data, you should replace the shortcut with the longer version. So a fully working example that includes your code example would be:

```<code>t = [0:0.1:1];
t_new = [0:0.01:1];
y = [1,2,1,3,2,2,4,5,6,1,0];

% fit a polynomial
pp = interp1(t,y,'spline','pp');
% get the height of the polynomial at query points t_new
p=ppval(pp,t_new);
% plot the new interpolated curve
plot(t,y,'o',t_new,p)

% piece-wise polynomial
[breaks,coefs,l,k,d] = unmkpp(pp);
% get its derivative
pp_der = mkpp(breaks,repmat(k-1:-1:1,d*l,1).*coefs(:,1:k-1),d);
% evaluate the derivative at points t (or any other points you wish)
slopes=ppval(pp_der,t);
</code>```

Method B: Using finite differences

A derivative of a continuous function is at its base just the difference of f(x) to f(x+infinitesimal difference) divided by said infinitesimal difference.

In matlab, eps is the smallest difference possible with a double precision. Therefore after each t_new we add a second point which is eps larger and interpolate y for the new points. Then the difference between each point and it's +eps pair divided by eps gives the derivative.

The problem is that if we work with such small differences the precision of the output derivatives is severely limited, meaning it can only have integer values. Therefore we add values slightly larger than eps to allow for higher precisions.

```<code>% how many floating points the derivatives can have
precision = 10;
% add after each t_new a second point with +eps difference
t_eps=[t_new; t_new+eps*precision];
t_eps=t_eps(:).';
% interpolate with those points and get the differences between them
differences = diff(interp1(t,y,t_eps,'spline'));
% delete all differences wich are not between t_new and t_new + eps
differences(2:2:end)=[];
% get the derivatives of each point
slopes = differences./(eps*precision);
</code>```

You can of course replace t_new with t (or any other time you want to get the differential of) if you want to get the derivatives at the old points.

This method is slightly inferior to method a) in your case, as it is slower and a bit less precise. But maybe it's useful to somebody else who is in a different situation.

Body:
Suppose I have the following data and commands:

clc;clear;
t = [0:0.1:1];
t_new = [0:0.01:1];
y = [1,2,1,3,2,2,4,5,6,1,0];
p = interp1(t,y,t_new,'spline');
plot(t,y,'o',t_new,p)

You can see they work quite fine, in the sense interpolating function matches the data points at the nodes fine. But my problem is, I need to compute the exact derivative of y (i.e., p function) w.r.t. time and plot it against the t vector. How can it be done? I shall not use diff commands, because I need to make sure the derivative function has the same length as t vector. Thanks a lot.

Body:
Method A: Using the derivative

This method calculates the actual derivative of the polynomial. If you have the curve fitting toolbox you can use:

% calculate the polynominal
pp = interp1(t,y,'spline','pp')
% take the first order derivative of it
pp_der=fnder(pp,1);
% evaluate the derivative at points t (or any other points you wish)
slopes=ppval(pp_der,t);

If you don't have the curve fitting toolbox you can replace the fnderline with:

% piece-wise polynomial
[breaks,coefs,l,k,d] = unmkpp(pp);
% get its derivative
pp_der = mkpp(breaks,repmat(k-1:-1:1,d*l,1).*coefs(:,1:k-1),d);

Source: This mathworks question. Thanks to  m7913d for linking it.

Appendix:

Note that

p = interp1(t,y,t_new,'spline');

is a shortcut for

% get the polynomial
pp = interp1(t,y,'spline','pp');
% get the height of the polynomial at query points t_new
p=ppval(pp,t_new);

To get the derivative we obviously need the polynomial and can't just work with the new interpolated points. To avoid interpolating the points twice which can take quite long for a lot of data, you should replace the shortcut with the longer version. So a fully working example that includes your code example would be:

t = [0:0.1:1];
t_new = [0:0.01:1];
y = [1,2,1,3,2,2,4,5,6,1,0];

% fit a polynomial
pp = interp1(t,y,'spline','pp');
% get the height of the polynomial at query points t_new
p=ppval(pp,t_new);
% plot the new interpolated curve
plot(t,y,'o',t_new,p)

% piece-wise polynomial
[breaks,coefs,l,k,d] = unmkpp(pp);
% get its derivative
pp_der = mkpp(breaks,repmat(k-1:-1:1,d*l,1).*coefs(:,1:k-1),d);
% evaluate the derivative at points t (or any other points you wish)
slopes=ppval(pp_der,t);

Method B: Using finite differences

A derivative of a continuous function is at its base just the difference of f(x) to f(x+infinitesimal difference) divided by said infinitesimal difference.

In matlab, eps is the smallest difference possible with a double precision. Therefore after each t_new we add a second point which is eps larger and interpolate y for the new points. Then the difference between each point and it's +eps pair divided by eps gives the derivative.

The problem is that if we work with such small differences the precision of the output derivatives is severely limited, meaning it can only have integer values. Therefore we add values slightly larger than eps to allow for higher precisions.

% how many floating points the derivatives can have
precision = 10;
% add after each t_new a second point with +eps difference
t_eps=[t_new; t_new+eps*precision];
t_eps=t_eps(:).';
% interpolate with those points and get the differences between them
differences = diff(interp1(t,y,t_eps,'spline'));
% delete all differences wich are not between t_new and t_new + eps
differences(2:2:end)=[];
% get the derivatives of each point
slopes = differences./(eps*precision);

You can of course replace t_new with t (or any other time you want to get the differential of) if you want to get the derivatives at the old points.

This method is slightly inferior to method a) in your case, as it is slower and a bit less precise. But maybe it's useful to somebody else who is in a different situation.


问:
How to append parameter?
How can I get a string by appending parameter(s) to Request.Url.Query?

Let say I have a parameter "value=100"

```<code>Request.Url.Query                            After Appending
""                                           "?value=100"
"?"                                          "?value=100"
"?page=15"                                   "?page=15&value=100"
"?page=15&sort=col"                          "?page=15&sort=col&value=100"
</code>```

答:
You cannot append parameters to the current query string. The querystring is readonly. Now if you want to manipulate querystrings in your application you could use the Url helpers to generate and manipulate urls.

You could also checkout the ParseQueryString method but this is rarely useful in an ASP.NET MVC application where you have routes and url helpers.

Sample usage:

```<code>string query = "?page=15&sort=col";
var values = HttpUtility.ParseQueryString(query);
values["value"] = "100";
query = values.ToString(); // page=15&sort=col&value=100
</code>```

Title: How to append parameter?

Body:
How can I get a string by appending parameter(s) to Request.Url.Query?

Let say I have a parameter "value=100"

Request.Url.Query                            After Appending
""                                           "?value=100"
"?"                                          "?value=100"
"?page=15"                                   "?page=15&value=100"
"?page=15&sort=col"                          "?page=15&sort=col&value=100"

Body:
You cannot append parameters to the current query string. The querystring is readonly. Now if you want to manipulate querystrings in your application you could use the Url helpers to generate and manipulate urls.

You could also checkout the ParseQueryString method but this is rarely useful in an ASP.NET MVC application where you have routes and url helpers.

Sample usage:

string query = "?page=15&sort=col";
var values = HttpUtility.ParseQueryString(query);
values["value"] = "100";
query = values.ToString(); // page=15&sort=col&value=100


问:
splitting a drill file using regex
i have a file here is it's dump

```<code>T01
X064900Y049200
X065900
X066900
X067900
X068900
X069900
T02
X062900Y048200
Y049200
Y050200
Y053700
X063900
X064900
X065900
X046350
</code>```

I wan to split it's contents   by T*   "T* must be included" by using
Java regex
   here what i did i read file contents into string parts
then String [] tools = parts.split("T\\d+");

but it didn't work, what is the best regex to use .

答:
It can be accomplished even without the split method, but using a capturing group:

This is the Regex: ((?<=T)[^T]*)

Title: splitting a drill file using regex

Body:
i have a file here is it's dump

T01
X064900Y049200
X065900
X066900
X067900
X068900
X069900
T02
X062900Y048200
Y049200
Y050200
Y053700
X063900
X064900
X065900
X046350

I wan to split it's contents   by T*   "T* must be included" by using
Java regex
   here what i did i read file contents into string parts
then String [] tools = parts.split("T\\d+");

but it didn't work, what is the best regex to use .


问:
vertica generate table with numbers & select prime numbers
I'm working on Vertica version 8+

I need to create a table with numbers from 1 to N and select the prime numbers

I've accomplished to do that in SQLite3 but Vertica doesn't allow recursive WITH

https://forum.vertica.com/discussion/206185/recursive-queries

Edit:

```<code>WITH seq AS (
  SELECT n FROM (
    SELECT ROW_NUMBER() OVER() AS n
    FROM (
        SELECT 1
        FROM (
            SELECT date(0) + INTERVAL '1 second' AS i
            UNION ALL
            SELECT date(0) + INTERVAL '100 seconds' AS i
        ) _
        TIMESERIES tm AS '1 second' OVER(ORDER BY i)
    ) _
  ) _
  WHERE n > 1 -- 1 is not prime number
)

SELECT n
FROM (SELECT n FROM seq) _
WHERE n NOT IN (
  SELECT n FROM (
    SELECT s1.n AS n, s2.n AS n2
    FROM seq AS s1
    CROSS JOIN seq AS s2
    ORDER BY n, n2
  ) _
  WHERE n2 < n AND n % n2 = 0
)
ORDER BY n
</code>```

答:
You don't need recursive WITH for this.

First Step. You need to generate all numbers from 1 to N (let's say 1000). You can easily do this in Vertica using TIMESERIES. The following will generate all numbers from 1 to 1000:

```<code>WITH seq AS (
    SELECT ROW_NUMBER() OVER() AS num FROM (
        SELECT 1 FROM (
            SELECT date(0) + INTERVAL '1 second' AS se UNION ALL
            SELECT date(0) + INTERVAL '1000 seconds' AS se ) a
        TIMESERIES tm AS '1 second' OVER(ORDER BY se)
    ) b
)
SELECT num FROM seq ;
 num
------
    1
    2
    3
    4
  ...
  997
  998
  999
 1000
</code>```

Second Step we just have to exclude non-prime numbers from the result set here above (see here, here and here):

```<code>WITH seq AS (
    SELECT ROW_NUMBER() OVER() AS num FROM (
        SELECT 1 FROM (
            SELECT date(0) + INTERVAL '1 second' AS se UNION ALL
            SELECT date(0) + INTERVAL '1000 seconds' AS se ) a
        TIMESERIES tm AS '1 second' OVER(ORDER BY se)
    ) b
)
SELECT num as prime
FROM seq
WHERE num NOT IN (
    SELECT s1.num * s2.num
    FROM seq s1 CROSS JOIN seq s2
        WHERE s1.num BETWEEN 2 AND CEILING (SQRT (1000))
        AND s1.num <= s2.num
        AND s2.num * s1.num <= 1000
)
ORDER BY 1
;
 prime
-------
     1
     2
     3
     5
     7
    11
   ...
   977
   983
   991
   997
</code>```

Body:
I'm working on Vertica version 8+

I need to create a table with numbers from 1 to N and select the prime numbers

I've accomplished to do that in SQLite3 but Vertica doesn't allow recursive WITH

https://forum.vertica.com/discussion/206185/recursive-queries

Edit:

WITH seq AS (
  SELECT n FROM (
    SELECT ROW_NUMBER() OVER() AS n
    FROM (
        SELECT 1
        FROM (
            SELECT date(0) + INTERVAL '1 second' AS i
            UNION ALL
            SELECT date(0) + INTERVAL '100 seconds' AS i
        ) _
        TIMESERIES tm AS '1 second' OVER(ORDER BY i)
    ) _
  ) _
  WHERE n > 1 -- 1 is not prime number
)

SELECT n
FROM (SELECT n FROM seq) _
WHERE n NOT IN (
  SELECT n FROM (
    SELECT s1.n AS n, s2.n AS n2
    FROM seq AS s1
    CROSS JOIN seq AS s2
    ORDER BY n, n2
  ) _
  WHERE n2 < n AND n % n2 = 0
)
ORDER BY n

Body:
You don't need recursive WITH for this.

First Step. You need to generate all numbers from 1 to N (let's say 1000). You can easily do this in Vertica using TIMESERIES. The following will generate all numbers from 1 to 1000:

WITH seq AS (
    SELECT ROW_NUMBER() OVER() AS num FROM (
        SELECT 1 FROM (
            SELECT date(0) + INTERVAL '1 second' AS se UNION ALL
            SELECT date(0) + INTERVAL '1000 seconds' AS se ) a
        TIMESERIES tm AS '1 second' OVER(ORDER BY se)
    ) b
)
SELECT num FROM seq ;
 num
------
    1
    2
    3
    4
  ...
  997
  998
  999
 1000

Second Step we just have to exclude non-prime numbers from the result set here above (see here, here and here):

WITH seq AS (
    SELECT ROW_NUMBER() OVER() AS num FROM (
        SELECT 1 FROM (
            SELECT date(0) + INTERVAL '1 second' AS se UNION ALL
            SELECT date(0) + INTERVAL '1000 seconds' AS se ) a
        TIMESERIES tm AS '1 second' OVER(ORDER BY se)
    ) b
)
SELECT num as prime
FROM seq
WHERE num NOT IN (
    SELECT s1.num * s2.num
    FROM seq s1 CROSS JOIN seq s2
        WHERE s1.num BETWEEN 2 AND CEILING (SQRT (1000))
        AND s1.num <= s2.num
        AND s2.num * s1.num <= 1000
)
ORDER BY 1
;
 prime
-------
     1
     2
     3
     5
     7
    11
   ...
   977
   983
   991
   997


问:
audio recording in android
I have and android emulator and microphone connected to my pc. I want to capture pcm pulses from microphone (i.e. record voice) and then send to udp socket. please anybody help me in source code at least for voice recording.</p>

答: Check Audalyzer, a sample application showing you how to read the raw audio stream from the microphone on real time. </p>

Title: audio recording in android


问:
Put space between end of page and button on iphone
Hello guys i have trouble with my code. I have a bootstrap button and thats is fine but how can i put space between the button and end of the page. because its only on iphone the problem. Its very weird because when im holding in normal its good the button but when i turn my iphone there is no space anymore.

This is my button:

```<code><div class="row">
    <div class="text-center">
        <button type="button" class="learn btn btn-info">Learn more</button>
    </div>
</div>
</code>```

答:
As Ashiqur suggested, add some margin to the bottom of the button</p>

```<code>.learn {
  margin-bottom: 1rem;
}
</code>```

Body:
Hello guys i have trouble with my code. I have a bootstrap button and thats is fine but how can i put space between the button and end of the page. because its only on iphone the problem. Its very weird because when im holding in normal its good the button but when i turn my iphone there is no space anymore.

This is my button:

        <button type="button" class="learn btn btn-info">Learn more</button>

Body:
As Ashiqur suggested, add some margin to the bottom of the button

.learn {
  margin-bottom: 1rem;
}


问:
Android ImageButton click not working sometimes
I'm using ImageButton in my xml, like this:

```<code><FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        >
        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/imageButton_home"
            android:src="@drawable/home_icon"
            android:background="@android:color/transparent"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="10dp"
            android:focusableInTouchMode="false"
            android:focusable="false"
            android:clickable="true"
            />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/imageButton_back"
            android:src="@drawable/back_icon"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="10dp"
            android:background="@android:color/transparent"
            android:visibility="gone"
            android:focusableInTouchMode="false"
            android:focusable="false"
            android:clickable="true"
            />

    </FrameLayout>
</code>```

Only one image button is visible at a time.
And I'm capturing the click in my java code as following:

```<code>  imageButtonHome.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent homeIntent = new Intent(SettingsActivity.this, MainActivity.class);
            startActivity(homeIntent);
        }
    });
</code>```

This works fine sometimes, but not always.
I see this line in my logcat whenever I click on image button:

```<code>D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
</code>```

This line always shows up, even when my ImageButton click action is not performed.

But when my ImageButton click works correctly, this other line adds up to log:

```<code> D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
 D/AbsListView: Get MotionRecognitionManager
</code>```

I want my image button to work every time. Please help.

答: Use setOnClickListener(...) on the ImageButton</p>

Body:
I'm using ImageButton in my xml, like this:

<FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        >
        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/imageButton_home"
            android:src="@drawable/home_icon"
            android:background="@android:color/transparent"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="10dp"
            android:focusableInTouchMode="false"
            android:focusable="false"
            android:clickable="true"
            />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/imageButton_back"
            android:src="@drawable/back_icon"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="10dp"
            android:background="@android:color/transparent"
            android:visibility="gone"
            android:focusableInTouchMode="false"
            android:focusable="false"
            android:clickable="true"
            />

    </FrameLayout>

Only one image button is visible at a time.
And I'm capturing the click in my java code as following:

  imageButtonHome.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent homeIntent = new Intent(SettingsActivity.this, MainActivity.class);
            startActivity(homeIntent);
        }
    });

This works fine sometimes, but not always.
I see this line in my logcat whenever I click on image button:

D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN

This line always shows up, even when my ImageButton click action is not performed.

But when my ImageButton click works correctly, this other line adds up to log:

 D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
 D/AbsListView: Get MotionRecognitionManager

I want my image button to work every time. Please help.


问:
View doesn't return anything in Laravel
I just started to learn the laravel framework and have a strange situation here.

First of all in my web.php I have code like:

```<code><?php
Route::get('/', function () {
    return view('welcome');
});

Route::get('users', ['uses' => 'UsersController@index']);
</code>```

In my UsersController.php file I have code like:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UsersController extends Controller
{
    public function index(){
        return view('users.index');
    }
}
</code>```

I have a file named index.blade.php in directory views/users that has the same content as the default welcome.blade.php. But when I try to return view('users.index'); there is no result (no error, or text) but when I try to return view('welcome'); it works just fine.

The directory and the file truly exists.
I'm using Macbook Pro.

welcome.blade.php and the /users/index.blade.php content (default welcome page):

```<code><!doctype html>
<html lang="{{ config('app.locale') }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">

        <!-- Styles -->
        <style>
            html, body {
                background-color: #fff;
                color: #636b6f;
                font-family: 'Raleway', sans-serif;
                font-weight: 100;
                height: 100vh;
                margin: 0;
            }

            .full-height {
                height: 100vh;
            }

            .flex-center {
                align-items: center;
                display: flex;
                justify-content: center;
            }

            .position-ref {
                position: relative;
            }

            .top-right {
                position: absolute;
                right: 10px;
                top: 18px;
            }

            .content {
                text-align: center;
            }

            .title {
                font-size: 84px;
            }

            .links > a {
                color: #636b6f;
                padding: 0 25px;
                font-size: 12px;
                font-weight: 600;
                letter-spacing: .1rem;
                text-decoration: none;
                text-transform: uppercase;
            }

            .m-b-md {
                margin-bottom: 30px;
            }
        </style>
    </head>
    <body>
        <div class="flex-center position-ref full-height">
            @if (Route::has('login'))
                <div class="top-right links">
                    @if (Auth::check())
                        <a href="{{ url('/home') }}">Home</a>
                    @else
                        <a href="{{ url('/login') }}">Login</a>
                        <a href="{{ url('/register') }}">Register</a>
                    @endif
                </div>
            @endif

            <div class="content">
                <div class="title m-b-md">
                    Laravel
                </div>

                <div class="links">
                    <a href="https://laravel.com/docs">Documentation</a>
                    <a href="https://laracasts.com">Laracasts</a>
                    <a href="https://laravel-news.com">News</a>
                    <a href="https://forge.laravel.com">Forge</a>
                    <a href="https://github.com/laravel/laravel">GitHub</a>
                </div>
            </div>
        </div>
    </body>
</html>
</code>```

答:
On apache check the logs, see what's wrong:
/var/log/apache2/error.log

Give 755 perms to bootstrap/cache/ and /storage folder.
sudo chmod -R 755 storage bootstrap/cache

Generate encryptions key:
php artisan key:generate

Check your /etc/hosts file, make sure it's pointing to right virtual host.

Restart apache:
sudo service apache2 restart

Title: View doesn't return anything in Laravel

Body:
I just started to learn the laravel framework and have a strange situation here.

First of all in my web.php I have code like:

<?php
Route::get('/', function () {
    return view('welcome');
});

Route::get('users', ['uses' => 'UsersController@index']);

In my UsersController.php file I have code like:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UsersController extends Controller
{
    public function index(){
        return view('users.index');
    }
}

I have a file named index.blade.php in directory views/users that has the same content as the default welcome.blade.php. But when I try to return view('users.index'); there is no result (no error, or text) but when I try to return view('welcome'); it works just fine.

The directory and the file truly exists.
I'm using Macbook Pro.

welcome.blade.php and the /users/index.blade.php content (default welcome page):

<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">

            @if (Route::has('login'))

                    @if (Auth::check())
                        Home
                    @else
                        Login
                        Register
                    @endif

            @endif

                    Laravel

                    Documentation
                    Laracasts
                    News
                    Forge
                    GitHub


问:
iPhone icon size
I am developing an application for iPhone to support multiple devices, iPhone 2-4. I had an issue with the app icon as it was shown pixelated in the iPhone 4 simulator so I have used a new image with higher resolution (300 x 300) to be precise. On the simulator its showing fine for both iPhone 4 and the iPhone device simulators. However, when I ported my app to an iPhone 3 actual device the icon did not show at all and instead I get a blank white icon. I don't have an iPhone 4 yet so I cant tell if the same issue will happen on the physical device.

I am not sure what is the best dimensions/dpi to use for an icon to display perfectly on an iPhone 4 and older devices? Would appreciate a help if possible..

答: You can set the various icon image names in the plist, under "icon files".</p>

Title: iPhone icon size