问:
Tensorflow model.train() not looping through all data
I'm trying to train a model for mnist.

```<code>import tensorflow as tf

mnist = tf.keras.datasets.mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

print(x_train.shape)
</code>```

What i got is (60000, 28, 28), there are 60,000 items in the data set.

Then, I create the model with the following code.

```<code>model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(10)
])

loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
model.compile(optimizer='adam',
              loss=loss_fn,
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=5)
</code>```

However, I got only 1875 items for each epoch.

```<code>2020-06-02 04:33:45.706474: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-06-02 04:33:45.706617: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
2020-06-02 04:33:47.437837: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'nvcuda.dll'; dlerror: nvcuda.dll not found
2020-06-02 04:33:47.437955: E tensorflow/stream_executor/cuda/cuda_driver.cc:313] failed call to cuInit: UNKNOWN ERROR (303)
2020-06-02 04:33:47.441329: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:169] retrieving CUDA diagnostic information for host: DESKTOP-H3BEO7F
2020-06-02 04:33:47.441480: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:176] hostname: DESKTOP-H3BEO7F
2020-06-02 04:33:47.441876: I tensorflow/core/platform/cpu_feature_guard.cc:143] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
2020-06-02 04:33:47.448274: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x27fc6b2c210 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-06-02 04:33:47.448427: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version
Epoch 1/5
1875/1875 [==============================] - 1s 664us/step - loss: 0.2971 - accuracy: 0.9140
Epoch 2/5
1875/1875 [==============================] - 1s 661us/step - loss: 0.1421 - accuracy: 0.9582
Epoch 3/5
1875/1875 [==============================] - 1s 684us/step - loss: 0.1068 - accuracy: 0.9675
Epoch 4/5
1875/1875 [==============================] - 1s 695us/step - loss: 0.0868 - accuracy: 0.9731
Epoch 5/5
1875/1875 [==============================] - 1s 682us/step - loss: 0.0764 - accuracy: 0.9762

Process finished with exit code 0

</code>```

答:
You are using the whole data, no worries!

Due to the Keras documentation, https://github.com/keras-team/keras/blob/master/keras/engine/training.py
 when you use model.fit and you do not specify the batch size, it got assigned to 32 by default.

batch_size     Integer or NULL. Number of samples per gradient update. If
  unspecified, batch_size will default to 32

It means that for each epoch you have 1875 steps, and in each step, your model has taken 32 data examples into the account. And guess what, 1875*32 is equal to 60,000.

Body:
I'm trying to train a model for mnist.

import tensorflow as tf

mnist = tf.keras.datasets.mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

print(x_train.shape)

What i got is (60000, 28, 28), there are 60,000 items in the data set.

Then, I create the model with the following code.

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(10)
])

loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
model.compile(optimizer='adam',
              loss=loss_fn,
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=5)

However, I got only 1875 items for each epoch.

2020-06-02 04:33:45.706474: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-06-02 04:33:45.706617: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
2020-06-02 04:33:47.437837: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'nvcuda.dll'; dlerror: nvcuda.dll not found
2020-06-02 04:33:47.437955: E tensorflow/stream_executor/cuda/cuda_driver.cc:313] failed call to cuInit: UNKNOWN ERROR (303)
2020-06-02 04:33:47.441329: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:169] retrieving CUDA diagnostic information for host: DESKTOP-H3BEO7F
2020-06-02 04:33:47.441480: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:176] hostname: DESKTOP-H3BEO7F
2020-06-02 04:33:47.441876: I tensorflow/core/platform/cpu_feature_guard.cc:143] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
2020-06-02 04:33:47.448274: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x27fc6b2c210 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-06-02 04:33:47.448427: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version
Epoch 1/5
1875/1875 [==============================] - 1s 664us/step - loss: 0.2971 - accuracy: 0.9140
Epoch 2/5
1875/1875 [==============================] - 1s 661us/step - loss: 0.1421 - accuracy: 0.9582
Epoch 3/5
1875/1875 [==============================] - 1s 684us/step - loss: 0.1068 - accuracy: 0.9675
Epoch 4/5
1875/1875 [==============================] - 1s 695us/step - loss: 0.0868 - accuracy: 0.9731
Epoch 5/5
1875/1875 [==============================] - 1s 682us/step - loss: 0.0764 - accuracy: 0.9762

Process finished with exit code 0


来源: stackexchange

问:
$filter not working in JPA/Olingo 2.0.11 with MySQL
Olingo2 version 2.0.11 has problem with spring-boot-starter-web version 2.0.0 or above!

I made an odata service with olingo2, jpa and spring-boot based on this GitHub repository.

I've set up the project to use MariaDB database and it works quiet good.

However, the project is a little bit old and I tried to upgrade it!

If you check its pom.xml in GitHub you will see the following details:

...
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.2.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.7</java.version>
        <cxf.version>3.1.5</cxf.version>
        <olingo.version>2.0.6</olingo.version>
    </properties>
...
```

<p>In the first step I tried to update the libraries versions like this:</p>

<pre class="lang-xml prettyprint-override"><code>    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
        <cxf.version>3.3.6</cxf.version>
        <olingo.version>2.0.11</olingo.version>
    </properties>
</code>```

As soon as I do this upgrade, I needed to update two imports in the CxfServletRegister.java and Application.java files as following:

/* In file: odata-boilerplate/src/main/java/com/penninkhof/odata/utils/CxfServletRegister.java
*/
// import org.springframework.boot.context.embedded.ServletRegistrationBean; <- old class replace with
import org.springframework.boot.web.servlet.ServletRegistrationBean; // <- new address
```

<p>and</p>

<pre class="lang-java prettyprint-override"><code>/* In file: odata-boilerplate/src/main/java/com/penninkhof/odata/Application.java
*/
//import org.springframework.boot.context.web.SpringBootServletInitializer; <-- old class replace with
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; // <- new address
</code>```

By these simple changes I could run the app again with command mvn spring-boot:run -P jar.

However I understood in the latest version of spring boot which is version 2.3.0.RELEASE it will run a new instance of the server each time a request is arrived.

Until here also everything seems fine. However there is a small issue!

While I have set the dialect value in the odata-boilerplate/src/main/resources/application.properties file like this:

```<code># WEB SERVER
server.port=9090

# MARIADB DATA SOURCE
spring.datasource.url = jdbc:mariadb://localhost:3306/cimply_ask?useUnicode=yes&characterEncoding=UTF-8
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.username = root
spring.datasource.password =
spring.datasource.testWhileIdle = false
spring.datasource.validationQuery = SELECT 1

# JPA / HIBERNATE
spring.jpa.database-platform=org.hibernate.dialect.MariaDBDialect
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MariaDBDialect
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.hibernate.auto_quote_keyword=true
</code>```

it is only set in a thread (or task) that is responsible for initiating the database initial values! Here is part of the console output. As it can be seen the logs are belonged to thread task-1 and in the line 6 it has set the correct dialect for the thread.

```<code>1- 22:22:29.075 [task-1] INFO  org.hibernate.jpa.internal.util.LogHelper - HHH000204: Processing PersistenceUnitInfo [name: default]
2- 22:22:29.177 [task-1] INFO  org.hibernate.Version - HHH000412: Hibernate ORM core version 5.4.15.Final
3- 22:22:29.459 [task-1] INFO  org.hibernate.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
4- 22:22:29.715 [task-1] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
5- 22:22:29.817 [task-1] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Start completed.
6- 22:22:29.840 [task-1] INFO  org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.MariaDBDialect
7- 22:22:31.067 [task-1] INFO  o.h.e.t.jta.platform.internal.JtaPlatformInitiator - HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
8- 22:22:31.317 [task-1] INFO  o.s.orm.jpa.LocalContainerEntityManagerFactoryBean - Initialized JPA EntityManagerFactory for persistence unit 'default'
</code>```

But what would happen when a request is arrived?

For example when I try the following request that I use a filtering on a column of type string:

```<code>http://localhost:9090/odata.svc/Members?$format=json&$filter=FirstName eq 'Jack'
</code>```

I receive an error message in response to my request in postman or browser, like this:

```<code>{
    "error": {
        "code": null,
        "message": {
            "lang": "en",
            "value": "org.hibernate.exception.SQLGrammarException: could not extract ResultSet"
        }
    }
}
</code>```

It actually generates a wrong query on database as it does not set the correct dialect. Here is the console output in my application:

```<code>22:56:52.593 [http-nio-9090-exec-1] INFO  org.apache.cxf.endpoint.ServerImpl - Setting the server's publish address to be /
22:57:22.605 [http-nio-9090-exec-1] WARN  org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 1064, SQLState: 42000
22:57:22.606 [http-nio-9090-exec-1] ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - You have an error in your SQL syntax; check the manual that corresponds
to your MariaDB server version for the right syntax to use near ''\'' at line 1
</code>```

What is the problem here? It uses escape '\' instead of escape '\\' in the query as it does not set the correct dialect based on the database type!

What I need to do? I need to know how can I set the correct dialect for the instance that is responsible for responding a request in this app?

Please take these points also in to account:

By upgrading this app to use the latest version of spring-boot-starter it will make a new thread each time a new request is arrived. You can send the same request and you will see the thread name will change as follow: [http-nio-9090-exec-2], [http-nio-9090-exec-3], [http-nio-9090-exec-1], ... sometimes even the old threads are used!

Each time a new request will be arrived the following part of the code is the entry point for processing the request. Maybe this is the place that I must set the dialect for the thread!

/* File: odata-boilerplate/src/main/java/com/penninkhof/odata/utils/JPAServiceFactory.java
*/

import javax.persistence.EntityManagerFactory;

import org.apache.olingo.odata2.jpa.processor.api.ODataJPAContext;
import org.apache.olingo.odata2.jpa.processor.api.ODataJPAServiceFactory;
import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPARuntimeException;

public class JPAServiceFactory extends ODataJPAServiceFactory {
    public static final String DEFAULT_ENTITY_UNIT_NAME = "Model";
    public static final String ENTITY_MANAGER_FACTORY_ID = "entityManagerFactory";

    @Override
    public ODataJPAContext initializeODataJPAContext() throws ODataJPARuntimeException {
        ODataJPAContext oDataJPAContext = getODataJPAContext();

        EntityManagerFactory factory = (EntityManagerFactory) SpringContextsUtil.getBean(ENTITY_MANAGER_FACTORY_ID);

        oDataJPAContext.setEntityManagerFactory(factory);
        oDataJPAContext.setPersistenceUnitName(DEFAULT_ENTITY_UNIT_NAME);
        oDataJPAContext.setJPAEdmExtension(new JPAEdmExtension());
        ODataContextUtil.setODataContext(oDataJPAContext.getODataContext());

        return oDataJPAContext;
    }
}
```

This question is a little bit long but I tried to explained all my investigations and work around. I need to know how can I set a default dialect that all threads in the application use that! As I mentioned earlier I tried to do it in the application.properties file but it seems it will be ignored in the time of request processing!

答:
Does not solve the original issue and is not the most efficient way..
but here is a workaround for how to remove the incorrect 'escape' statement with only one slash:

```<code>public class SqlStatementInspector implements StatementInspector {

    private static final long serialVersionUID = 1L;
    private static final Logger LOG = Logger.getLogger(SqlStatementInspector.class);

    @Override
    public String inspect(String sql) {
        if (!sql.contains("escape \'\\'")) {
            return sql;
        }
        // OData JPA query correction -> current version (2.0.11) contains
        // the invalid 'escape "\"' statement that delivers no results
        LOG.info("Replacing invalid statement: escape \"\\\"");
        return sql.replace("escape \'\\'", "");
    }
}
</code>```

This overwrites the inspect method and you can modify the generated sql query when using hibernate

in my persistence.xml file i then need to set the property "hibernate.session_factory.statement_inspector" to connect my StatementInspector implementation with my hibernate session factory

```<code><property
                name="hibernate.session_factory.statement_inspector"
                value="SqlStatementInspector" />
</code>```

i don't know how exactly this would work with spring-boot but maybe there is a similiar property for your application.properties?

ContentLicense: CC BY-SA 4.0

Body:
Olingo2 version 2.0.11 has problem with spring-boot-starter-web version 2.0.0 or above!

I made an odata service with olingo2, jpa and spring-boot based on this GitHub repository.

I've set up the project to use MariaDB database and it works quiet good.

However, the project is a little bit old and I tried to upgrade it!

If you check its pom.xml in GitHub you will see the following details:

...
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.2.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.7</java.version>
        <cxf.version>3.1.5</cxf.version>
        <olingo.version>2.0.6</olingo.version>
    </properties>
...

In the first step I tried to update the libraries versions like this:

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
        <cxf.version>3.3.6</cxf.version>
        <olingo.version>2.0.11</olingo.version>
    </properties>

As soon as I do this upgrade, I needed to update two imports in the CxfServletRegister.java and Application.java files as following:

/* In file: odata-boilerplate/src/main/java/com/penninkhof/odata/utils/CxfServletRegister.java
*/
// import org.springframework.boot.context.embedded.ServletRegistrationBean; <- old class replace with
import org.springframework.boot.web.servlet.ServletRegistrationBean; // <- new address

and

/* In file: odata-boilerplate/src/main/java/com/penninkhof/odata/Application.java
*/
//import org.springframework.boot.context.web.SpringBootServletInitializer; <-- old class replace with
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; // <- new address

By these simple changes I could run the app again with command mvn spring-boot:run -P jar.

However I understood in the latest version of spring boot which is version 2.3.0.RELEASE it will run a new instance of the server each time a request is arrived.

Until here also everything seems fine. However there is a small issue!

While I have set the dialect value in the odata-boilerplate/src/main/resources/application.properties file like this:

# WEB SERVER
server.port=9090

# MARIADB DATA SOURCE
spring.datasource.url = jdbc:mariadb://localhost:3306/cimply_ask?useUnicode=yes&characterEncoding=UTF-8
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.username = root
spring.datasource.password =
spring.datasource.testWhileIdle = false
spring.datasource.validationQuery = SELECT 1

# JPA / HIBERNATE
spring.jpa.database-platform=org.hibernate.dialect.MariaDBDialect
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MariaDBDialect
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.hibernate.auto_quote_keyword=true

it is only set in a thread (or task) that is responsible for initiating the database initial values! Here is part of the console output. As it can be seen the logs are belonged to thread task-1 and in the line 6 it has set the correct dialect for the thread.

1- 22:22:29.075 [task-1] INFO  org.hibernate.jpa.internal.util.LogHelper - HHH000204: Processing PersistenceUnitInfo [name: default]
2- 22:22:29.177 [task-1] INFO  org.hibernate.Version - HHH000412: Hibernate ORM core version 5.4.15.Final
3- 22:22:29.459 [task-1] INFO  org.hibernate.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
4- 22:22:29.715 [task-1] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
5- 22:22:29.817 [task-1] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Start completed.
6- 22:22:29.840 [task-1] INFO  org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.MariaDBDialect
7- 22:22:31.067 [task-1] INFO  o.h.e.t.jta.platform.internal.JtaPlatformInitiator - HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
8- 22:22:31.317 [task-1] INFO  o.s.orm.jpa.LocalContainerEntityManagerFactoryBean - Initialized JPA EntityManagerFactory for persistence unit 'default'

But what would happen when a request is arrived?

For example when I try the following request that I use a filtering on a column of type string:

http://localhost:9090/odata.svc/Members?$format=json&$filter=FirstName eq 'Jack'

I receive an error message in response to my request in postman or browser, like this:

{
    "error": {
        "code": null,
        "message": {
            "lang": "en",
            "value": "org.hibernate.exception.SQLGrammarException: could not extract ResultSet"
        }
    }
}

It actually generates a wrong query on database as it does not set the correct dialect. Here is the console output in my application:

22:56:52.593 [http-nio-9090-exec-1] INFO  org.apache.cxf.endpoint.ServerImpl - Setting the server's publish address to be /
22:57:22.605 [http-nio-9090-exec-1] WARN  org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 1064, SQLState: 42000
22:57:22.606 [http-nio-9090-exec-1] ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - You have an error in your SQL syntax; check the manual that corresponds
to your MariaDB server version for the right syntax to use near ''\'' at line 1

What is the problem here? It uses escape '\' instead of escape '\\' in the query as it does not set the correct dialect based on the database type!

What I need to do? I need to know how can I set the correct dialect for the instance that is responsible for responding a request in this app?

Please take these points also in to account:

By upgrading this app to use the latest version of spring-boot-starter it will make a new thread each time a new request is arrived. You can send the same request and you will see the thread name will change as follow: [http-nio-9090-exec-2], [http-nio-9090-exec-3], [http-nio-9090-exec-1], ... sometimes even the old threads are used!

Each time a new request will be arrived the following part of the code is the entry point for processing the request. Maybe this is the place that I must set the dialect for the thread!

/* File: odata-boilerplate/src/main/java/com/penninkhof/odata/utils/JPAServiceFactory.java
*/

import javax.persistence.EntityManagerFactory;

import org.apache.olingo.odata2.jpa.processor.api.ODataJPAContext;
import org.apache.olingo.odata2.jpa.processor.api.ODataJPAServiceFactory;
import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPARuntimeException;

public class JPAServiceFactory extends ODataJPAServiceFactory {
    public static final String DEFAULT_ENTITY_UNIT_NAME = "Model";
    public static final String ENTITY_MANAGER_FACTORY_ID = "entityManagerFactory";

    @Override
    public ODataJPAContext initializeODataJPAContext() throws ODataJPARuntimeException {
        ODataJPAContext oDataJPAContext = getODataJPAContext();

        EntityManagerFactory factory = (EntityManagerFactory) SpringContextsUtil.getBean(ENTITY_MANAGER_FACTORY_ID);

        oDataJPAContext.setEntityManagerFactory(factory);
        oDataJPAContext.setPersistenceUnitName(DEFAULT_ENTITY_UNIT_NAME);
        oDataJPAContext.setJPAEdmExtension(new JPAEdmExtension());
        ODataContextUtil.setODataContext(oDataJPAContext.getODataContext());

        return oDataJPAContext;
    }
}

This question is a little bit long but I tried to explained all my investigations and work around. I need to know how can I set a default dialect that all threads in the application use that! As I mentioned earlier I tried to do it in the application.properties file but it seems it will be ignored in the time of request processing!

Body:
Does not solve the original issue and is not the most efficient way..
but here is a workaround for how to remove the incorrect 'escape' statement with only one slash:

public class SqlStatementInspector implements StatementInspector {

    private static final long serialVersionUID = 1L;
    private static final Logger LOG = Logger.getLogger(SqlStatementInspector.class);

    @Override
    public String inspect(String sql) {
        if (!sql.contains("escape \'\\'")) {
            return sql;
        }
        // OData JPA query correction -> current version (2.0.11) contains
        // the invalid 'escape "\"' statement that delivers no results
        LOG.info("Replacing invalid statement: escape \"\\\"");
        return sql.replace("escape \'\\'", "");
    }
}

This overwrites the inspect method and you can modify the generated sql query when using hibernate

in my persistence.xml file i then need to set the property "hibernate.session_factory.statement_inspector" to connect my StatementInspector implementation with my hibernate session factory

<property
                name="hibernate.session_factory.statement_inspector"
                value="SqlStatementInspector" />

i don't know how exactly this would work with spring-boot but maybe there is a similiar property for your application.properties?


问:
RabbitMQ + .NET C#: Low and variable performances on message publishing + consuming
I'm trying to improve the performances of publishing and consuming messages with RabbitMQ + .NET C#.

I've defined the relatively "big" xml file (as an embedded resource) below:

<?xml version="1.0" encoding="UTF-8"?>
<Document>
  <CstmrCdtTrfInitn>
    <GrpHdr>
      <MsgId>ABC/090928/CCT001</MsgId>
      <CreDtTm>2009-09-28T14:07:00</CreDtTm>
      <NbOfTxs>3</NbOfTxs>
      <CtrlSum>11500000</CtrlSum>
      <InitgPty>
        <Nm>ABC Corporation</Nm>
        <PstlAdr>
          <StrtNm>Times Square</StrtNm>
          <BldgNb>7</BldgNb>
          <PstCd>NY 10036</PstCd>
          <TwnNm>New York</TwnNm>
          <Ctry>US</Ctry>
        </PstlAdr>
      </InitgPty>
    </GrpHdr>
    <PmtInf>
      <PmtInfId>ABC/086</PmtInfId>
      <PmtMtd>TRF</PmtMtd>
      <BtchBookg>false</BtchBookg>
      <ReqdExctnDt>2009-09-29</ReqdExctnDt>
      <Dbtr>
        <Nm>ABC Corporation</Nm>
        <PstlAdr>
          <StrtNm>Times Square</StrtNm>
          <BldgNb>7</BldgNb>
          <PstCd>NY 10036</PstCd>
          <TwnNm>New York</TwnNm>
          <Ctry>US</Ctry>
        </PstlAdr>
      </Dbtr>
      <DbtrAcct>
        <Id>
          <Othr>
            <Id>00125574999</Id>
          </Othr>
        </Id>
      </DbtrAcct>
      <DbtrAgt>
        <FinInstnId>
          <BIC>BBBBUS33</BIC>
        </FinInstnId>
      </DbtrAgt>
      <CdtTrfTxInf>
        <PmtId>
          <InstrId>ABC/090928/CCT001/01</InstrId>
          <EndToEndId>ABC/4562/2009-09-08</EndToEndId>
        </PmtId>
        <Amt>
          <InstdAmt Ccy="JPY">10000000</InstdAmt>
        </Amt>
        <ChrgBr>SHAR</ChrgBr>
        <CdtrAgt>
          <FinInstnId>
            <BIC>AAAAGB2L</BIC>
          </FinInstnId>
        </CdtrAgt>
        <Cdtr>
          <Nm>DEF Electronics</Nm>
          <PstlAdr>
            <AdrLine>Corn Exchange 5th Floor</AdrLine>
            <AdrLine>Mark Lane 55</AdrLine>
            <AdrLine>EC3R7NE London</AdrLine>
            <AdrLine>GB</AdrLine>
          </PstlAdr>
        </Cdtr>
        <CdtrAcct>
          <Id>
            <Othr>
              <Id>23683707994125</Id>
            </Othr>
          </Id>
        </CdtrAcct>
        <Purp>
          <Cd>CINV</Cd>
        </Purp>
        <RmtInf>
          <Strd>
            <RfrdDocInf>
              <Nb>4562</Nb>
              <RltdDt>2009-09-08</RltdDt>
            </RfrdDocInf>
          </Strd>
        </RmtInf>
      </CdtTrfTxInf>
      <CdtTrfTxInf>
        <PmtId>
          <InstrId>ABC/090628/CCT001/2</InstrId>
          <EndToEndId>ABC/ABC-13679/2009-09-15</EndToEndId>
        </PmtId>
        <Amt>
          <InstdAmt Ccy="EUR">500000</InstdAmt>
        </Amt>
        <ChrgBr>CRED</ChrgBr>
        <CdtrAgt>
          <FinInstnId>
            <BIC>DDDDBEBB</BIC>
          </FinInstnId>
        </CdtrAgt>
        <Cdtr>
          <Nm>GHI Semiconductors</Nm>
          <PstlAdr>
            <StrtNm>Avenue Brugmann</StrtNm>
            <BldgNb>415</BldgNb>
            <PstCd>1180</PstCd>
            <TwnNm>Brussels</TwnNm>
          </PstlAdr>
        </Cdtr>
        <CdtrAcct>
          <Id>
            <IBAN>BE30001216371411</IBAN>
          </Id>
        </CdtrAcct>
        <InstrForCdtrAgt>
          <Cd>PHOB</Cd>
          <InstrInf>+32/2/2222222</InstrInf>
        </InstrForCdtrAgt>
        <Purp>
          <Cd>GDDS</Cd>
        </Purp>
        <RmtInf>
          <Strd>
            <RfrdDocInf>
              <Tp>
                <CdOrPrtry>
                  <Cd>CINV</Cd>
                </CdOrPrtry>
              </Tp>
              <Nb>ABC-13679</Nb>
              <RltdDt>2009-09-15</RltdDt>
            </RfrdDocInf>
          </Strd>
        </RmtInf>
      </CdtTrfTxInf>
      <CdtTrfTxInf>
        <PmtId>
          <InstrId>ABC/090928/CCT001/3</InstrId>
          <EndToEndId>ABC/987-AC/2009-09-27</EndToEndId>
        </PmtId>
        <Amt>
          <InstdAmt Ccy="USD">1000000</InstdAmt>
        </Amt>
        <ChrgBr>SHAR</ChrgBr>
        <CdtrAgt>
          <FinInstnId>
            <BIC>BBBBUS66</BIC>
          </FinInstnId>
        </CdtrAgt>
        <Cdtr>
          <Nm>ABC Corporation</Nm>
          <PstlAdr>
            <Dept>Treasury department</Dept>
            <StrtNm>Bush Street</StrtNm>
            <BldgNb>13</BldgNb>
            <PstCd>CA 94108</PstCd>
            <TwnNm>San Francisco</TwnNm>
            <Ctry>US</Ctry>
          </PstlAdr>
        </Cdtr>
        <CdtrAcct>
          <Id>
            <Othr>
              <Id>4895623</Id>
            </Othr>
          </Id>
        </CdtrAcct>
        <Purp>
          <Cd>INTC</Cd>
        </Purp>
        <RmtInf>
          <Strd>
            <RfrdDocInf>
              <Tp>
                <CdOrPrtry>
                  <Cd>CINV</Cd>
                </CdOrPrtry>
              </Tp>
              <Nb>987-AC</Nb>
              <RltdDt>2009-09-27</RltdDt>
            </RfrdDocInf>
          </Strd>
        </RmtInf>
      </CdtTrfTxInf>
    </PmtInf>
  </CstmrCdtTrfInitn>
</Document>
```

<p>Then I publish that file above about 500,000 times to the same queue, publishing and consuming happen in the same .NET Core C# program below: </p>

<p>.NET C# Code:</p>

<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

using RabbitMQ.Client;
using RabbitMQ.Client.Events;

namespace CSharpPlayground
{
    public static class EmbeddedResource
    {
        public static string Load(string fileName)
        {
            var executingAssembly = Assembly.GetExecutingAssembly();
            var resource = $"{executingAssembly.ManifestModule.Name.Replace(".dll", string.Empty)}.{fileName}";
            using var stream = executingAssembly.GetManifestResourceStream(resource);
            using var streamReader = new StreamReader(stream!);
            return streamReader.ReadToEnd();
        }
    }

    public static class CheapExtensions
    {
        public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
        {
            foreach(var item in source)
            {
                action(item);
            }
        }
        public static void ForEach<T>(this IEnumerable<T> source) =>
            source.ForEach(item => {});
    }

    public static class Program
    {
        private static readonly string XmlStuff = EmbeddedResource.Load("XmlStuff.xml");

        public static void Main()
        {
            const string queueName = "hello";
            var factory = new ConnectionFactory
            {
                HostName = "localhost",
                DispatchConsumersAsync = true
            };
            using var connection = factory.CreateConnection();
            using var queueDeclareChannel = connection.CreateModel();

            queueDeclareChannel.QueueDeclare(
                queue: queueName,
                durable: true,
                exclusive: false,
                autoDelete: false,
                arguments: null);

            using var consumerChannel = connection.CreateModel();
            var consumer = new AsyncEventingBasicConsumer(consumerChannel);
            consumer.Received += async (sender, eventArgs) =>
            {
                var receivedBody = eventArgs.Body;
                var receivedMessage = Encoding.UTF8.GetString(receivedBody.ToArray());
                //Console.WriteLine($"[x] Received stuff");
            };
            consumerChannel.BasicConsume(
                queue: queueName,
                autoAck: true,
                consumer: consumer);

            var messageToSend = XmlStuff;
            var bodyToSend = new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(messageToSend));

            Enumerable
                .Repeat((messageToSend, bodyToSend), 500_000)
                .AsParallel()
                .Select((data, index) =>
                {
                    var (message, body) = data;
                    using var publishChannel = connection.CreateModel();
                    var basicProperties = publishChannel.CreateBasicProperties();
                    publishChannel.BasicPublish(
                        exchange: "",
                        routingKey: queueName,
                        mandatory: false,
                        basicProperties: basicProperties,
                        body: body);
                    //Console.WriteLine($"[x] Sent stuff"
                    return index;
                }).ForEach();

            Console.ReadKey();
        }
    }
}
</code>```

I've tried to the extent possible to remove the Console.WriteLine calls to circumvent the bottleneck of pushing something to standard output.

It turns out that the performances seem rather low, and I'm wondering if the performances I have (in terms of message rates) are somehow "normal":

答:
I'm not a RabbitMQ expert, but I do know the creation of a channel (CreateModel()) per message to publish is a RabbitMQ anti-pattern and will hurt performance. That's because every channel creation requires a network round-trip to the broker. The approach also risks exhausting the broker.

Unfortunately, many of the getting started with RabbitMQ blogs start this way, probably because it simplifies the problem. The problem, so to speak, is that a channel is not thread-safe.

If you wanted to write your own messaging framework on top of RabbitMQ then I would start with a single publish channel and use a lock to synchronize it.

If you wanted to build a real application, avoid re-inventing the wheel, and many headaches, I would take a look at a number of well supported open source frameworks, such as EasyNetQ or MassTransit.

Body:
I'm trying to improve the performances of publishing and consuming messages with RabbitMQ + .NET C#.

I've defined the relatively "big" xml file (as an embedded resource) below:

<?xml version="1.0" encoding="UTF-8"?>
<Document>
  <CstmrCdtTrfInitn>
    <GrpHdr>
      <MsgId>ABC/090928/CCT001</MsgId>
      <CreDtTm>2009-09-28T14:07:00</CreDtTm>
      <NbOfTxs>3</NbOfTxs>
      <CtrlSum>11500000</CtrlSum>
      <InitgPty>
        <Nm>ABC Corporation</Nm>
        <PstlAdr>
          <StrtNm>Times Square</StrtNm>
          <BldgNb>7</BldgNb>
          <PstCd>NY 10036</PstCd>
          <TwnNm>New York</TwnNm>
          <Ctry>US</Ctry>
        </PstlAdr>
      </InitgPty>
    </GrpHdr>
    <PmtInf>
      <PmtInfId>ABC/086</PmtInfId>
      <PmtMtd>TRF</PmtMtd>
      <BtchBookg>false</BtchBookg>
      <ReqdExctnDt>2009-09-29</ReqdExctnDt>
      <Dbtr>
        <Nm>ABC Corporation</Nm>
        <PstlAdr>
          <StrtNm>Times Square</StrtNm>
          <BldgNb>7</BldgNb>
          <PstCd>NY 10036</PstCd>
          <TwnNm>New York</TwnNm>
          <Ctry>US</Ctry>
        </PstlAdr>
      </Dbtr>
      <DbtrAcct>
        <Id>
          <Othr>
            <Id>00125574999</Id>
          </Othr>
        </Id>
      </DbtrAcct>
      <DbtrAgt>
        <FinInstnId>
          <BIC>BBBBUS33</BIC>
        </FinInstnId>
      </DbtrAgt>
      <CdtTrfTxInf>
        <PmtId>
          <InstrId>ABC/090928/CCT001/01</InstrId>
          <EndToEndId>ABC/4562/2009-09-08</EndToEndId>
        </PmtId>
        <Amt>
          <InstdAmt Ccy="JPY">10000000</InstdAmt>
        </Amt>
        <ChrgBr>SHAR</ChrgBr>
        <CdtrAgt>
          <FinInstnId>
            <BIC>AAAAGB2L</BIC>
          </FinInstnId>
        </CdtrAgt>
        <Cdtr>
          <Nm>DEF Electronics</Nm>
          <PstlAdr>
            <AdrLine>Corn Exchange 5th Floor</AdrLine>
            <AdrLine>Mark Lane 55</AdrLine>
            <AdrLine>EC3R7NE London</AdrLine>
            <AdrLine>GB</AdrLine>
          </PstlAdr>
        </Cdtr>
        <CdtrAcct>
          <Id>
            <Othr>
              <Id>23683707994125</Id>
            </Othr>
          </Id>
        </CdtrAcct>
        <Purp>
          <Cd>CINV</Cd>
        </Purp>
        <RmtInf>
          <Strd>
            <RfrdDocInf>
              <Nb>4562</Nb>
              <RltdDt>2009-09-08</RltdDt>
            </RfrdDocInf>
          </Strd>
        </RmtInf>
      </CdtTrfTxInf>
      <CdtTrfTxInf>
        <PmtId>
          <InstrId>ABC/090628/CCT001/2</InstrId>
          <EndToEndId>ABC/ABC-13679/2009-09-15</EndToEndId>
        </PmtId>
        <Amt>
          <InstdAmt Ccy="EUR">500000</InstdAmt>
        </Amt>
        <ChrgBr>CRED</ChrgBr>
        <CdtrAgt>
          <FinInstnId>
            <BIC>DDDDBEBB</BIC>
          </FinInstnId>
        </CdtrAgt>
        <Cdtr>
          <Nm>GHI Semiconductors</Nm>
          <PstlAdr>
            <StrtNm>Avenue Brugmann</StrtNm>
            <BldgNb>415</BldgNb>
            <PstCd>1180</PstCd>
            <TwnNm>Brussels</TwnNm>
          </PstlAdr>
        </Cdtr>
        <CdtrAcct>
          <Id>
            <IBAN>BE30001216371411</IBAN>
          </Id>
        </CdtrAcct>
        <InstrForCdtrAgt>
          <Cd>PHOB</Cd>
          <InstrInf>+32/2/2222222</InstrInf>
        </InstrForCdtrAgt>
        <Purp>
          <Cd>GDDS</Cd>
        </Purp>
        <RmtInf>
          <Strd>
            <RfrdDocInf>
              <Tp>
                <CdOrPrtry>
                  <Cd>CINV</Cd>
                </CdOrPrtry>
              </Tp>
              <Nb>ABC-13679</Nb>
              <RltdDt>2009-09-15</RltdDt>
            </RfrdDocInf>
          </Strd>
        </RmtInf>
      </CdtTrfTxInf>
      <CdtTrfTxInf>
        <PmtId>
          <InstrId>ABC/090928/CCT001/3</InstrId>
          <EndToEndId>ABC/987-AC/2009-09-27</EndToEndId>
        </PmtId>
        <Amt>
          <InstdAmt Ccy="USD">1000000</InstdAmt>
        </Amt>
        <ChrgBr>SHAR</ChrgBr>
        <CdtrAgt>
          <FinInstnId>
            <BIC>BBBBUS66</BIC>
          </FinInstnId>
        </CdtrAgt>
        <Cdtr>
          <Nm>ABC Corporation</Nm>
          <PstlAdr>
            <Dept>Treasury department</Dept>
            <StrtNm>Bush Street</StrtNm>
            <BldgNb>13</BldgNb>
            <PstCd>CA 94108</PstCd>
            <TwnNm>San Francisco</TwnNm>
            <Ctry>US</Ctry>
          </PstlAdr>
        </Cdtr>
        <CdtrAcct>
          <Id>
            <Othr>
              <Id>4895623</Id>
            </Othr>
          </Id>
        </CdtrAcct>
        <Purp>
          <Cd>INTC</Cd>
        </Purp>
        <RmtInf>
          <Strd>
            <RfrdDocInf>
              <Tp>
                <CdOrPrtry>
                  <Cd>CINV</Cd>
                </CdOrPrtry>
              </Tp>
              <Nb>987-AC</Nb>
              <RltdDt>2009-09-27</RltdDt>
            </RfrdDocInf>
          </Strd>
        </RmtInf>
      </CdtTrfTxInf>
    </PmtInf>
  </CstmrCdtTrfInitn>
</Document>

Then I publish that file above about 500,000 times to the same queue, publishing and consuming happen in the same .NET Core C# program below:

.NET C# Code:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

using RabbitMQ.Client;
using RabbitMQ.Client.Events;

namespace CSharpPlayground
{
    public static class EmbeddedResource
    {
        public static string Load(string fileName)
        {
            var executingAssembly = Assembly.GetExecutingAssembly();
            var resource = $"{executingAssembly.ManifestModule.Name.Replace(".dll", string.Empty)}.{fileName}";
            using var stream = executingAssembly.GetManifestResourceStream(resource);
            using var streamReader = new StreamReader(stream!);
            return streamReader.ReadToEnd();
        }
    }

    public static class CheapExtensions
    {
        public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
        {
            foreach(var item in source)
            {
                action(item);
            }
        }
        public static void ForEach<T>(this IEnumerable<T> source) =>
            source.ForEach(item => {});
    }

    public static class Program
    {
        private static readonly string XmlStuff = EmbeddedResource.Load("XmlStuff.xml");

        public static void Main()
        {
            const string queueName = "hello";
            var factory = new ConnectionFactory
            {
                HostName = "localhost",
                DispatchConsumersAsync = true
            };
            using var connection = factory.CreateConnection();
            using var queueDeclareChannel = connection.CreateModel();

            queueDeclareChannel.QueueDeclare(
                queue: queueName,
                durable: true,
                exclusive: false,
                autoDelete: false,
                arguments: null);

            using var consumerChannel = connection.CreateModel();
            var consumer = new AsyncEventingBasicConsumer(consumerChannel);
            consumer.Received += async (sender, eventArgs) =>
            {
                var receivedBody = eventArgs.Body;
                var receivedMessage = Encoding.UTF8.GetString(receivedBody.ToArray());
                //Console.WriteLine($"[x] Received stuff");
            };
            consumerChannel.BasicConsume(
                queue: queueName,
                autoAck: true,
                consumer: consumer);

            var messageToSend = XmlStuff;
            var bodyToSend = new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(messageToSend));

            Enumerable
                .Repeat((messageToSend, bodyToSend), 500_000)
                .AsParallel()
                .Select((data, index) =>
                {
                    var (message, body) = data;
                    using var publishChannel = connection.CreateModel();
                    var basicProperties = publishChannel.CreateBasicProperties();
                    publishChannel.BasicPublish(
                        exchange: "",
                        routingKey: queueName,
                        mandatory: false,
                        basicProperties: basicProperties,
                        body: body);
                    //Console.WriteLine($"[x] Sent stuff"
                    return index;
                }).ForEach();

            Console.ReadKey();
        }
    }
}

I've tried to the extent possible to remove the Console.WriteLine calls to circumvent the bottleneck of pushing something to standard output.

It turns out that the performances seem rather low, and I'm wondering if the performances I have (in terms of message rates) are somehow "normal":


问:
Pass data to layout that are common to all pages
I have a website which have a layout page. However this layout page have data which all pages model must provide such page title, page name and the location where we actually are for an HTML helper I did which perform some action. Also each page have their own view models properties.

How can I do this? It seems that its a bad idea to type a layout but how do I pass theses infos?

答:
what i did is very simple and it's works

Declare Static property in any controller or you can make a data-class with static values if you want like this:

```<code>public static username = "Admin";
public static UserType = "Administrator";
</code>```

These values can be updated by the controllers based on operations.
later you can use them in your _Layout

In _layout.cshtml

```<code>@project_name.Controllers.HomeController.username
@project_name.Controllers.HomeController.UserType
</code>```

ContentLicense: CC BY-SA 3.0

Body:
what i did is very simple and it's works

Declare Static property in any controller or you can make a data-class with static values if you want like this:

public static username = "Admin";
public static UserType = "Administrator";

These values can be updated by the controllers based on operations.
later you can use them in your _Layout

In _layout.cshtml

@project_name.Controllers.HomeController.username
@project_name.Controllers.HomeController.UserType


问:
Join these 2 tables to get this specific output?
I am using SQL Server 2014. I am working on a query where I want to extract information from 2 specific tables to create my final output.

An extract of the 2 tables (Rebookings and ResaList) are given below.

Rebookings Table (each CancelledID has its corresponding RebookingID):

```<code>CancelledID            RebookingID
  102                     541
  250                     351
  129                     800
  ...
</code>```

ResaList Table:

```<code>ID      Property         ArrivalDate       RN
100       X              2020-05-22         9
102       X              2020-03-05         7
250       D              2020-04-12        10
129       E              2020-03-15         8
351       D              2020-09-23         5
541       X              2020-06-01         7
800       E              2020-07-11         8
...
</code>```

Here is my desired output:

```<code>ID       Property        ArrivalDate         RN    RebookingID        Rebooking_ArrivalDate    Rebooking_RN     Tag
102         X            2020-03-05           7       541              2020-06-01                   7           Cancelled
250         D            2020-04-12          10       351              2020-09-23                   5           Re-booked
129         E            2020-03-15           8       800              2020-07-11                   8           Re-booked
</code>```

This is what I have done so far:

```<code>USE [MyDatabase]

select
  a.[ID],
  a.[Property],
  a.[Arrival Date],
  a.[RN],
  b.[RebookingID],
  (CASE WHEN a.[ID] in (SELECT [CancelledID] FROM [Rebookings]) THEN 'Re-booked'
      ELSE 'Cancelled'
      END) as [Tag]
from [ResaList] a
LEFT JOIN [Rebookings] b on b.[CancelledID] = a.[ID]
where a.[ID] in (SELECT [CancelledID] FROM [Rebookings])
GROUP BY a.[ID], a.[Property], a.[ArrivalDate], b.[RebookingID]
</code>```

I am stuck at how to bring Rebooking_ArrivalDate and Rebooking_RN into the above output. Any help would be appreciated.

答:
I have tried this in SQL Server.

DECLARE @cancelled Table (cancelledId int, rebookingId int)

INSERT into @cancelled values
(102    , 541  ),
( 250   ,  351 ),
( 129   ,  800 );

DECLARE @ResaList TABLE(Id int, property CHAR(1), ArrivalDate date, RN int)

INSERT INTO @ResaList values
(100  ,'X','2020-05-22',  9),
(102  ,'X','2020-03-05',  7),
(250  ,'D','2020-04-12', 10),
(129  ,'E','2020-03-15',  8),
(351  ,'D','2020-09-23',  5),
(541  ,'X','2020-06-01',  7),
(800  ,'E','2020-07-11',  8);

SELECT r.Id, r.Property, r.ArrivalDate, r.rn,
  rebooking.RebookingId
, rebooking.Rebooking_ArrivalDate
, rebooking.Rebooking_RN
, CASE WHEN rebooking.RebookingId IS NOT NULL THEN 'Re-booked' ELSE 'cancelled' end as tag
FROM @ResaList as r
OUTER APPLY (SELECT rc.Id, rc.ArrivalDate, rc.RN
FROM @cancelled as c
INNER JOIN @ResaList AS rc
ON rc.Id = c.rebookingId
WHERE c.cancelledId = r.Id) as rebooking(RebookingId, Rebooking_ArrivalDate, Rebooking_RN)
```

```+-----+----------+-------------+----+-------------+-----------------------+--------------+-----------+
| Id  | Property | ArrivalDate | rn | RebookingId | Rebooking_ArrivalDate | Rebooking_RN |    tag    |
+-----+----------+-------------+----+-------------+-----------------------+--------------+-----------+
| 100 | X        | 2020-05-22  |  9 | NULL        | NULL                  | NULL         | cancelled |
| 102 | X        | 2020-03-05  |  7 | 541         | 2020-06-01            | 7            | Re-booked |
| 250 | D        | 2020-04-12  | 10 | 351         | 2020-09-23            | 5            | Re-booked |
| 129 | E        | 2020-03-15  |  8 | 800         | 2020-07-11            | 8            | Re-booked |
| 351 | D        | 2020-09-23  |  5 | NULL        | NULL                  | NULL         | cancelled |
| 541 | X        | 2020-06-01  |  7 | NULL        | NULL                  | NULL         | cancelled |
| 800 | E        | 2020-07-11  |  8 | NULL        | NULL                  | NULL         | cancelled |
+-----+----------+-------------+----+-------------+-----------------------+--------------+-----------+
```

Body:
I am using SQL Server 2014. I am working on a query where I want to extract information from 2 specific tables to create my final output.

An extract of the 2 tables (Rebookings and ResaList) are given below.

Rebookings Table (each CancelledID has its corresponding RebookingID):

CancelledID            RebookingID
  102                     541
  250                     351
  129                     800
  ...

ResaList Table:

ID      Property         ArrivalDate       RN
100       X              2020-05-22         9
102       X              2020-03-05         7
250       D              2020-04-12        10
129       E              2020-03-15         8
351       D              2020-09-23         5
541       X              2020-06-01         7
800       E              2020-07-11         8
...

Here is my desired output:

ID       Property        ArrivalDate         RN    RebookingID        Rebooking_ArrivalDate    Rebooking_RN     Tag
102         X            2020-03-05           7       541              2020-06-01                   7           Cancelled
250         D            2020-04-12          10       351              2020-09-23                   5           Re-booked
129         E            2020-03-15           8       800              2020-07-11                   8           Re-booked

This is what I have done so far:

USE [MyDatabase]

select
  a.[ID],
  a.[Property],
  a.[Arrival Date],
  a.[RN],
  b.[RebookingID],
  (CASE WHEN a.[ID] in (SELECT [CancelledID] FROM [Rebookings]) THEN 'Re-booked'
      ELSE 'Cancelled'
      END) as [Tag]
from [ResaList] a
LEFT JOIN [Rebookings] b on b.[CancelledID] = a.[ID]
where a.[ID] in (SELECT [CancelledID] FROM [Rebookings])
GROUP BY a.[ID], a.[Property], a.[ArrivalDate], b.[RebookingID]

I am stuck at how to bring Rebooking_ArrivalDate and Rebooking_RN into the above output. Any help would be appreciated.

Body:
I have tried this in SQL Server.

DECLARE @cancelled Table (cancelledId int, rebookingId int)

INSERT into @cancelled values
(102    , 541  ),
( 250   ,  351 ),
( 129   ,  800 );

DECLARE @ResaList TABLE(Id int, property CHAR(1), ArrivalDate date, RN int)

INSERT INTO @ResaList values
(100  ,'X','2020-05-22',  9),
(102  ,'X','2020-03-05',  7),
(250  ,'D','2020-04-12', 10),
(129  ,'E','2020-03-15',  8),
(351  ,'D','2020-09-23',  5),
(541  ,'X','2020-06-01',  7),
(800  ,'E','2020-07-11',  8);

SELECT r.Id, r.Property, r.ArrivalDate, r.rn,
  rebooking.RebookingId
, rebooking.Rebooking_ArrivalDate
, rebooking.Rebooking_RN
, CASE WHEN rebooking.RebookingId IS NOT NULL THEN 'Re-booked' ELSE 'cancelled' end as tag
FROM @ResaList as r
OUTER APPLY (SELECT rc.Id, rc.ArrivalDate, rc.RN
FROM @cancelled as c
INNER JOIN @ResaList AS rc
ON rc.Id = c.rebookingId
WHERE c.cancelledId = r.Id) as rebooking(RebookingId, Rebooking_ArrivalDate, Rebooking_RN)

+-----+----------+-------------+----+-------------+-----------------------+--------------+-----------+
| Id  | Property | ArrivalDate | rn | RebookingId | Rebooking_ArrivalDate | Rebooking_RN |    tag    |
+-----+----------+-------------+----+-------------+-----------------------+--------------+-----------+
| 100 | X        | 2020-05-22  |  9 | NULL        | NULL                  | NULL         | cancelled |
| 102 | X        | 2020-03-05  |  7 | 541         | 2020-06-01            | 7            | Re-booked |
| 250 | D        | 2020-04-12  | 10 | 351         | 2020-09-23            | 5            | Re-booked |
| 129 | E        | 2020-03-15  |  8 | 800         | 2020-07-11            | 8            | Re-booked |
| 351 | D        | 2020-09-23  |  5 | NULL        | NULL                  | NULL         | cancelled |
| 541 | X        | 2020-06-01  |  7 | NULL        | NULL                  | NULL         | cancelled |
| 800 | E        | 2020-07-11  |  8 | NULL        | NULL                  | NULL         | cancelled |
+-----+----------+-------------+----+-------------+-----------------------+--------------+-----------+


问:
Python, Opencv, Imutils: ValueError: too many values to unpack (expected 2)
I am trying to feed live video to the Tkinter window. I am using imutils.video for the Videostream. When I tried to run the code I am getting below-mentioned error.
runfile('C:/Users/Ravi/Face_Detector/opencv_tkinter.py', wdir='C:/Users/Ravi/Face_Detector')

```<code>Traceback (most recent call last):

  File "C:\Users\Ravi\opencv_tkinter.py", line 37, in <module>
show_frame() #Displayq

  File "C:\Users\Ravi\opencv_tkinter.py", line 23, in show_frame
_, frame = cap.read()

ValueError: too many values to unpack (expected 2)
</code>```

When I am using cap = cv2.VideoCapture(0), then everything works fine. What can be the difference between
cap = cv2.VideoCapture(0) and cap = VideoStream(src=0).start()? In my other applications I am using cap = VideoStream(src=0).start(), that is why I need to stick with this. Can not afford to use cv2.VideoCapture. Any help is appriciated!

code:

```<code>import numpy as np
import cv2
import tkinter as tk
from PIL import Image, ImageTk
from imutils.video import VideoStream
import time

#Set up GUI
window = tk.Tk()  #Makes main window
window.title("Test_1")
window.config(background="#FFFFFF")

#Graphics window
imageFrame = tk.Frame(window, width=600, height=600)
imageFrame.grid(row=2, column=0, padx=2, pady=2)

#Capture video frames

cap = VideoStream(src=0).start()
time.sleep(2.0)

def show_frame():
    _, frame = cap.read()
    frame = cv2.flip(frame, 1)
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
    frame = Image.fromarray(frame)
    frame = ImageTk.PhotoImage(image=frame)
    display.img = frame #Shows frame for display 1
    display.configure(image=frame)
    window.after(10, show_frame)

myLable1 = tk.Label(imageFrame, text = "Title_1", bg='blue', fg="white", font=("Helvetica", 16))
myLable1.grid(row= 1, column= 0)
display = tk.Label(imageFrame)
display.grid(row=2, column=0, padx=10, pady=2)  #Display 1

show_frame() #Displayq
window.mainloop()  #Starts GUI
</code>```

答: I have tried with frame = cap.read() and it worked</p>

Body:
I am trying to feed live video to the Tkinter window. I am using imutils.video for the Videostream. When I tried to run the code I am getting below-mentioned error.
runfile('C:/Users/Ravi/Face_Detector/opencv_tkinter.py', wdir='C:/Users/Ravi/Face_Detector')

Traceback (most recent call last):

  File "C:\Users\Ravi\opencv_tkinter.py", line 37, in <module>
show_frame() #Displayq

  File "C:\Users\Ravi\opencv_tkinter.py", line 23, in show_frame
_, frame = cap.read()

ValueError: too many values to unpack (expected 2)

When I am using cap = cv2.VideoCapture(0), then everything works fine. What can be the difference between
cap = cv2.VideoCapture(0) and cap = VideoStream(src=0).start()? In my other applications I am using cap = VideoStream(src=0).start(), that is why I need to stick with this. Can not afford to use cv2.VideoCapture. Any help is appriciated!

code:

import numpy as np
import cv2
import tkinter as tk
from PIL import Image, ImageTk
from imutils.video import VideoStream
import time

#Set up GUI
window = tk.Tk()  #Makes main window
window.title("Test_1")
window.config(background="#FFFFFF")

#Graphics window
imageFrame = tk.Frame(window, width=600, height=600)
imageFrame.grid(row=2, column=0, padx=2, pady=2)

#Capture video frames

cap = VideoStream(src=0).start()
time.sleep(2.0)

def show_frame():
    _, frame = cap.read()
    frame = cv2.flip(frame, 1)
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
    frame = Image.fromarray(frame)
    frame = ImageTk.PhotoImage(image=frame)
    display.img = frame #Shows frame for display 1
    display.configure(image=frame)
    window.after(10, show_frame)

myLable1 = tk.Label(imageFrame, text = "Title_1", bg='blue', fg="white", font=("Helvetica", 16))
myLable1.grid(row= 1, column= 0)
display = tk.Label(imageFrame)
display.grid(row=2, column=0, padx=10, pady=2)  #Display 1

show_frame() #Displayq
window.mainloop()  #Starts GUI


问:
Filtering an array of arrays JS
I'm trying to write a function, that accepts an array of arrays as argument and filtering this array under certain condition. I will explain this condition later.
For example I have such array:

```<code> const arr = [
  [1, 1, 20],
  [2, 1, 15],
  [3, 1.5, 15],
  [4, 1, 15],
  [5, 1, 20],
  [6, 1.5, 15],
  [7, 1, 25],
  [8, 1, 15],
  [9, 0, 15],
  [10, 0, 15],
  [11, 0, 15],
]
</code>```

and the condition. I want to filter it by the value of the third column, but only if it's at least three in a sequence. The function should accept two arguments (or more if needed): value and array
So for example

```<code> const filterByValue = (array, val) => { //definition
     return filtredArr
   }
</code>```

const newArr = filterByValue(array,15)
and now newArr should equal:

```<code> [
   [2, 1, 15],
   [3, 1.5, 15],
   [4, 1, 15],
   [8, 1, 15],
   [9, 0, 15],
   [10, 0, 15],
   [11, 0, 15],
 ]
</code>```

For now I only made:

```<code>const filterByValue = (arr, value) => {
      const newArr = arr.filter((elem, index) => elem[2] === value)
      return newArr
  }
</code>```

but this function returns

```<code>  [
     [2, 1, 15],
     [3, 1.5, 15],
     [4, 1, 15],
     [6, 1.5, 15],
     [8, 1, 15],
     [9, 0, 15],
     [10, 0, 15],
     [11, 0, 15],
  ]
</code>```

there shouldn't be [6,1.5,15]. I have no idea how it could be done to return only fragments of an array that contain at least three internal arrays in a row. Maybe any of you have any idea?

edit more explanation

This sequence means to me that I want only output which internal arrays that contain a set value in the third value (value argument in a function), but that they also have internal arrays that follow each other (at least three). Let's assume that the function accepts arr (first array in my post) and value = 15. The first internal array contains 20 as the third value, so it falls off. The second is okey, the third also and the fourth also - and should return in this situation 2,3,4 internal board (because they follow three in succession). Then the fifth value is 20, the sixth value is 15, but the next (seventh) value 25 again, so the function should not take into account the sixth table (because it is not followed by at least two tables that have the value 15). In the table 8,9,10,11 we have the value 15, and these are four tables (i.e. at least three). Therefore, the function should return an array containing the following tables 2,3,4 and 8,9,10,11. The sixth array contains the value 15, but not followed by two more that would have this value as well. The expected output is the second board in my post.

答:
```<code>const filterByValue = (arr,value) => {
    let newArray = [];
    let cache = [];
    arr.forEach(elem => {
        if (elem[2] === value) {
            cache.push(elem);
        } else {
            if (cache.length >= 3) {
                newArray = newArray.concat(cache);
            }
            cache = [];
        }
    });
    if (cache.length >= 3) {
        newArray = newArray.concat(cache);
    }
    return newArray;
}
</code>```

Title: Filtering an array of arrays JS

Body:
I'm trying to write a function, that accepts an array of arrays as argument and filtering this array under certain condition. I will explain this condition later.
For example I have such array:

 const arr = [
  [1, 1, 20],
  [2, 1, 15],
  [3, 1.5, 15],
  [4, 1, 15],
  [5, 1, 20],
  [6, 1.5, 15],
  [7, 1, 25],
  [8, 1, 15],
  [9, 0, 15],
  [10, 0, 15],
  [11, 0, 15],
]

and the condition. I want to filter it by the value of the third column, but only if it's at least three in a sequence. The function should accept two arguments (or more if needed): value and array
So for example

 const filterByValue = (array, val) => { //definition
     return filtredArr
   }

const newArr = filterByValue(array,15)
and now newArr should equal:

 [
   [2, 1, 15],
   [3, 1.5, 15],
   [4, 1, 15],
   [8, 1, 15],
   [9, 0, 15],
   [10, 0, 15],
   [11, 0, 15],
 ]

For now I only made:

const filterByValue = (arr, value) => {
      const newArr = arr.filter((elem, index) => elem[2] === value)
      return newArr
  }

but this function returns

  [
     [2, 1, 15],
     [3, 1.5, 15],
     [4, 1, 15],
     [6, 1.5, 15],
     [8, 1, 15],
     [9, 0, 15],
     [10, 0, 15],
     [11, 0, 15],
  ]

there shouldn't be [6,1.5,15]. I have no idea how it could be done to return only fragments of an array that contain at least three internal arrays in a row. Maybe any of you have any idea?

edit more explanation

This sequence means to me that I want only output which internal arrays that contain a set value in the third value (value argument in a function), but that they also have internal arrays that follow each other (at least three). Let's assume that the function accepts arr (first array in my post) and value = 15. The first internal array contains 20 as the third value, so it falls off. The second is okey, the third also and the fourth also - and should return in this situation 2,3,4 internal board (because they follow three in succession). Then the fifth value is 20, the sixth value is 15, but the next (seventh) value 25 again, so the function should not take into account the sixth table (because it is not followed by at least two tables that have the value 15). In the table 8,9,10,11 we have the value 15, and these are four tables (i.e. at least three). Therefore, the function should return an array containing the following tables 2,3,4 and 8,9,10,11. The sixth array contains the value 15, but not followed by two more that would have this value as well. The expected output is the second board in my post.


问:
how to make a suvat calculator calculate from missing values
I'm trying to code a suvat calculator to use a specific equation if certain values are missing but I keep getting errors with strings when I input nothing and errors like (TypeError: can't multiply sequence by non-int of type 'float') or (TypeError: 'str' object is not callable)
Here's the code</p>

```<code>s= input('Please enter the displacement: ')
u= input('Please enter the Inital velocity: ')
v= input('Please enter the Final Velocity: ')
a= input('Please enter the acceleration: ')
t= input('Please enter the time taken: ')

if s == "" and a == "":
    answer = float(0.5 * (u + v) * t)
    print("Your answer is", answer)

#### FIX THIS ^^^^^^ THE OTHER ONE TOO

if v == "":
    answer = u + a * t
    print("Your answer is", answer)
</code>```

答:
Please make sure your question shows your research effort. By default, the input value will be a string and you need to convert it into the float.</p>

```<code>s= input('Please enter the displacement: ')
u= input('Please enter the Inital velocity: ')
v= input('Please enter the Final Velocity: ')
a= input('Please enter the acceleration: ')
t= input('Please enter the time taken: ')

if s == "" and a == "":
    answer = float(0.5 * (float(u) + float(v)) * float(t))
    print("Your answer is", answer)

#### FIX THIS ^^^^^^ THE OTHER ONE TOO

if v == "":
    answer = float(u) + float(a) * float(t)
    print("Your answer is", answer)
</code>```

Body:
I'm trying to code a suvat calculator to use a specific equation if certain values are missing but I keep getting errors with strings when I input nothing and errors like (TypeError: can't multiply sequence by non-int of type 'float') or (TypeError: 'str' object is not callable)
Here's the code

s= input('Please enter the displacement: ')
u= input('Please enter the Inital velocity: ')
v= input('Please enter the Final Velocity: ')
a= input('Please enter the acceleration: ')
t= input('Please enter the time taken: ')

if s == "" and a == "":
    answer = float(0.5 * (u + v) * t)
    print("Your answer is", answer)

#### FIX THIS ^^^^^^ THE OTHER ONE TOO

if v == "":
    answer = u + a * t
    print("Your answer is", answer)

Body:
Please make sure your question shows your research effort. By default, the input value will be a string and you need to convert it into the float.

s= input('Please enter the displacement: ')
u= input('Please enter the Inital velocity: ')
v= input('Please enter the Final Velocity: ')
a= input('Please enter the acceleration: ')
t= input('Please enter the time taken: ')

if s == "" and a == "":
    answer = float(0.5 * (float(u) + float(v)) * float(t))
    print("Your answer is", answer)

#### FIX THIS ^^^^^^ THE OTHER ONE TOO

if v == "":
    answer = float(u) + float(a) * float(t)
    print("Your answer is", answer)


问:
ASP.NET MVC Razor Concatenation
I'm trying the render an HTML list that looks like the following, using the Razor view engine:

```<code><ul>
  <li id="item_1">Item 1</li>
  <li id="item_2">Item 2</li>
</ul>
</code>```

The code that I am attempting to use to render this list is:

```<code><ul>
@foreach (var item in Model.TheItems)
{
  <li id="item_@item.TheItemId">Item @item.TheItemId</li>
}
</ul>
</code>```

The parser is choking, because it thinks that that everything to the right of the underscore in the id attribute is plain text and should not be parsed.  I'm uncertain of how to instruct the parser to render TheItemId.

I don't want to but a property on the model object that includes the item_ prefix.

I also have to keep this syntax as I am using the list with JQuery Sortable and with the serialize function that requires the id attribute to be formatted in this syntax.

答:
You can so this in a simpler way:</p>

```<code>id="item_@item.TheItemId"
</code>```

Title: ASP.NET MVC Razor Concatenation

Body:
I'm trying the render an HTML list that looks like the following, using the Razor view engine:

Item 1

Item 2

The code that I am attempting to use to render this list is:

@foreach (var item in Model.TheItems)
{

Item @item.TheItemId

}

The parser is choking, because it thinks that that everything to the right of the underscore in the id attribute is plain text and should not be parsed.  I'm uncertain of how to instruct the parser to render TheItemId.

I don't want to but a property on the model object that includes the item_ prefix.

I also have to keep this syntax as I am using the list with JQuery Sortable and with the serialize function that requires the id attribute to be formatted in this syntax.

Body:
You can so this in a simpler way:

id="item_@item.TheItemId"


Title: Filtering an array of arrays JS

Body:
You could take a closure over an index and check if the values are in a sequence of three.

const
    array = [[1, 1, 20], [2, 1, 15], [3, 1.5, 15], [4, 1, 15], [5, 1, 20], [6, 1.5, 15], [7, 1, 25], [8, 1, 15], [9, 0, 15], [10, 0, 15], [11, 0, 15]],
    value = 15,
    result = array.filter(
        (index => ({ 2: v }, i, a) => {
            if (v !== value) return false;
            if (index === i || a[i + 1][2] === value && a[i + 2][2] === value) {
                index = i + 1;
                return true;
            }
        })
        (-1)
    );

console.log(result);


问:
Python - TensorFlow and Keras
I've been searching all about What is Tensorflow and Keras. They say that Tensorflow runs on top of Keras which means that Tensorflow is the "BACKEND" of KERAS.  (Although you can use others like Theano and CNTK)

Does the "BACKEND" term here mean it does the whole mathematical process thing behind a deep learning model ? What I mean is like Tensorflow is the one who does the complicated stuffs like processing the matrices (tensor) , doing all the math stuff?

On the other hand KERAS is the guy that is needed ONLY for us to create a MODEL, right?
and ONCE the model is created, its "BACKEND" is Tensorflow, right? cause for the MODEL TO WORK AS IT SHOULD BE (like process matrices and do all the math stuffs) it needs a "BACKEND" which is Tensorflow.

That is what I understand based on some open forums and the Keras documentation:

Keras is a model-level library, providing high-level building blocks for developing deep learning models. It does not handle itself low-level operations such as tensor products, convolutions and so on. Instead, it relies on a specialized, well-optimized tensor manipulation library to do so, serving as the “backend engine” of Keras.

Is my understanding correct? Please enlighten me if you have other answers.

答:
When we say that Tensorflow is the backend of Keras, we mean that Keras do not do calculations by itself. Keras just provide easy to use functions that use more complex Tensorflow code. It is then a little less powerful but it is sufficient in most cases. And when it is not, you can add Tensorflow code in your Keras Code as they both use The same Tensorflow objects in background.

Keras is now the official Tensorflow High level API, it is then a part of Tensorflow.

Title: Python - TensorFlow and Keras


问:
When to use composite key instead of auto increment
I am creating a database and I am not sure about one of my tables. This table stores the users that are in each game, so one entry per user per game. The user is identified by their user_id which is a 36 character UUID4, and the game is identified by a session_id which is an 8 character alphanumeric string such as "ABK2RXN4". Currently, I have created an additional field just called id which is an integer that auto increments, and I have set that to be the primary key. These are the only 3 fields.

Since the combination of the session_id and the user_id will always result in a unique outcome, should I instead use those two as the composite private key and remove the id field?

Thanks.

EDIT:

Do things change if we have a more complicated table that will require more fields? Take this table for example.

```<code>| id  | voter    | voting_for | round    | category_id | acceptable |
|-----|----------|------------|----------|-------------|------------|
| int | char(36) | char(36)   | smallint | int         | boolean    |
</code>```

This is to do with votes within a game. Essentially after each round, the users in the game will vote on the answers of the other users within the game. So each entry has the user_id of the voter, the user_id of the person they are voting_for, the current round, the category_id of the category within the game and whether or not they agreed with the answer, acceptable. So, you could make a composite primary key using voter, voting_for, round and category_id. Is this any worse just because there are more fields, or should I still use the composite key instead of the existing auto increment id?

答:
Your bridge table is based on two columns. Both are not nullable and you want a unique constraint on them, so as to have no duplicates.

This makes the columns already a key for the table. "Primary key" is just a name for one such key. You can just leave this as is (i.e. declare the columns NOT NULL and have a unique constraint on them). You can also declare this the "primary key". This would not change anything actually.

You can also decide to add a technical single-column key (an integer ID as you suggest). Then your table would have two unique keys. The latter can be used to reference a row easier from another table, if such exist. Some people working with databases based on technical IDs prefer each table to have such ID, but it's not necessary as long as you don't need the reference. Which key (the ID or the composite key) and if any at all you call "primary" again has no real effect. Typically you would call the ID the primary key.

Body:
I am creating a database and I am not sure about one of my tables. This table stores the users that are in each game, so one entry per user per game. The user is identified by their user_id which is a 36 character UUID4, and the game is identified by a session_id which is an 8 character alphanumeric string such as "ABK2RXN4". Currently, I have created an additional field just called id which is an integer that auto increments, and I have set that to be the primary key. These are the only 3 fields.

Since the combination of the session_id and the user_id will always result in a unique outcome, should I instead use those two as the composite private key and remove the id field?

Thanks.

EDIT:

Do things change if we have a more complicated table that will require more fields? Take this table for example.

| id  | voter    | voting_for | round    | category_id | acceptable |
|-----|----------|------------|----------|-------------|------------|
| int | char(36) | char(36)   | smallint | int         | boolean    |

This is to do with votes within a game. Essentially after each round, the users in the game will vote on the answers of the other users within the game. So each entry has the user_id of the voter, the user_id of the person they are voting_for, the current round, the category_id of the category within the game and whether or not they agreed with the answer, acceptable. So, you could make a composite primary key using voter, voting_for, round and category_id. Is this any worse just because there are more fields, or should I still use the composite key instead of the existing auto increment id?


问:
What is the maximum size limit of varchar data type in sqlite?
I'm new to sqlite. I want to know the maximum size limit of varchar data type in sqlite?

can anybody suggest me some information related to this? I searched on sqlite.org site and they give the answer as:

Q. What is the maximum size of a VARCHAR in SQLite?

A. SQLite does not enforce the length of a VARCHAR. You can declare a VARCHAR(10) and SQLite will be happy to let you put 500
characters in it. And it will keep all   500 characters intact - it
never truncates.

but I want to know the exact max size limit of varchar datatype in sqlite.

答:
from http://www.sqlite.org/limits.html

Maximum length of a string or BLOB

The maximum number of bytes in a
  string or BLOB in SQLite is defined by
  the preprocessor macro
  SQLITE_MAX_LENGTH. The default value of this macro is 1 billion (1 thousand
  million or 1,000,000,000). You can
  raise or lower this value at
  compile-time using a command-line
  option like this:

-DSQLITE_MAX_LENGTH=123456789 The current implementation will only
  support a string or BLOB length up to
  231-1 or 2147483647. And some built-in
  functions such as hex() might fail
  well before that point. In
  security-sensitive applications it is
  best not to try to increase the
  maximum string and blob length. In
  fact, you might do well to lower the
  maximum string and blob length to
  something more in the range of a few
  million if that is possible.

During part of SQLite's INSERT and
  SELECT processing, the complete
  content of each row in the database is
  encoded as a single BLOB. So the
  SQLITE_MAX_LENGTH parameter also
  determines the maximum number of bytes
  in a row.


问:
Movlet Failing if double quotes exists in string
I have a string with double quotes for example:

```<code>"Diagnosed with "Covid19 -Ve"
</code>```

while rendering in MEL variable it's failing.

My string may contains multiple double quotes in future.

How to escape if string contains all the double quotes in entire string value at the end in MEL

答:
you can escape the double quotes character using a backslash and then the double quotes. Just like this:</p>

```<code>myVariable = "Diagnosed with \"Covid19 -Ve" ;
</code>```

Body:
I have a string with double quotes for example:

"Diagnosed with "Covid19 -Ve"

while rendering in MEL variable it's failing.

My string may contains multiple double quotes in future.

How to escape if string contains all the double quotes in entire string value at the end in MEL

Body:
you can escape the double quotes character using a backslash and then the double quotes. Just like this:

myVariable = "Diagnosed with \"Covid19 -Ve" ;


问:
Laravel set DB field into an empty array
I have a field in my DB table where i set it as an array using json_encode. The field is called categories, where i input one or more category for a book. As follows:

```<code>$book->categories = json_encode($request->input('categories'));
</code>```

Now my question is, when i try to update the categories with an empty array, i get an error. I tried to set the default value to null and then just pass null in my request

```<code>$book->categories = null;
</code>```

But that didn't change anything in the DB. How can i update this field with an empty array??

答:
please try:</p>

```<code>if($request->input('categories')==null)
$book->categories=[];
else
book->categories = json_encode($request->input('categories'));
</code>```

Body:
I have a field in my DB table where i set it as an array using json_encode. The field is called categories, where i input one or more category for a book. As follows:

$book->categories = json_encode($request->input('categories'));

Now my question is, when i try to update the categories with an empty array, i get an error. I tried to set the default value to null and then just pass null in my request

$book->categories = null;

But that didn't change anything in the DB. How can i update this field with an empty array??

Body:
please try:

if($request->input('categories')==null)
$book->categories=[];
else
book->categories = json_encode($request->input('categories'));


问:
google Apps script using mailApp to send htmlbody (content being modified)
I was trying to send an approval letter with google apps script (mailApp).
And hide some data in the hidden input.
However, the id of the input was changed by google.

The script in google apps script:

```<code>MailApp.sendEmail({
    to: email,
    subject: "Classroom register Approval",
    body: "",
    htmlBody:
      "<form action = 'google apps script website' method = 'POST'>" +
      "<input id='approverow' type='hidden' value="+ e.range.getRowIndex() +">" +
      "<button type = \"submit\">Approve</button>"
  })
</code>```

real HTML in email

```<code><form action="google apps script website" method="POST" target="_blank">
<input id="m_8985313804230818410approverow" type="hidden" value="22">
<button type="submit">Approve</button></form>
</code>```

Why Google change the element id and how can I stop it?

答:
Issue:

I think the id is only getting modified when being displayed in the corresponding INBOX, but it's not modified in the message itself.

Explanation:

As you probably know, the id of an element must be unique in the whole document. So I think this is a way to ensure that the id is unique in the page in which it is being displayed (e.g. INBOX). Think, for example, what would happen if the id you specified matched the one in Gmail sidebar?

More importantly, you can notice that if you retrieve the message body once it has been sent (via GmailApp.search, or what have you) the id of the message is the one you specified, no modification.

Also, this is not particular to Google: you can check that the id gets modified in different ways depending on where the email is being displayed. While messages displayed in Gmail INBOX get appended something like m{many numbers}, messages displayed in Outlook get appended x_. And a similar behaviour seems to occur for the class attribute: in Outlook, class attributes from the email body also get x_ appended, while in Gmail, class is not even present.

Body:
I was trying to send an approval letter with google apps script (mailApp).
And hide some data in the hidden input.
However, the id of the input was changed by google.

The script in google apps script:

MailApp.sendEmail({
    to: email,
    subject: "Classroom register Approval",
    body: "",
    htmlBody:
      "<form action = 'google apps script website' method = 'POST'>" +
      "<input id='approverow' type='hidden' value="+ e.range.getRowIndex() +">" +
      "<button type = \"submit\">Approve</button>"
  })

real HTML in email

<form action="google apps script website" method="POST" target="_blank">
<input id="m_8985313804230818410approverow" type="hidden" value="22">
<button type="submit">Approve</button></form>

Why Google change the element id and how can I stop it?


问:
Automatic ScrollViewer scrolling to bottom and top on set time interval
I am displaying an ObservableCollection inside a Scrollviewer which contains about 50 rows. If I display them all at once, the text is too small. To make them big enough to see clearly, some of the entries will be out of view and I will need to scroll.

What I would like to do is display the top 35 in the main view (scrolled to top), then every 20 seconds automatically scroll to bottom which will show the bottom 15 rows (including some at top that it has space for obviously), wait 10 secs and then scroll back to top. Repeat over and over indefinitely.

It doesn't have to use a scrollviewer if there is a better way.

How can I achieve this?

答:
Place them in an ItemsControl and re-template it with a ScrollViewer:

```<code><ItemsControl x:Name="theItemsControl" ItemsSource="{Binding Items}">
    <ItemsControl.Template>
        <ControlTemplate TargetType="ItemsControl">
            <ScrollViewer x:Name="theScrollViewer">
                <ItemsPresenter />
            </ScrollViewer>
        </ControlTemplate>
    </ItemsControl.Template>
</ItemsControl>
</code>```

Then create an animation task back in your main window:

```<code>    public MainWindow()
    {
        InitializeComponent();
        theItemsControl.Loaded += (s, e) => Task.Run(Animate);
    }

    private async Task Animate()
    {
        var theScrollViewer = theItemsControl.Template.FindName("theScrollViewer", theItemsControl) as ScrollViewer;
        while (true)
        {
            this.Dispatcher.Invoke(() => theScrollViewer.ScrollToTop());
            await Task.Delay(TimeSpan.FromSeconds(10));
            this.Dispatcher.Invoke(() => theScrollViewer.ScrollToBottom());
            await Task.Delay(TimeSpan.FromSeconds(10));
        }
    }
</code>```

If you want smooth scrolling then it's a little bit more complicated, you'll need to create animations for the scroll offset, set their positions to the virtual height of your ScrollViewer and trigger them in your animation task.

Body:
Place them in an ItemsControl and re-template it with a ScrollViewer:

<ItemsControl x:Name="theItemsControl" ItemsSource="{Binding Items}">
    <ItemsControl.Template>
        <ControlTemplate TargetType="ItemsControl">
            <ScrollViewer x:Name="theScrollViewer">
                <ItemsPresenter />
            </ScrollViewer>
        </ControlTemplate>
    </ItemsControl.Template>
</ItemsControl>

Then create an animation task back in your main window:

    public MainWindow()
    {
        InitializeComponent();
        theItemsControl.Loaded += (s, e) => Task.Run(Animate);
    }

    private async Task Animate()
    {
        var theScrollViewer = theItemsControl.Template.FindName("theScrollViewer", theItemsControl) as ScrollViewer;
        while (true)
        {
            this.Dispatcher.Invoke(() => theScrollViewer.ScrollToTop());
            await Task.Delay(TimeSpan.FromSeconds(10));
            this.Dispatcher.Invoke(() => theScrollViewer.ScrollToBottom());
            await Task.Delay(TimeSpan.FromSeconds(10));
        }
    }

If you want smooth scrolling then it's a little bit more complicated, you'll need to create animations for the scroll offset, set their positions to the virtual height of your ScrollViewer and trigger them in your animation task.


问:
Regex capture all matches in word
For example, I have this string:

```<code>222
</code>```

What pattern I should use to get a count of "22" matches exactly 2 times?

```<code>222 -> (22)2 and 2(22)
</code>```

So, for 2222 I would have 3 matches:

```<code>2222 -> (22)22 and 2(22)2 and 22(22)
</code>```

答: Try 2{2}. The number inside the braces is the number of repetitions of the token prior to the opening brace.

Title: Regex capture all matches in word

Body:
For example, I have this string:

222

What pattern I should use to get a count of "22" matches exactly 2 times?

222 -> (22)2 and 2(22)

So, for 2222 I would have 3 matches:

2222 -> (22)22 and 2(22)2 and 22(22)


问:
Not redirecting to desired page
How can I get the loginState in Navigation, so after successful login system should redirect to Profile screen. Now after successful login, it is not Redirecting to profile screen.
I have read few tutorials but all with complex details, I would like to have some simple way of implementing this, as I have only 4 screens.

I have added a demo below:

https://codesandbox.io/s/amazing-ellis-2h3pd?file=/src/components/Home.js

答:
On successful sign in, store flag in local storage

localStorage.setItem('userLoggedIn', true);

App.js : Allow user to access signing in related pages without restriction

const App = () => {
  return (

        <Switch>
          <Route exact path="/signIn" component={SignIn} />
          <Route exact path="/signUp" component={SignUp} />
          <Route exact path="/forgotPassword" component={ForgotPassword} />

          <PrivateRoute path="/" component={Dashboard} />
        </Switch>

  );
}```
</div>
</div>
</p>

<ol start="3">
<li>PrivateRoute.js : if user is not logged in always get redirected to sign in</li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
        localStorage.getItem('userLoggedIn')
            ? <Component {...props}></Component>
            : <Redirect to={{ pathname: '/signIn', state: { from: props.location } }} />
    )} />
);</code>```

Dashboard.js : After sign in user can access Dashboard

class Dashboard extends Component {
    render() {
        return (

                <Switch>
                  <Route exact path="/" component={MY_PROFILE} />
                  <Route exact path="/myProfile" component={MyProfile} />
                </Switch>

        );
    }
}```

Title: Not redirecting to desired page

Body:
On successful sign in, store flag in local storage

localStorage.setItem('userLoggedIn', true);

App.js : Allow user to access signing in related pages without restriction

const App = () => {
  return (
    <div className="App">
        <Switch>
          <Route exact path="/signIn" component={SignIn} />
          <Route exact path="/signUp" component={SignUp} />
          <Route exact path="/forgotPassword" component={ForgotPassword} />

          <PrivateRoute path="/" component={Dashboard} />
        </Switch>
    </div>
  );
}

PrivateRoute.js : if user is not logged in always get redirected to sign in

const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
        localStorage.getItem('userLoggedIn')
            ? <Component {...props}></Component>
            : <Redirect to={{ pathname: '/signIn', state: { from: props.location } }} />
    )} />
);

Dashboard.js : After sign in user can access Dashboard

class Dashboard extends Component {
    render() {
        return (
            <div>
              <Header />
              <div>
                <Switch>
                  <Route exact path="/" component={MY_PROFILE} />
                  <Route exact path="/myProfile" component={MyProfile} />
                </Switch>
              </div>
            </div>
        );
    }
}