问:
Socket read timeout only using JDBC
I'm getting an exception on an Oracle WITH/SELECT construct, that if I pasted into SQL Developer, works fine and comes back in 9.655s.

```<code>[DEBUG] 2020-05-30 23:17:29.848 [http-nio-8090-exec-6] JdbcTransaction - [] Opening JDBC Connection
[DEBUG] 2020-05-30 23:17:30.336 [http-nio-8090-exec-6] JdbcTransaction - [] Setting autocommit to false on JDBC Connection [oracle.jdbc.driver.T4CConnection@c1d7134]
[DEBUG] 2020-05-30 23:17:30.336 [http-nio-8090-exec-6] getTotalUniqueUsersDetailsByKeyByTime - [] ==>  Preparing: with main_data as ( select /*+ parallel(SCHUC) parallel(SCHU) parallel(SCHUT) parallel(SCHCM) parallel(SCHET) parallel(SCHES) */ distinct schutm.user_type_meta_name as KEY ,schuc.time_unit as TIME_UNIT ,schuc.user_key as VALUE from ( /* BP1 */ /* BP4 */ select /*+ parallel(SCHUCD) parallel(SCHFQL) */ YEAR_MONTH as TIME_UNIT ,schucd.TRACE_ID_KEY ,schucd.platform_id ,schucd.user_key ,schucd.event_type_id ,schucd.event_source_id ,REFERRER_ID ,PARENT_ID ,sum(USAGE_COUNT) as usage_count from sc_report_new.sc_hub_usage_counts_day schucd WHERE FISCAL_QUARTER_ID IN ( ? ) group by YEAR_MONTH ,schucd.TRACE_ID_KEY ,schucd.platform_id ,schucd.user_key ,schucd.event_type_id ,schucd.event_source_id ,REFERRER_ID ,PARENT_ID ) schuc inner join sc_hub_users schu on schuc.user_key=schu.user_key inner join sc_hub_user_types schut on schut.user_type_id=schu.user_type_id inner join sc_hub_user_types_meta_map schutmm on schutmm.user_type_id=schut.user_type_id inner join sc_hub_user_types_meta schutm ON schutm.user_type_meta_id = schutmm.user_type_meta_id inner join sc_hub_content_master schcm on schcm.trace_id_key=schuc.trace_id_key inner join sc_hub_event_types schet on schet.event_type_id = schuc.event_type_id inner join sc_hub_event_sources sches on sches.event_source_id = schuc.event_source_id WHERE ( (schcm.PAGETYPE='Page' AND sches.event_source_name='wem' AND schet.event_code='V') OR (schcm.PAGETYPE='Page' AND sches.event_source_name='purchaseshubs' AND schet.event_code='S') OR (schcm.PAGETYPE='Hub' AND sches.event_source_name='saleshubs' AND schet.event_code='S') ) ) select /*+parallel(AUTO) */ KEY,time_unit,count(VALUE) as VALUE from main_data group by KEY,TIME_UNIT order by case when KEY = 'Other' then 1 else 0 end, KEY, TIME_UNIT
[DEBUG] 2020-05-30 23:17:30.336 [http-nio-8090-exec-6] getTotalUniqueUsersDetailsByKeyByTime - [] ==> Parameters: 2020Q4(String)
org.apache.ibatis.exceptions.PersistenceException:
### Error querying database.  Cause: java.sql.SQLRecoverableException: IO Error: Socket read timed out
### The error may exist in com/mycompany/myapp/screport/mapper/hubportfolio/TotalUniqueUsers.xml
### The error may involve com.mycompany.myapp.screport.mapper.hubportfolio.TotalUniqueUsers.getTotalUniqueUsersDetailsByKeyByTime-Inline
### The error occurred while setting parameters
### SQL: with main_data as (                       select /*+ parallel(SCHUC)  parallel(SCHU)  parallel(SCHUT)  parallel(SCHCM) parallel(SCHET) parallel(SCHES) */              distinct                                           schutm.user_type_meta_name as KEY                                      ,schuc.time_unit as TIME_UNIT                ,schuc.user_key as VALUE         from                     (                                   /* BP1 */                                                          /* BP4 */                                       select /*+ parallel(SCHUCD) parallel(SCHFQL) */                             YEAR_MONTH as TIME_UNIT                            ,schucd.TRACE_ID_KEY                            ,schucd.platform_id                            ,schucd.user_key                            ,schucd.event_type_id                            ,schucd.event_source_id                            ,REFERRER_ID                            ,PARENT_ID                            ,sum(USAGE_COUNT)  as usage_count                                   from sc_report_new.sc_hub_usage_counts_day schucd                      WHERE  FISCAL_QUARTER_ID IN                                           (                                  ?                             )                      group by YEAR_MONTH                        ,schucd.TRACE_ID_KEY                        ,schucd.platform_id                        ,schucd.user_key                        ,schucd.event_type_id                        ,schucd.event_source_id                        ,REFERRER_ID                        ,PARENT_ID                                                                                ) schuc               inner join sc_hub_users schu         on schuc.user_key=schu.user_key                           inner join sc_hub_user_types schut                 on schut.user_type_id=schu.user_type_id                                       inner join sc_hub_user_types_meta_map schutmm                     on schutmm.user_type_id=schut.user_type_id                     inner join sc_hub_user_types_meta schutm                     ON schutm.user_type_meta_id = schutmm.user_type_meta_id                                         inner join sc_hub_content_master schcm         on schcm.trace_id_key=schuc.trace_id_key                   inner join sc_hub_event_types schet         on schet.event_type_id = schuc.event_type_id         inner join sc_hub_event_sources sches         on sches.event_source_id = schuc.event_source_id                                                                                WHERE  (             (schcm.PAGETYPE='Page' AND sches.event_source_name='wem' AND schet.event_code='V')              OR              (schcm.PAGETYPE='Page' AND sches.event_source_name='purchaseshubs' AND schet.event_code='S')              OR              (schcm.PAGETYPE='Hub' AND sches.event_source_name='saleshubs' AND schet.event_code='S')         )                )          select /*+parallel(AUTO) */              KEY,time_unit,count(VALUE) as VALUE from main_data         group by KEY,TIME_UNIT         order by case when KEY = 'Other' then 1 else 0 end, KEY, TIME_UNIT
### Cause: java.sql.SQLRecoverableException: IO Error: Socket read timed out
    at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:149)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:140)
    at com.mycompany.myapp.screport.dao.SCHubPortfolioServiceHandler.getTotalUniqueUserDetailsByTime(SCHubPortfolioServiceHandler.java:296)
    at com.mycompany.myapp.screport.services.SCHubPortfolioService.getTotalUniqueUserDetailsByTime(SCHubPortfolioService.java:269)
    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:498)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
    at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
    at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.thetransactioncompany.cors.CORSFilter.doFilter(CORSFilter.java:174)
    at com.thetransactioncompany.cors.CORSFilter.doFilter(CORSFilter.java:237)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.sql.SQLRecoverableException: IO Error: Socket read timed out
    at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:897)

</code>```

I'm using Tomcat 9 on a Java 1.8 JRE, MyBatis and Oracle 11g(I think).  The Oracle database is not hosted by my machine, but is in the same timezone and latency is not an issue.  If I take the query above, substitute the ? for '2020Q4' I can get an answer back in less than 10s according to SQL Developer.

Some key Maven dependencies include:

```<code>        <dependency>
            <groupId>com.cisco.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.3</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

</code>```

When I get the DataSource to build the connection, I do it this way:

```<code>        OracleDataSource result = new OracleDataSource();
        Class.forName("oracle.jdbc.driver.OracleDriver");
        String connectionString = lCiscoLifeJdbcUrl;
        String username = lCiscoLifeJdbcUserName;
        String password = lCiscoLifeJdbcPassword;
        OracleDataSource oracleDataSource = (OracleDataSource)result;
        oracleDataSource.setURL(connectionString);
        oracleDataSource.setPassword(password);
        oracleDataSource.setUser(username);
        String timeoutKey = "oracle.jdbc.ReadTimeout";
        Properties connectionProperties;
        try {
            connectionProperties = oracleDataSource.getConnectionProperties();
            if(connectionProperties==null) {
                connectionProperties = new Properties();
            }
            connectionProperties.put(timeoutKey, 60 /* minutes */ * 60 /* seconds per minutes */ * 1000 /* ms per seconds */);
        } catch (SQLException e) {
            e.printStackTrace();
        }
</code>```

From previous debugging, the connectionProperties defaulted to null, but I wanted to allow for those to be set by smarter people than myself.

Also, please note that this error occurs in about 8 out of 64 tests, so not every select triggers this issue.  I do no database updates or DML type statements.  Everything is assumed to be fully committed at this point.

I'm using MyBatis XML mapper files, but this is NOT a Spring driven project.  I manually build the DataSource, Configuration, Environment via Java objects.

What am I missing?

答: Can you set the connection properties as shown in DataSourceSample Also, check out OracleConnection for the list of properties. </p>

Title: Socket read timeout only using JDBC

Body:
I'm getting an exception on an Oracle WITH/SELECT construct, that if I pasted into SQL Developer, works fine and comes back in 9.655s.

[DEBUG] 2020-05-30 23:17:29.848 [http-nio-8090-exec-6] JdbcTransaction - [] Opening JDBC Connection
[DEBUG] 2020-05-30 23:17:30.336 [http-nio-8090-exec-6] JdbcTransaction - [] Setting autocommit to false on JDBC Connection [oracle.jdbc.driver.T4CConnection@c1d7134]
[DEBUG] 2020-05-30 23:17:30.336 [http-nio-8090-exec-6] getTotalUniqueUsersDetailsByKeyByTime - [] ==>  Preparing: with main_data as ( select /*+ parallel(SCHUC) parallel(SCHU) parallel(SCHUT) parallel(SCHCM) parallel(SCHET) parallel(SCHES) */ distinct schutm.user_type_meta_name as KEY ,schuc.time_unit as TIME_UNIT ,schuc.user_key as VALUE from ( /* BP1 */ /* BP4 */ select /*+ parallel(SCHUCD) parallel(SCHFQL) */ YEAR_MONTH as TIME_UNIT ,schucd.TRACE_ID_KEY ,schucd.platform_id ,schucd.user_key ,schucd.event_type_id ,schucd.event_source_id ,REFERRER_ID ,PARENT_ID ,sum(USAGE_COUNT) as usage_count from sc_report_new.sc_hub_usage_counts_day schucd WHERE FISCAL_QUARTER_ID IN ( ? ) group by YEAR_MONTH ,schucd.TRACE_ID_KEY ,schucd.platform_id ,schucd.user_key ,schucd.event_type_id ,schucd.event_source_id ,REFERRER_ID ,PARENT_ID ) schuc inner join sc_hub_users schu on schuc.user_key=schu.user_key inner join sc_hub_user_types schut on schut.user_type_id=schu.user_type_id inner join sc_hub_user_types_meta_map schutmm on schutmm.user_type_id=schut.user_type_id inner join sc_hub_user_types_meta schutm ON schutm.user_type_meta_id = schutmm.user_type_meta_id inner join sc_hub_content_master schcm on schcm.trace_id_key=schuc.trace_id_key inner join sc_hub_event_types schet on schet.event_type_id = schuc.event_type_id inner join sc_hub_event_sources sches on sches.event_source_id = schuc.event_source_id WHERE ( (schcm.PAGETYPE='Page' AND sches.event_source_name='wem' AND schet.event_code='V') OR (schcm.PAGETYPE='Page' AND sches.event_source_name='purchaseshubs' AND schet.event_code='S') OR (schcm.PAGETYPE='Hub' AND sches.event_source_name='saleshubs' AND schet.event_code='S') ) ) select /*+parallel(AUTO) */ KEY,time_unit,count(VALUE) as VALUE from main_data group by KEY,TIME_UNIT order by case when KEY = 'Other' then 1 else 0 end, KEY, TIME_UNIT
[DEBUG] 2020-05-30 23:17:30.336 [http-nio-8090-exec-6] getTotalUniqueUsersDetailsByKeyByTime - [] ==> Parameters: 2020Q4(String)
org.apache.ibatis.exceptions.PersistenceException:
### Error querying database.  Cause: java.sql.SQLRecoverableException: IO Error: Socket read timed out
### The error may exist in com/mycompany/myapp/screport/mapper/hubportfolio/TotalUniqueUsers.xml
### The error may involve com.mycompany.myapp.screport.mapper.hubportfolio.TotalUniqueUsers.getTotalUniqueUsersDetailsByKeyByTime-Inline
### The error occurred while setting parameters
### SQL: with main_data as (                       select /*+ parallel(SCHUC)  parallel(SCHU)  parallel(SCHUT)  parallel(SCHCM) parallel(SCHET) parallel(SCHES) */              distinct                                           schutm.user_type_meta_name as KEY                                      ,schuc.time_unit as TIME_UNIT                ,schuc.user_key as VALUE         from                     (                                   /* BP1 */                                                          /* BP4 */                                       select /*+ parallel(SCHUCD) parallel(SCHFQL) */                             YEAR_MONTH as TIME_UNIT                            ,schucd.TRACE_ID_KEY                            ,schucd.platform_id                            ,schucd.user_key                            ,schucd.event_type_id                            ,schucd.event_source_id                            ,REFERRER_ID                            ,PARENT_ID                            ,sum(USAGE_COUNT)  as usage_count                                   from sc_report_new.sc_hub_usage_counts_day schucd                      WHERE  FISCAL_QUARTER_ID IN                                           (                                  ?                             )                      group by YEAR_MONTH                        ,schucd.TRACE_ID_KEY                        ,schucd.platform_id                        ,schucd.user_key                        ,schucd.event_type_id                        ,schucd.event_source_id                        ,REFERRER_ID                        ,PARENT_ID                                                                                ) schuc               inner join sc_hub_users schu         on schuc.user_key=schu.user_key                           inner join sc_hub_user_types schut                 on schut.user_type_id=schu.user_type_id                                       inner join sc_hub_user_types_meta_map schutmm                     on schutmm.user_type_id=schut.user_type_id                     inner join sc_hub_user_types_meta schutm                     ON schutm.user_type_meta_id = schutmm.user_type_meta_id                                         inner join sc_hub_content_master schcm         on schcm.trace_id_key=schuc.trace_id_key                   inner join sc_hub_event_types schet         on schet.event_type_id = schuc.event_type_id         inner join sc_hub_event_sources sches         on sches.event_source_id = schuc.event_source_id                                                                                WHERE  (             (schcm.PAGETYPE='Page' AND sches.event_source_name='wem' AND schet.event_code='V')              OR              (schcm.PAGETYPE='Page' AND sches.event_source_name='purchaseshubs' AND schet.event_code='S')              OR              (schcm.PAGETYPE='Hub' AND sches.event_source_name='saleshubs' AND schet.event_code='S')         )                )          select /*+parallel(AUTO) */              KEY,time_unit,count(VALUE) as VALUE from main_data         group by KEY,TIME_UNIT         order by case when KEY = 'Other' then 1 else 0 end, KEY, TIME_UNIT
### Cause: java.sql.SQLRecoverableException: IO Error: Socket read timed out
    at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:149)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:140)
    at com.mycompany.myapp.screport.dao.SCHubPortfolioServiceHandler.getTotalUniqueUserDetailsByTime(SCHubPortfolioServiceHandler.java:296)
    at com.mycompany.myapp.screport.services.SCHubPortfolioService.getTotalUniqueUserDetailsByTime(SCHubPortfolioService.java:269)
    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:498)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
    at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
    at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.thetransactioncompany.cors.CORSFilter.doFilter(CORSFilter.java:174)
    at com.thetransactioncompany.cors.CORSFilter.doFilter(CORSFilter.java:237)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.sql.SQLRecoverableException: IO Error: Socket read timed out
    at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:897)

I'm using Tomcat 9 on a Java 1.8 JRE, MyBatis and Oracle 11g(I think).  The Oracle database is not hosted by my machine, but is in the same timezone and latency is not an issue.  If I take the query above, substitute the ? for '2020Q4' I can get an answer back in less than 10s according to SQL Developer.

Some key Maven dependencies include:

        <dependency>
            <groupId>com.cisco.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.3</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

When I get the DataSource to build the connection, I do it this way:

        OracleDataSource result = new OracleDataSource();
        Class.forName("oracle.jdbc.driver.OracleDriver");
        String connectionString = lCiscoLifeJdbcUrl;
        String username = lCiscoLifeJdbcUserName;
        String password = lCiscoLifeJdbcPassword;
        OracleDataSource oracleDataSource = (OracleDataSource)result;
        oracleDataSource.setURL(connectionString);
        oracleDataSource.setPassword(password);
        oracleDataSource.setUser(username);
        String timeoutKey = "oracle.jdbc.ReadTimeout";
        Properties connectionProperties;
        try {
            connectionProperties = oracleDataSource.getConnectionProperties();
            if(connectionProperties==null) {
                connectionProperties = new Properties();
            }
            connectionProperties.put(timeoutKey, 60 /* minutes */ * 60 /* seconds per minutes */ * 1000 /* ms per seconds */);
        } catch (SQLException e) {
            e.printStackTrace();
        }

From previous debugging, the connectionProperties defaulted to null, but I wanted to allow for those to be set by smarter people than myself.

Also, please note that this error occurs in about 8 out of 64 tests, so not every select triggers this issue.  I do no database updates or DML type statements.  Everything is assumed to be fully committed at this point.

I'm using MyBatis XML mapper files, but this is NOT a Spring driven project.  I manually build the DataSource, Configuration, Environment via Java objects.

What am I missing?


来源: stackexchange

问:
Getting error nonetype object is not callable, how do i remove this?
`This is the program to print a list of remainder by dividing a list by a given number, also I don't fully understand how to create a decorator would be helpful if someone could explain.

```<code># to print array of items of remainders
number_in_array = int(input("How many numbers do you want in the array? "))
array = []
remainder_array = []
for i in range(0,number_in_array):
    item_in_array = int(input("Enter no "+str(i+1)+" item : "))
    array.append(item_in_array)
print("Your array is :")
print(array)
divisor = int(input("Enter the number to divide array with : "))
def decider(function):
    def whenzero(array,divisor):
        for i in range(0,number_in_array):
            if array[i] == 0:
                print("Division is not possible")
                array.pop(i)
            else:
                return function(array,divisor)
        return whenzero()
@decider
def divide(array,divisor):
    for i in range(0,number_in_array):
        remainder = array[i] % divisor
        remainder_array.append(remainder)
    print(remainder_array)
divide(array,divisor)
</code>```

Thank you Anwarvic it did solve the nonetype error but when i want it to display "not possible" when a item in list is 0 it shows this error:

```<code>Traceback (most recent call last):
  File "C:/Users/acer/PycharmProjects/untitled/venv/Practice.py", line 26, in <module>
    divide(array, divisor, number_in_array,remainder_array)
  File "C:/Users/acer/PycharmProjects/untitled/venv/Practice.py", line 14, in whenzero
    if array[i] == 0:
IndexError: list index out of range
</code>```

I edited the code as follows:

```<code># to print array of items of remainders
number_in_array = int(input("How many numbers do you want in the array? "))
array = []
remainder_array = []
for i in range(0,number_in_array):
    item_in_array = int(input("Enter no "+str(i+1)+" item : "))
    array.append(item_in_array)
print("Your array is :")
print(array)
divisor = int(input("Enter the number to divide array with : "))
def decider(function):
    def whenzero(array,divisor,number_in_array,remainder_array):
        for i in range(0,number_in_array):
            if array[i] == 0:
                print("Division is not possible")
                array.pop(i)
            else:
                return function(array,divisor,number_in_array,remainder_array)
    return whenzero
@decider
def divide(array,divisor,number_in_array,remainder_array):
    for i in range(0,number_in_array):
        remainder = array[i] % divisor
        remainder_array.append(remainder)
    print(remainder_array)
divide(array, divisor, number_in_array,remainder_array)
</code>```

答:
You're almost there, all you need to do is to return whenzero from decider like so:

```<code>def decider(function):
    def whenzero(array, divisor):
        ...
    return whenzero    #<--- without parentheses and outside whenzero()

...
</code>```

Decorators are a design pattern that can be used to derive new functionality to your code at the last moment. I really suggest reading this blog post  to know more.

ContentLicense: CC BY-SA 4.0

Body:
`This is the program to print a list of remainder by dividing a list by a given number, also I don't fully understand how to create a decorator would be helpful if someone could explain.

# to print array of items of remainders
number_in_array = int(input("How many numbers do you want in the array? "))
array = []
remainder_array = []
for i in range(0,number_in_array):
    item_in_array = int(input("Enter no "+str(i+1)+" item : "))
    array.append(item_in_array)
print("Your array is :")
print(array)
divisor = int(input("Enter the number to divide array with : "))
def decider(function):
    def whenzero(array,divisor):
        for i in range(0,number_in_array):
            if array[i] == 0:
                print("Division is not possible")
                array.pop(i)
            else:
                return function(array,divisor)
        return whenzero()
@decider
def divide(array,divisor):
    for i in range(0,number_in_array):
        remainder = array[i] % divisor
        remainder_array.append(remainder)
    print(remainder_array)
divide(array,divisor)

Thank you Anwarvic it did solve the nonetype error but when i want it to display "not possible" when a item in list is 0 it shows this error:

Traceback (most recent call last):
  File "C:/Users/acer/PycharmProjects/untitled/venv/Practice.py", line 26, in <module>
    divide(array, divisor, number_in_array,remainder_array)
  File "C:/Users/acer/PycharmProjects/untitled/venv/Practice.py", line 14, in whenzero
    if array[i] == 0:
IndexError: list index out of range

I edited the code as follows:

# to print array of items of remainders
number_in_array = int(input("How many numbers do you want in the array? "))
array = []
remainder_array = []
for i in range(0,number_in_array):
    item_in_array = int(input("Enter no "+str(i+1)+" item : "))
    array.append(item_in_array)
print("Your array is :")
print(array)
divisor = int(input("Enter the number to divide array with : "))
def decider(function):
    def whenzero(array,divisor,number_in_array,remainder_array):
        for i in range(0,number_in_array):
            if array[i] == 0:
                print("Division is not possible")
                array.pop(i)
            else:
                return function(array,divisor,number_in_array,remainder_array)
    return whenzero
@decider
def divide(array,divisor,number_in_array,remainder_array):
    for i in range(0,number_in_array):
        remainder = array[i] % divisor
        remainder_array.append(remainder)
    print(remainder_array)
divide(array, divisor, number_in_array,remainder_array)

Body:
You're almost there, all you need to do is to return whenzero from decider like so:

def decider(function):
    def whenzero(array, divisor):
        ...
    return whenzero    #<--- without parentheses and outside whenzero()

...

Decorators are a design pattern that can be used to derive new functionality to your code at the last moment. I really suggest reading this blog post  to know more.


问:
Question about Introspection / static_assert (C++17)
I have a (container like) class that accepts several of my other types/classes as the data member. Now I would like to specify some properties (edit: positive integer) of the data type as compile time information. This works fine, but I would like to static_assert that the provided type is correct (uint8_t), the actual value is different for most data type classes. I set the number as a std::integral_constant with uint8_t.

1) How do I do that (see example code provided)?

2) Is there a better approach?

I can use language features up to c++17.

(edited for clarification)

```<code>class DataClass
{
     public:
        // compile time information about char count
        using char_count = std::integral_constant<uint8_t, 2>;

     private:
        ...
}

class DataClass2
{
     public:
        // compile time information about char count
        using char_count = std::integral_constant<uint8_t, 4>;

     private:
        ...
}

template <typename DataType, ...>
class ContainerClass
{
     private:
        // does not work: error C2923: 'std::is_same_v':
        // 'value' is not a valid template type argument for parameter '<unnamed-symbol>'
        static_assert(std::is_same_v<DataType::char_count::value, uint8_t>, "not uint8_t");
        // this also does not work
        static_assert(std::is_same_v<decltype(DataType::char_count::value), uint8_t>, "also not uint8_t");

        // using the value actually works fine
        constexpr static auto char_count = DataType::char_count::value;

     public:
        ...
}

</code>```

答:
What you want to do depends on what exatly do you want to check.

Want to check that char_count has value 2? static_assert(DataType::char_count::value == 2, "char_count is not 2!");

Want to check that char_count is an integral constant (or something else) that has uint8_t as type member type alias ? static_assert(std::is_same_v(typename DataType::char_count::value_type, "char_count is not uint8_t!");

Want to checkt that char_count is an integral constant with value 2 and type uint8_t? static_assert(std::is_same_v<DataType::char_count, std::integral_constant<uint8_t, 2>>, "char_count is not 2 or not uint8_t!");

Body:
I have a (container like) class that accepts several of my other types/classes as the data member. Now I would like to specify some properties (edit: positive integer) of the data type as compile time information. This works fine, but I would like to static_assert that the provided type is correct (uint8_t), the actual value is different for most data type classes. I set the number as a std::integral_constant with uint8_t.

1) How do I do that (see example code provided)?

2) Is there a better approach?

I can use language features up to c++17.

(edited for clarification)

class DataClass
{
     public:
        // compile time information about char count
        using char_count = std::integral_constant<uint8_t, 2>;

     private:
        ...
}

class DataClass2
{
     public:
        // compile time information about char count
        using char_count = std::integral_constant<uint8_t, 4>;

     private:
        ...
}

template <typename DataType, ...>
class ContainerClass
{
     private:
        // does not work: error C2923: 'std::is_same_v':
        // 'value' is not a valid template type argument for parameter '<unnamed-symbol>'
        static_assert(std::is_same_v<DataType::char_count::value, uint8_t>, "not uint8_t");
        // this also does not work
        static_assert(std::is_same_v<decltype(DataType::char_count::value), uint8_t>, "also not uint8_t");

        // using the value actually works fine
        constexpr static auto char_count = DataType::char_count::value;

     public:
        ...
}


问:
Most Efficient Way Of Clearing Cache Using ASP.NET
I am building an ASP.NET/Umbraco powered website which is very custom data driven via  entity framework, we are having to cache quite a lot of the data queries (For example searches by keyword) as it's a busy site.

But when a user creates a new data entry, I need to clear all the cached queries (Searches etc..) so the new entry is available in the results.

So in my create, delete and update methods I am calling the following method:

```<code>public static void ClearCacheItems()
{
    var enumerator = HttpContext.Current.Cache.GetEnumerator();

    while (enumerator.MoveNext())
    {
        HttpContext.Current.Cache.Remove(enumerator.Key.ToString());
    }
}
</code>```

Is this really bad? I can't see how else I am supposed to clear the cached items?

答:
Yep, never loop through the cache and remove items. It will give you a world of pain (I went through this recently). As you'll get an error "collection was modified, enumeration may not execute".

I also have a cache for searching, and I don't set an expiry - I manually invalidate when required.

The trick is the data is held into "buckets". That "bucket" is usually the parent identifier, or if you want to get into database terms, the foreign key.

So if you need to clear all "Orders" for a given "Customer", the cache key should be the CustomerId. In my case, I cache a ReadOnlyCollection<T>. So I don't need to loop, just remove it, then add in the fresh copy.

Also, to be doubly safe - I use a ReaderWriterLockSlim to invalidate the cache. When I know it needs to be invalidated, I first call the database, get a write lock, flush and refresh the relevant cache, then close the write lock.

That way it's all seamless.

ContentLicense: CC BY-SA 3.0

Body:
I am building an ASP.NET/Umbraco powered website which is very custom data driven via  entity framework, we are having to cache quite a lot of the data queries (For example searches by keyword) as it's a busy site.

But when a user creates a new data entry, I need to clear all the cached queries (Searches etc..) so the new entry is available in the results.

So in my create, delete and update methods I am calling the following method:

public static void ClearCacheItems()
{
    var enumerator = HttpContext.Current.Cache.GetEnumerator();

    while (enumerator.MoveNext())
    {
        HttpContext.Current.Cache.Remove(enumerator.Key.ToString());
    }
}

Is this really bad? I can't see how else I am supposed to clear the cached items?


问:
How skip value if the result minus? in excel
I want show up string from table use vlook up, but when the value has not been entered then the table is empty, but in the cell he has filled in the value = -4, can this be resolved?

my formula =VLOOKUP(MOD((U2-4);12);sio;2)

table_aray sio and output valu = -4 (block yellow = 'monyet')

答:
not sure about your data region, maybe something like this </p>

```<code>=if(isblank(U2),"",VLOOKUP(MOD((U2-4),12),sio,2,0)
</code>```

Body:
not sure about your data region, maybe something like this

=if(isblank(U2),"",VLOOKUP(MOD((U2-4),12),sio,2,0)


问:
Trying to convert into typescript..cant figure out how to make action types and payload..i am using useContext and use Reducer
Trying to convert  into typescript..cant figure out how to make action types and payload..i am using useContext and use Reducer
i basically want my action to get types from the key of ./types that is provided and laso figure out the way to provide pylaoad
this is my state

```<code>import React, { useReducer } from "react"
import AlertContext from "./AlertContext"
import { SHOW_ALERT,REMOVE_ALERT } from "../Types"
import AlertReducer from "./AlertReducer"
import { IAlertState } from "../IAlertState"

export interface typealert{
 variant : string,
text: string,
}
const AlertState = (props : any) =>{

const initialState :IAlertState = {
    alert:{
        variant :'',
        text :''
    }
}

const [state,dispatch] = useReducer(AlertReducer,initialState)

const showAlert =(variant : string,text : string) =>{
    dispatch({type:SHOW_ALERT,payload:{variant,text}})
    setTimeout(()=>{
        setAlert({variant:'',text:''})
    },2000)
}

const setAlert =(alert : typealert) => dispatch({type :REMOVE_ALERT,payload:null})

return(
    <AlertContext.Provider value={{
        alert:state.alert,
        showAlert
    }}>
        {props.children}
    </AlertContext.Provider>
)
</code>```

}

export default AlertState

this is my reducer

```<code>import React from "react"
import { SHOW_ALERT,REMOVE_ALERT } from "../Types"
import { IAlertState } from "../IAlertState"

export interface IActionTypes{
type : any,
payload : any
}

export default (state : IAlertState ,action : IActionTypes) =>{
switch(action.type)
{
    case SHOW_ALERT:
    return{
        ...state,
        alert:{
            variant : action.payload["variant"],
            text:action.payload["text"]
        }
    }
    case REMOVE_ALERT:
        return{
            ...state,
            alert:{
                variant: '',
                text:''
            }
        }
default : return state
}

}
</code>```

in this the action type i have provided is of any but i want it of type that is coming from ./types file here

```<code>export const SEARCH_USERS = 'SEARCH_USERS'
export const GET_USER ='GET_USER'
export const GET_REPOS = 'GET_REPOS'
export const CLEAR_USERS ='CLEAR_USERS'
export const SHOW_ALERT ='SHOW_ALERT'
export const SET_LOADING ='SET_LOADING'
export const USER_LOADING ='USER_LOADING'
export const REMOVE_ALERT ='REMOVE_ALERT'
</code>```

答:
type ActionTypes =
  | {
      type: SEARCH_USERS;
      payload: IAlertState["alert"];
    }
  | {
      type: REMOVE_ALERT;
      payload: void;
    }

  | ....

```

use union types to model your payload & type,
since type is a natural tag to discriminate the union type,
your code will get well-typed and proper narrowing

Body:
Trying to convert  into typescript..cant figure out how to make action types and payload..i am using useContext and use Reducer
i basically want my action to get types from the key of ./types that is provided and laso figure out the way to provide pylaoad
this is my state

import React, { useReducer } from "react"
import AlertContext from "./AlertContext"
import { SHOW_ALERT,REMOVE_ALERT } from "../Types"
import AlertReducer from "./AlertReducer"
import { IAlertState } from "../IAlertState"

export interface typealert{
 variant : string,
text: string,
}
const AlertState = (props : any) =>{

const initialState :IAlertState = {
    alert:{
        variant :'',
        text :''
    }
}

const [state,dispatch] = useReducer(AlertReducer,initialState)

const showAlert =(variant : string,text : string) =>{
    dispatch({type:SHOW_ALERT,payload:{variant,text}})
    setTimeout(()=>{
        setAlert({variant:'',text:''})
    },2000)
}

const setAlert =(alert : typealert) => dispatch({type :REMOVE_ALERT,payload:null})

return(
    <AlertContext.Provider value={{
        alert:state.alert,
        showAlert
    }}>
        {props.children}
    </AlertContext.Provider>
)

}

export default AlertState

this is my reducer

import React from "react"
import { SHOW_ALERT,REMOVE_ALERT } from "../Types"
import { IAlertState } from "../IAlertState"

export interface IActionTypes{
type : any,
payload : any
}

export default (state : IAlertState ,action : IActionTypes) =>{
switch(action.type)
{
    case SHOW_ALERT:
    return{
        ...state,
        alert:{
            variant : action.payload["variant"],
            text:action.payload["text"]
        }
    }
    case REMOVE_ALERT:
        return{
            ...state,
            alert:{
                variant: '',
                text:''
            }
        }
default : return state
}

}

in this the action type i have provided is of any but i want it of type that is coming from ./types file here

export const SEARCH_USERS = 'SEARCH_USERS'
export const GET_USER ='GET_USER'
export const GET_REPOS = 'GET_REPOS'
export const CLEAR_USERS ='CLEAR_USERS'
export const SHOW_ALERT ='SHOW_ALERT'
export const SET_LOADING ='SET_LOADING'
export const USER_LOADING ='USER_LOADING'
export const REMOVE_ALERT ='REMOVE_ALERT'

Body:
type ActionTypes =
  | {
      type: SEARCH_USERS;
      payload: IAlertState["alert"];
    }
  | {
      type: REMOVE_ALERT;
      payload: void;
    }

  | ....

use union types to model your payload & type,
since type is a natural tag to discriminate the union type,
your code will get well-typed and proper narrowing


问:
ClassNotFoundException: org.apache.commons.dbcp.BasicDataSourceFactory- on upgrading tomcat from version 7 to 9
I recently upgraded my tomcat to  from v7.3 to v9.43 and all of a sudden my application throws an exception at server startup while connecting to DB.
Exception LOG:
SEVERE: Exception processing global JNDI Resources
    javax.naming.NamingException: Could not load resource factory class [Root exception is java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSourceFactory]
        at org.apache.naming.factory.FactoryBase.getObjectInstance(FactoryBase.java:70)
        at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:321)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:857)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:160)
        at org.apache.naming.NamingContextBindingsEnumeration.nextElementInternal(NamingContextBindingsEnumeration.java:117)
        at org.apache.naming.NamingContextBindingsEnumeration.next(NamingContextBindingsEnumeration.java:71)
        at org.apache.naming.NamingContextBindingsEnumeration.next(NamingContextBindingsEnumeration.java:34)
        at org.apache.catalina.mbeans.GlobalResourcesLifecycleListener.createMBeans(GlobalResourcesLifecycleListener.java:127)
        at org.apache.catalina.mbeans.GlobalResourcesLifecycleListener.createMBeans(GlobalResourcesLifecycleListener.java:101)
        at org.apache.catalina.mbeans.GlobalResourcesLifecycleListener.lifecycleEvent(GlobalResourcesLifecycleListener.java:76)
        at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:123)
        at org.apache.catalina.util.LifecycleBase.setStateInternal(LifecycleBase.java:423)
        at org.apache.catalina.util.LifecycleBase.setState(LifecycleBase.java:366)
        at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:923)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
        at org.apache.catalina.startup.Catalina.start(Catalina.java:633)
        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:498)
        at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:343)
        at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:474)
    Caused by: java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSourceFactory
        at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        at org.apache.naming.factory.FactoryBase.getObjectInstance(FactoryBase.java:65)
        ... 21 more</p>

答:
You should add this dependency

Maven:

```<code><dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.4</version>
</dependency>
</code>```

Gradle:

```<code>compile group: 'commons-dbcp', name: 'commons-dbcp', version: '1.4'
</code>```

Body:
You should add this dependency

Maven:

<dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.4</version>
</dependency>

Gradle:

compile group: 'commons-dbcp', name: 'commons-dbcp', version: '1.4'


问:
JQ function hover()
I need to make an element selection when the cursor sticks on it for 3 seconds. In the above example, it turns out to select an element, but there are problems with elements that have a common ancestor, the timer is not reset to them, but when the "confirmed" class is present, everything works as planned, you need to make the timer reset.

Text translation...

```<code><style>
  .elem {
    -webkit-transition: background-color .3s ease-out, .2s outline ease-in-out !important;
    -o-transition: background-color .3s ease-out, .2s outline ease-in-out !important;
    transition: background-color .3s ease-out, .2s outline ease-in-out !important;
    background-color: #bcd5eb !important;
    outline: 1px solid #1d66bb !important;
    color: #333 !important;
    cursor: pointer !important;
    z-index: 999999 !important;
  }

  .confirmed {
    background-color: #fc7169 !important;
    outline: 1px solid #dd345f !important;
    color: #333 !important;
    cursor: pointer !important;
    z-index: 999999 !important;
  }
</style>
<ul>
  <li>menu 1</li>
  <li>menu 2</li>
  <li>menu 3</li>
  <li>menu 4</li>
  <li>menu 5</li>
</ul>

<div>
  <span>flow 1</span><br>
  <span>flow 2</span><br>
  <span>flow 3</span><br>
  <span>flow 4</span><br>
  <span>flow 5</span><br>
</div>
<br>
<span>flow 1</span><br>
<span>flow 2</span><br>
<span>flow 3</span><br>
<span>flow 4</span><br>
<span>flow 5</span><br>
<script>
  $('*').hover(
    function(event) {
      event.stopImmediatePropagation();

      event.stopPropagation();

      $('.elem').removeClass('elem');

      $(this).addClass('elem');

      $.data(this, 'timer',
        setTimeout($.proxy(
          function() {
            $('.confirmed').removeClass('confirmed');

            $('.elem').addClass('confirmed')
          }, this
        ), 2500)
      );
    },

    function() {
      clearTimeout($.data(this, 'timer'));

      $('.elem').removeClass('elem')

    }
  );
</script>
</code>```

EXAMPLE
https://jsfiddle.net/module/6k8zqpv4/3/

答:
How about manually resetting the timers of all parent elements on mouseout? It no longer experiences the problem where the timer continues to run down when waving the mouse over a group when there is no ".confirmed" element. Your javascript would look like this:</p>

```<code>$( '*' ).hover(
  function( event ) {
    event.stopImmediatePropagation();

    event.stopPropagation();

    $( '.elem' ).removeClass( 'elem' );

    $( this ).addClass( 'elem' );

    $.data( this, 'timer',
           setTimeout( $.proxy(
      function() {
        $( '.confirmed' ).removeClass( 'confirmed' );

        $( '.elem' ).addClass( 'confirmed' )
      }, this
    ), 2500 )
          );
  },

  function() {
    clearTimeout( $.data( this, 'timer' ) );

    // new code
    $(this).parents().each(function(index, parent){
      clearTimeout($(parent).data("timer"));
    });

    $( '.elem' ).removeClass( 'elem' )

  }
);
</code>```

Title: JQ function hover()

Body:
I need to make an element selection when the cursor sticks on it for 3 seconds. In the above example, it turns out to select an element, but there are problems with elements that have a common ancestor, the timer is not reset to them, but when the "confirmed" class is present, everything works as planned, you need to make the timer reset.

Text translation...

menu 1

menu 2

menu 3

menu 4

menu 5

  flow 1

  flow 2

  flow 3

  flow 4

  flow 5

flow 1

flow 2

flow 3

flow 4

flow 5

EXAMPLE
https://jsfiddle.net/module/6k8zqpv4/3/

Body:
How about manually resetting the timers of all parent elements on mouseout? It no longer experiences the problem where the timer continues to run down when waving the mouse over a group when there is no ".confirmed" element. Your javascript would look like this:

$( '*' ).hover(
  function( event ) {
    event.stopImmediatePropagation();

    event.stopPropagation();

    $( '.elem' ).removeClass( 'elem' );

    $( this ).addClass( 'elem' );

    $.data( this, 'timer',
           setTimeout( $.proxy(
      function() {
        $( '.confirmed' ).removeClass( 'confirmed' );

        $( '.elem' ).addClass( 'confirmed' )
      }, this
    ), 2500 )
          );
  },

  function() {
    clearTimeout( $.data( this, 'timer' ) );

    // new code
    $(this).parents().each(function(index, parent){
      clearTimeout($(parent).data("timer"));
    });

    $( '.elem' ).removeClass( 'elem' )

  }
);


问:
Junit test becomes broken when I change a way to initialize Mockito
```<code>public class DummyTest {

    @InjectMocks
    private TestService service;
    @Mock
    private TestRepository repository;

    @BeforeEach
    public void before() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testMe() {
        when(repository.findAllByQuery("")).thenReturn(List.of());
        List<String> entities = service.findAllByQuery("test");

        verify(repository, times(1)).findAllByQuery(anyString());
    }
}

class TestService {

    private TestRepository repository;

    public List<String> findAllByQuery(String query) {
        return repository.findAllByQuery(query);
    }
}

class TestRepository {

    public List<String> findAllByQuery(String query) {
        return List.of("");
    }
}
</code>```

The test above successfully passed when I do Mockito initialization via @BeforeEach annotation.
After, I tried to remove @BeforeEach annotation and initialize Mockito with @ExtendWith(MockitoExtension.class) and the test failed due to:

org.mockito.exceptions.misusing.UnnecessaryStubbingException:

```<code>org.mockito.exceptions.misusing.UnnecessaryStubbingException:
Unnecessary stubbings detected.
Clean & maintainable test code requires zero unnecessary code.
Following stubbings are unnecessary (click to navigate to relevant line of code):
  1. -> at DummyTest.testMe(DummyTest.java:33)
Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class.
</code>```

Could you please explain to me, why I got so different test execution results? Technically, I have just changed the way to initialize Mockito and that all.

答:
@ExtendWith(MockitoExtension.class) and MockitoAnnotations.initMocks(this) configures Mockito in a little different way.

When you use @ExtendWith(MockitoExtension.class) additionally configures "strictness" of Mockito with default value STRICT_STUBS.

Which means you have to change the configuration of you stubs like this:

    @Test
    public void testMe() {
        when(repository.findAllByQuery(anyString())).thenReturn(List.of());
        List<String> entities = service.findAllByQuery("test");

        verify(repository, times(1)).findAllByQuery(anyString());
    }
```

<p>or even like this:</p>

<pre class="lang-java prettyprint-override"><code>    @Test
    public void testMe() {
        when(repository.findAllByQuery(eq("test"))).thenReturn(List.of());
        List<String> entities = service.findAllByQuery("test");

        verify(repository, times(1)).findAllByQuery(anyString());
    }
</code>```

Body:
public class DummyTest {

    @InjectMocks
    private TestService service;
    @Mock
    private TestRepository repository;

    @BeforeEach
    public void before() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testMe() {
        when(repository.findAllByQuery("")).thenReturn(List.of());
        List<String> entities = service.findAllByQuery("test");

        verify(repository, times(1)).findAllByQuery(anyString());
    }
}

class TestService {

    private TestRepository repository;

    public List<String> findAllByQuery(String query) {
        return repository.findAllByQuery(query);
    }
}

class TestRepository {

    public List<String> findAllByQuery(String query) {
        return List.of("");
    }
}

The test above successfully passed when I do Mockito initialization via @BeforeEach annotation.
After, I tried to remove @BeforeEach annotation and initialize Mockito with @ExtendWith(MockitoExtension.class) and the test failed due to:

org.mockito.exceptions.misusing.UnnecessaryStubbingException:

org.mockito.exceptions.misusing.UnnecessaryStubbingException:
Unnecessary stubbings detected.
Clean & maintainable test code requires zero unnecessary code.
Following stubbings are unnecessary (click to navigate to relevant line of code):
  1. -> at DummyTest.testMe(DummyTest.java:33)
Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class.

Could you please explain to me, why I got so different test execution results? Technically, I have just changed the way to initialize Mockito and that all.

Body:
@ExtendWith(MockitoExtension.class) and MockitoAnnotations.initMocks(this) configures Mockito in a little different way.

When you use @ExtendWith(MockitoExtension.class) additionally configures "strictness" of Mockito with default value STRICT_STUBS.

Which means you have to change the configuration of you stubs like this:

    @Test
    public void testMe() {
        when(repository.findAllByQuery(anyString())).thenReturn(List.of());
        List<String> entities = service.findAllByQuery("test");

        verify(repository, times(1)).findAllByQuery(anyString());
    }

or even like this:

    @Test
    public void testMe() {
        when(repository.findAllByQuery(eq("test"))).thenReturn(List.of());
        List<String> entities = service.findAllByQuery("test");

        verify(repository, times(1)).findAllByQuery(anyString());
    }


问:
Does APNG support frame-based palettes or only a global palette?
I'm having a hard time understanding how palette information is handled in APNG animations that use type PNG_COLOR_TYPE_PALETTE because, apparently, there is little to no documentation.

All PNG_COLOR_TYPE_PALETTE test animation files that I have have just a single PLTE chunk; i.e., all frames share the same global palette. Is this a limitation of the APNG file format; or, can frames also use individual palettes as is possible with GIF, for example? If that is possible, where should the frame-based PLTE chunks go?

Thanks!

答: To answer my own question, I've tried several tools which convert GIFs to APNG and when I use them with multi-palette GIFs those tools always remap the frame pixels to one global palette so I guess APNG doesn't support multiple palettes but just a single global palette shared by all frames.</p>


问:
How to pass the input arguments of a function into the block body of it
I'm implementing asp.net core project. In the razor view my code is like the following:

```<code>     @using System.Linq;

@model CSDDashboard.TempClasses.ChartListObjects
@{

    var XLabels = Newtonsoft.Json.JsonConvert.SerializeObject(Model.TotalReqStatus.Select(i => i.DimensionOne).ToList());
    var YValues = Newtonsoft.Json.JsonConvert.SerializeObject(Model.TotalReqStatus.Select(i => i.Quantity).ToList());
    ViewData["Title"] = "Pie Chart";
    //-----------------
    var XLabels1 = Newtonsoft.Json.JsonConvert.SerializeObject(Model.GrantedTimeAvg.Select(i => i.DimensionOne).ToList());
    var YValues1 = Newtonsoft.Json.JsonConvert.SerializeObject(Model.GrantedTimeAvg.Select(i => i.Quantity).ToList());
    ViewData["Title"] = "Line Chart";
    //------------------
    var XLabels2 = Newtonsoft.Json.JsonConvert.SerializeObject(Model.GrantedPercent.Select(i => i.DimensionOne).ToList());
    var YValues2 = Newtonsoft.Json.JsonConvert.SerializeObject(Model.GrantedPercent.Select(i => i.Quantity).ToList());
    ViewData["Title"] = "Line Chart";
    //------------------
    var XLabels3 = Newtonsoft.Json.JsonConvert.SerializeObject(Model.GrantedApiToApplicantAvg.Select(i => i.DimensionOne).ToList());
    var YValues3 = Newtonsoft.Json.JsonConvert.SerializeObject(Model.GrantedApiToApplicantAvg.Select(i => i.Quantity).ToList());
    ViewData["Title"] = "Line Chart";
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    @**@
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <style>

        html, body, h1, h2, h3, h4, h5 {
            font-family: "Raleway", sans-serif
        }
    </style>
</head>

<body>
    <canvas id="piechart" style="width:100%; height:500px"></canvas>
    <canvas id="linechart1" style="width:100%; height:500px"></canvas>
    <canvas id="linechart2" style="width:100%; height:500px"></canvas>
    <canvas id="linechart3" style="width:100%; height:500px"></canvas>
<div class="container" style="width:100%; height:500px">
        <div class="row">
 </div>
            <div class="col-3">
                @*style="width:30%">*@
                <!-- pie chart -->
                <script type="text/javascript">
@*Pie chart eliminated*@
                    PieChartShow(XLabels,YValues,piechart);
                </script>
                <!--cell 4 row 1-->
            </div>
        </div>
        <div class="row">
            <div class="col-4">
                <!-- line chart -->
                <script type="text/javascript">
                    LineChartShow(XLabels1, YLabels1,linechart1);
                </script>
                <!--cell 1 row 2-->
            </div>
            <div class="col-4">
                <!-- line chart -->
                <script type="text/javascript">
                    LineChartShow(XLabels2, YLabels2,linechart2);
                </script>
                <!--cell2 row 2-->
            </div>

            <div class="col-4">
                <!-- line chart -->
                <script type="text/javascript">
                    LineChartShow(XLabels3, YLabels3,,linechart3);
                </script>
                <!--cell3 row3-->
            </div>
       </div>
    </div>

</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
    var PieChartShow =
    $(function () {
        // var chartName = "piechart";

         //Here is where I have the problem:
        var myXLabels = arguments[0];
        var YYalues = arguments[1];
        var chartName = arguments[2];
    var ctx = document.getElementById(chartName).getContext('2d');
    var data = {
    labels: @Html.Raw(myXLabels),
    datasets: [{
    label: "API Charts",
    backgroundColor: [
    'rgba(255, 99, 132, 0.2)',
    'rgba(54, 162, 235, 0.2)',
    'rgba(255, 206, 86, 0.2)',
    'rgba(75, 192, 192, 0.2)',
    'rgba(153, 102, 255, 0.2)',
    'rgba(255, 159, 64, 0.2)',
    'rgba(255, 0, 0)',
    'rgba(0, 255, 0)',
    'rgba(0, 0, 255)',
    'rgba(192, 192, 192)',
    'rgba(255, 255, 0)',
    'rgba(255, 0, 255)'
    ],
    borderColor: [
    'rgba(255,99,132,1)',
    'rgba(54, 162, 235, 1)',
    'rgba(255, 206, 86, 1)',
    'rgba(75, 192, 192, 1)',
    'rgba(153, 102, 255, 1)',
    'rgba(255, 159, 64, 1)',
    'rgba(255, 0, 0)',
    'rgba(0, 255, 0)',
    'rgba(0, 0, 255)',
    'rgba(192, 192, 192)',
    'rgba(255, 255, 0)',
    'rgba(255, 0, 255)'
    ],
    borderWidth: 1,
    data: @Html.Raw(YValues)
    }]
    };

    var options = {
    maintainAspectRatio: false,
    scales: {
    yAxes: [{
    ticks: {
    min: 0,
    beginAtZero: true
    },
    gridLines: {
    display: true,
    color: "rgba(255,99,164,0.2)"
    }
    }],
    xAxes: [{
    ticks: {
    min: 0,
    beginAtZero: true
    },
    gridLines: {
    display: false
    }
    }]
    }
    };

    var myChart = new  Chart(ctx, {
    options: options,
    data: data,
    type:'pie'

    });
    });

    @**@
var LineChartShow = $(function () {

            var chartName = arguments[2];
            var ctx = document.getElementById(chartName).getContext('2d');
            var data = {
                labels: @Html.Raw(arguments[0]),
                @*labels: @Html.Raw(),*@
                @*labels: @Html.Raw(),*@
                datasets: [{
                    label: "API Charts",
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(54, 162, 235, 0.2)',
                        'rgba(255, 206, 86, 0.2)',
                        'rgba(75, 192, 192, 0.2)',
                        'rgba(153, 102, 255, 0.2)',
                        'rgba(255, 159, 64, 0.2)',
                        'rgba(255, 0, 0)',
                        'rgba(0, 255, 0)',
                        'rgba(0, 0, 255)',
                        'rgba(192, 192, 192)',
                        'rgba(255, 255, 0)',
                        'rgba(255, 0, 255)'
                    ],
                    borderColor: [
                        'rgba(255,99,132,1)',
                        'rgba(54, 162, 235, 1)',
                        'rgba(255, 206, 86, 1)',
                        'rgba(75, 192, 192, 1)',
                        'rgba(153, 102, 255, 1)',
                        'rgba(255, 159, 64, 1)',
                        'rgba(255, 0, 0)',
                        'rgba(0, 255, 0)',
                        'rgba(0, 0, 255)',
                        'rgba(192, 192, 192)',
                        'rgba(255, 255, 0)',
                        'rgba(255, 0, 255)'
                    ],
                    borderWidth: 1,
                    data: @Html.Raw(YValues1)
            }]
            };

            var options = {
                maintainAspectRatio: false,
                scales: {
                    yAxes: [{
                        ticks: {
                            min: 0,
                            beginAtZero: true
                        },
                        gridLines: {
                            display: true,
                            color: "rgba(255,99,164,0.2)"
                        }
                    }],
                    xAxes: [{
                        ticks: {
                            min: 0,
                            beginAtZero: true
                        },
                        gridLines: {
                            display: false
                        }
                    }]
                }
            };

            var myChart = new Chart(ctx, {
                options: options,
                data: data,
                type: 'line'

            });
        });

</script>
</code>```

In a div tag, I call PieChartShow(XLabels,YValues,piechart); and i want to pass XLabels, YValues and piechart as the input parameters of PieChartShow javascript function and the third parameter "piechart" is the related canvas id. But now my problem is myXLabels is unknown inside the block of data in the function PieChartShow. I appreciate if anyone suggests me how I can pass XLabels and YValues into PieChartShow function.

答:
Try updating your function to

```<code>function PieChartShow(XLabels) {
    var ctx = document.getElementById(chartName).getContext('2d');
    var data = {
       labels: @Html.Raw(XLabels)
    }
}
</code>```

I am not sure this is the full implementation of your function though.

Body:
I'm implementing asp.net core project. In the razor view my code is like the following:

     @using System.Linq;

@model CSDDashboard.TempClasses.ChartListObjects
@{

    var XLabels = Newtonsoft.Json.JsonConvert.SerializeObject(Model.TotalReqStatus.Select(i => i.DimensionOne).ToList());
    var YValues = Newtonsoft.Json.JsonConvert.SerializeObject(Model.TotalReqStatus.Select(i => i.Quantity).ToList());
    ViewData["Title"] = "Pie Chart";
    //-----------------
    var XLabels1 = Newtonsoft.Json.JsonConvert.SerializeObject(Model.GrantedTimeAvg.Select(i => i.DimensionOne).ToList());
    var YValues1 = Newtonsoft.Json.JsonConvert.SerializeObject(Model.GrantedTimeAvg.Select(i => i.Quantity).ToList());
    ViewData["Title"] = "Line Chart";
    //------------------
    var XLabels2 = Newtonsoft.Json.JsonConvert.SerializeObject(Model.GrantedPercent.Select(i => i.DimensionOne).ToList());
    var YValues2 = Newtonsoft.Json.JsonConvert.SerializeObject(Model.GrantedPercent.Select(i => i.Quantity).ToList());
    ViewData["Title"] = "Line Chart";
    //------------------
    var XLabels3 = Newtonsoft.Json.JsonConvert.SerializeObject(Model.GrantedApiToApplicantAvg.Select(i => i.DimensionOne).ToList());
    var YValues3 = Newtonsoft.Json.JsonConvert.SerializeObject(Model.GrantedApiToApplicantAvg.Select(i => i.Quantity).ToList());
    ViewData["Title"] = "Line Chart";
}

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    @**@
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    <canvas id="piechart" style="width:100%; height:500px"></canvas>
    <canvas id="linechart1" style="width:100%; height:500px"></canvas>
    <canvas id="linechart2" style="width:100%; height:500px"></canvas>
    <canvas id="linechart3" style="width:100%; height:500px"></canvas>

                @*style="width:30%">*@

In a div tag, I call PieChartShow(XLabels,YValues,piechart); and i want to pass XLabels, YValues and piechart as the input parameters of PieChartShow javascript function and the third parameter "piechart" is the related canvas id. But now my problem is myXLabels is unknown inside the block of data in the function PieChartShow. I appreciate if anyone suggests me how I can pass XLabels and YValues into PieChartShow function.

Body:
Try updating your function to

function PieChartShow(XLabels) {
    var ctx = document.getElementById(chartName).getContext('2d');
    var data = {
       labels: @Html.Raw(XLabels)
    }
}

I am not sure this is the full implementation of your function though.


问:
Getting response null while testing TCP calls for multiple api with JMeter using CSV Data Config
I am trying to load test with Jmeter using TCP sampler with CSV DATA config. When I am running a single API(TCP call)in the loop then it is getting the response of all API request, however, if I am hitting two different API calls(TCP calls) in the loop the second one always fails with response null, but I do see the server responding when I test the same using command line. What could be the cause and possible solution to help Jmeter read the response for all API requests is made.

Success case with only one TCP calls:
enter image description here

Failure case with 2 different TCP calls:

enter image description here

答: I figured it out the in Jmeter it reads the one CSV file in one user thread. Though in the same test plan I have two TCP sampler test cases and both were reading different CSV files using CSV data config but the file in the first test case was getting read and the second test case CSV file was ignored. That is why the second test case was failing. So this infers that to run multiple test cases in a test plan we can read only one file at the test plan level. </p>


问:
Show legend in chart
I am using Microsoft Chart, and I have top Legend displayed at the top in a pie chart. Which property is used to show or hide the legend of a pie chart?</p>

答:
Just do the following.

```<code>Legend leg = new Legend();
Chart1.Legends.Add(leg);// This will show all legends.
</code>```

Actually you have to create a legend object, set its different or desired properties like font, etc., and then add it to the chart.

Title: Show legend in chart

Body:
Just do the following.

Legend leg = new Legend();
Chart1.Legends.Add(leg);// This will show all legends.

Actually you have to create a legend object, set its different or desired properties like font, etc., and then add it to the chart.


问:
Outlook email - SMTPLIB - Can't send emails
I'm creating a script that sends emails with my outlook email that have the following SMTP settings:

```<code>Servername: smtp.office365.com
Port: 587
Protocol command: STARTTLS
</code>```

For that I was using the following code:

```<code>client = smtplib.SMTP('smtp.office365.com', 587)
client.ehlo()
client.starttls()
client.ehlo()
client.login(user, password)
client.sendmail(msg['From'], emaillist , msg.as_string())
client.close()
</code>```

And I am getting the following error:

```<code>(554, b'5.2.0 STOREDRV.Submission.Exception:OutboundSpamException; Failed to process message due to a permanent exception with message WASCL UserAction verdict is not None. Actual verdict is HipNotify. OutboundSpamException: WASCL UserAction verdict is not None. Actual verdict is HipNotify. [Hostname=DB8P191MB0809.EURP191.PROD.OUTLOOK.COM]')
</code>```

What I am doing wrong?

答:
Your code looks fine- this is an email server error message rather than a Python exception. For some reason (probably to stop automated programs sending spam) your email host is blocking your email.

This github thread here suggests that you can fix the issue by logging in confirming your identity.

Body:
I'm creating a script that sends emails with my outlook email that have the following SMTP settings:

Servername: smtp.office365.com
Port: 587
Protocol command: STARTTLS

For that I was using the following code:

client = smtplib.SMTP('smtp.office365.com', 587)
client.ehlo()
client.starttls()
client.ehlo()
client.login(user, password)
client.sendmail(msg['From'], emaillist , msg.as_string())
client.close()

And I am getting the following error:

(554, b'5.2.0 STOREDRV.Submission.Exception:OutboundSpamException; Failed to process message due to a permanent exception with message WASCL UserAction verdict is not None. Actual verdict is HipNotify. OutboundSpamException: WASCL UserAction verdict is not None. Actual verdict is HipNotify. [Hostname=DB8P191MB0809.EURP191.PROD.OUTLOOK.COM]')

What I am doing wrong?


问:
React Native - Switch two values
I'm trying to see if I can switch between two values for my navigator:
This works:

```<code>function getHeaderTitle(route) {
  const routeName = route.state
    ? route.state.routes[route.state.index].name
    : route.params?.screen || 'The Market';

  switch (routeName) {
    case 'Stands':
      return 'The Market';
    case 'Map':
      return 'How to find the Market';
    case 'Favorites':
      return 'Favorites';
    case 'Info':
      return 'Info about the Market';
  }

  return routeName;
}
</code>```

where I need I exec:

```<code>getHeaderTitle(route) // works
</code>```

and I would like to add a value (color) to avoid to create a second one just for it:

```<code>function getHeaderTitle(route) {
  const routeName = route.state
    ? route.state.routes[route.state.index].name
    : route.params?.screen || 'The Market';

  let color;

  switch ((routeName, color)) {
    case 'Stands':
      return 'The Market', (color = Colors.MarketColor);
    case 'Map':
      return 'How to find the Market', (color = Colors.MapColor);
    case 'Favorites':
      return 'Favorites', (color = Colors.FavColor);
    case 'Info':
      return 'Info about the Market', (color = Colors.InfoColor);
  }
  return routeName, color;
}
</code>```

But it doesn't work.
Any idea?
thanks

答:
As you have specific colors for each route, you can set it as an object and return it from switch. And switch doesnt support multiple variables. You will have to go with an if else. And rather than returning outside you can return using the default case with a default color.</p>

```<code>function getHeaderTitle(route) {
  const routeName = route.state
    ? route.state.routes[route.state.index].name
    : route.params ?.screen || 'The Market';

  switch (routeName) {
    case 'Stands':
      return { route: 'The Market', color: Colors.MarketColor };
    case 'Map':
      return { route: 'How to find the Market', color: Colors.MapColor };
    case 'Favorites':
      return { route: 'Favorites', color: Colors.FavColor };
    case 'Info':
      return { route: 'Info about the Market', color: Colors.InfoColor };
    default:
      return { route: routeName, color: 'default color' };
  }

}
</code>```

Title: React Native - Switch two values

Body:
I'm trying to see if I can switch between two values for my navigator:
This works:

function getHeaderTitle(route) {
  const routeName = route.state
    ? route.state.routes[route.state.index].name
    : route.params?.screen || 'The Market';

  switch (routeName) {
    case 'Stands':
      return 'The Market';
    case 'Map':
      return 'How to find the Market';
    case 'Favorites':
      return 'Favorites';
    case 'Info':
      return 'Info about the Market';
  }

  return routeName;
}

where I need I exec:

getHeaderTitle(route) // works

and I would like to add a value (color) to avoid to create a second one just for it:

function getHeaderTitle(route) {
  const routeName = route.state
    ? route.state.routes[route.state.index].name
    : route.params?.screen || 'The Market';

  let color;

  switch ((routeName, color)) {
    case 'Stands':
      return 'The Market', (color = Colors.MarketColor);
    case 'Map':
      return 'How to find the Market', (color = Colors.MapColor);
    case 'Favorites':
      return 'Favorites', (color = Colors.FavColor);
    case 'Info':
      return 'Info about the Market', (color = Colors.InfoColor);
  }
  return routeName, color;
}

But it doesn't work.
Any idea?
thanks

Body:
As you have specific colors for each route, you can set it as an object and return it from switch. And switch doesnt support multiple variables. You will have to go with an if else. And rather than returning outside you can return using the default case with a default color.

function getHeaderTitle(route) {
  const routeName = route.state
    ? route.state.routes[route.state.index].name
    : route.params ?.screen || 'The Market';

  switch (routeName) {
    case 'Stands':
      return { route: 'The Market', color: Colors.MarketColor };
    case 'Map':
      return { route: 'How to find the Market', color: Colors.MapColor };
    case 'Favorites':
      return { route: 'Favorites', color: Colors.FavColor };
    case 'Info':
      return { route: 'Info about the Market', color: Colors.InfoColor };
    default:
      return { route: routeName, color: 'default color' };
  }

}


问:
bash how to link multilines to command?
I would like to do something like that inside the script

```<code>readonly refScript="./libs/refScript.sh"
readonly config=$(cat myConfig.txt) #multiline config file

readonly exec="$refScript $config"

$($exec "$1" "$2" "$3" "$4") #exec has problem because $config is multiline
</code>```

I would like to do something like $($exec "$1" "$2" "$3" "$4") instead of and doing $("$refScript" "$config" "$1" "$2" "$3" "$4"). How to do this?

答:
Of course, already the cocept of

```<code>$($exec ....)
</code>```

looks weird. It means that you first run the command stored in the variable exec, and then interpret the standard output of this command as another command to be executed. While this is not forbidden, I would be really surprised if you really intended it in this way.

But to focus on your original question: For passing the newline characters of your parameter configuration, just quote the evaluation:

```<code>./libs/refScript.sh "$(<myConfig.txt)" "$1" "$2" "$3" "$4"
</code>```

Title: bash how to link multilines to command?

Body:
I would like to do something like that inside the script

readonly refScript="./libs/refScript.sh"
readonly config=$(cat myConfig.txt) #multiline config file

readonly exec="$refScript $config"

$($exec "$1" "$2" "$3" "$4") #exec has problem because $config is multiline

I would like to do something like $($exec "$1" "$2" "$3" "$4") instead of and doing $("$refScript" "$config" "$1" "$2" "$3" "$4"). How to do this?

Body:
Of course, already the cocept of

$($exec ....)

looks weird. It means that you first run the command stored in the variable exec, and then interpret the standard output of this command as another command to be executed. While this is not forbidden, I would be really surprised if you really intended it in this way.

But to focus on your original question: For passing the newline characters of your parameter configuration, just quote the evaluation:

./libs/refScript.sh "$(<myConfig.txt)" "$1" "$2" "$3" "$4"


问:
Google Cloud KMS encryption got very different results between command line and java code
I am a beginner to google cloud. I have a java code which uses KMS to encrypt some credential information. At last it returns the cyphertext (a String object), which is what i need. It gives me something like this:

CiQAUxKMC06hZ7cuhlqdQQPGdNJqotwoKlSzjKmr+kwR3iMLg04SZABqmWMTCukKk0EVIDa1PpqqSIszczXGvt+nQN/jpV3DLEjXH3xkzdL0an9kiRIfLHryhcFwaYt/DczI4sy4VdZSoyKcszzZyGdVjISsyIbMnYINuqme1sa7GqLM98cXfnYzHjE=

```<code>EncryptResponse response = kms.projects().locations().keyRings().cryptoKeys()
            .encrypt(resourceName, request)
            .execute();
return response.getCiphertext();
</code>```

Now I also want a bootstrap script that could do the similar thing. However, when I use command line as follows. The content in the encryption.txt file is not nice looking as a String, but some unicode characters. Is there a way I could achieve the above nice encryption string by using gcloud kms command line?

export ENCRYPTION=$(gcloud kms encrypt --location=global --keyring=$KEYRING --key=$KEY --plaintext-file=text.txt --ciphertext-file=encryption.txt)

答:
There are 2 things.
One is the API Call.

```<code>curl -s -X POST "https://cloudkms.googleapis.com/v1/projects/<PROJECT>/locations/<LOCATIO >/keyRings/<KEY_RING>/cryptoKeys/<KEY>:encrypt" \
-d "{\"plaintext\":\"$(echo hello world | base64)\"}" \
-H "Authorization:Bearer $(gcloud auth application-default print-access-token)" \  -H "Content-Type:application/json"
</code>```

This API call gives base64 encoded value of cipher text which is readable.

Another way is yo use SDK (here only talking about java SDK)

EncryptResponse.getCiphertext() will return gibberish, you have to encode it using base64 to get the readable cipher text

```<code>String cipherText = new String(Base64.getEncoder().encode(response.getCiphertext().toByteArray()))
</code>```

output of above string and cipher text received by API will match.

Similarly while decoding using KMS, API will give base64 decoded value of text on the other hand you have to manually convert output of SDK call to string by decoding

```<code> String decodedText = new String(Base64.getDecoder().decode(key)
</code>```

Body:
I am a beginner to google cloud. I have a java code which uses KMS to encrypt some credential information. At last it returns the cyphertext (a String object), which is what i need. It gives me something like this:

CiQAUxKMC06hZ7cuhlqdQQPGdNJqotwoKlSzjKmr+kwR3iMLg04SZABqmWMTCukKk0EVIDa1PpqqSIszczXGvt+nQN/jpV3DLEjXH3xkzdL0an9kiRIfLHryhcFwaYt/DczI4sy4VdZSoyKcszzZyGdVjISsyIbMnYINuqme1sa7GqLM98cXfnYzHjE=

EncryptResponse response = kms.projects().locations().keyRings().cryptoKeys()
            .encrypt(resourceName, request)
            .execute();
return response.getCiphertext();

Now I also want a bootstrap script that could do the similar thing. However, when I use command line as follows. The content in the encryption.txt file is not nice looking as a String, but some unicode characters. Is there a way I could achieve the above nice encryption string by using gcloud kms command line?

export ENCRYPTION=$(gcloud kms encrypt --location=global --keyring=$KEYRING --key=$KEY --plaintext-file=text.txt --ciphertext-file=encryption.txt)

Body:
There are 2 things.
One is the API Call.

curl -s -X POST "https://cloudkms.googleapis.com/v1/projects/<PROJECT>/locations/<LOCATIO >/keyRings/<KEY_RING>/cryptoKeys/<KEY>:encrypt" \
-d "{\"plaintext\":\"$(echo hello world | base64)\"}" \
-H "Authorization:Bearer $(gcloud auth application-default print-access-token)" \  -H "Content-Type:application/json"

This API call gives base64 encoded value of cipher text which is readable.

Another way is yo use SDK (here only talking about java SDK)

EncryptResponse.getCiphertext() will return gibberish, you have to encode it using base64 to get the readable cipher text

String cipherText = new String(Base64.getEncoder().encode(response.getCiphertext().toByteArray()))

output of above string and cipher text received by API will match.

Similarly while decoding using KMS, API will give base64 decoded value of text on the other hand you have to manually convert output of SDK call to string by decoding

 String decodedText = new String(Base64.getDecoder().decode(key)


问:
"CFBundleVersion must be a string" from OS X dashboard
While developing my dashboard widget, I looked at the console (system logs) and found that an error message:

```<code>2009-03-06 22:08:35.244 Widget Installer[3874] CFBundleVersion must be a string
</code>```

The property is marked as type string in Info.plist.  I've tried changing it from a 1.2 number to a series of letters (can't be mistaken for number) and also following apple's versioning guidelines.  No mater, what, I get this error every time.

答: The Widget Installer parses all the existing widgets to check for older versions.  This message can come from any widget on your system, and if you've checked your own, it's probably one of the others.

OwnerDisplayName: Justin Love

ContentLicense: CC BY-SA 2.5

Body:
While developing my dashboard widget, I looked at the console (system logs) and found that an error message:

2009-03-06 22:08:35.244 Widget Installer[3874] CFBundleVersion must be a string

The property is marked as type string in Info.plist.  I've tried changing it from a 1.2 number to a series of letters (can't be mistaken for number) and also following apple's versioning guidelines.  No mater, what, I get this error every time.


问:
The mysqli_connect not working
I installed apache, php and mysql. Now when I execute the php code, the mysqli_connect() is not working, neither it's showing the message in die.

```<code>$dbc=mysqli_connect(' ', ' ', ' ', ' ') or die('not connecting');
</code>```

Now someone tell me what database username shall I pass to mysqli_connect and what password. I don't remember I was asked for any username or password
and why isn't the message in die() showing up?

My var_dump(function_exists('mysqli_connect')); outputs bool(false).. if it has anything to do with it, how do I correct it.?

答: Looks like MySQLi extension is not installed. What does var_dump(function_exists('mysqli_connect')); output?

Title: The mysqli_connect not working

Body:
I installed apache, php and mysql. Now when I execute the php code, the mysqli_connect() is not working, neither it's showing the message in die.

$dbc=mysqli_connect(' ', ' ', ' ', ' ') or die('not connecting');

Now someone tell me what database username shall I pass to mysqli_connect and what password. I don't remember I was asked for any username or password
and why isn't the message in die() showing up?

My var_dump(function_exists('mysqli_connect')); outputs bool(false).. if it has anything to do with it, how do I correct it.?


问:
echo $JAVA_HOME returns blank in MacOS catalina despite having set it properly in zshrc
I a using the latest MacOS catalina(10.15.4) and using .zshrc for my profile as latest version of mac deprecated the bash shell, This is the follow-up question of my previous unanswered question on not able to change the default java version to 1.8 using jenv.

When I was trying to debug more found my echo $JAVA_HOME always returns blank, despite having set it in following manner.

```<code>export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)
</code>```

And

```<code>export JAVA_HOME=/Library/Java/JavaVirtualMachines/amazon-corretto-8.jdk/Contents/Home
</code>```

Note i've sourced my .zshrc file after the change but still no luck, although when I set on the terminal then it print the proper value but its only on that console(as expected).

Adding the content of my ~/.zshrc

```<code>export JAVA_HOME=/Library/Java/JavaVirtualMachines/amazon-corretto-8.jdk/Contents/Home
#export JAVA11_HOME=/Library/Java/JavaVirtualMachines/amazon-corretto-11.jdk/Contents/Home
export PATH="$HOME/.jenv/bin:$PATH"
eval "$(jenv init -)"
#export JAVA14_HOME=$(/usr/libexec/java_home -v14)
#export RUNTIME_JAVA_HOME=$(/usr/libexec/java_home -v11)
export PATH=$JAVA_HOME/bin:$PATH
#export PATH="/Users/java-dev/Library/Python/3.7/bin/:$PATH"
export PATH=/usr/local/bin:$PATH
export PATH=/usr/bin:$PATH
alias sr='source ~/.zshrc'
alias rt='cd /Users/java-dev/rt'
alias dev='cd /Users/java-dev/development'
alias code='cd /Users/java-dev/code'
</code>```

答:
The file name is changed in latest catalina OS . you need to create a file named .zprofile (same place where you have created .bash_profile file. This needs to be done because .bash_profile is now .zprofile) and place your export command over there.

If it already exists, please append your export command in the file like below.

export PATH=$your_path$:$PATH

export JAVA_HOME=$your_path$

export M2_HOME=$your_path$

check this macOS Catalina 10.15(beta) - Why is ~/.bash_profile not sourced by my shell?

Body:
I a using the latest MacOS catalina(10.15.4) and using .zshrc for my profile as latest version of mac deprecated the bash shell, This is the follow-up question of my previous unanswered question on not able to change the default java version to 1.8 using jenv.

When I was trying to debug more found my echo $JAVA_HOME always returns blank, despite having set it in following manner.

export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)

And

export JAVA_HOME=/Library/Java/JavaVirtualMachines/amazon-corretto-8.jdk/Contents/Home

Note i've sourced my .zshrc file after the change but still no luck, although when I set on the terminal then it print the proper value but its only on that console(as expected).

Adding the content of my ~/.zshrc

export JAVA_HOME=/Library/Java/JavaVirtualMachines/amazon-corretto-8.jdk/Contents/Home
#export JAVA11_HOME=/Library/Java/JavaVirtualMachines/amazon-corretto-11.jdk/Contents/Home
export PATH="$HOME/.jenv/bin:$PATH"
eval "$(jenv init -)"
#export JAVA14_HOME=$(/usr/libexec/java_home -v14)
#export RUNTIME_JAVA_HOME=$(/usr/libexec/java_home -v11)
export PATH=$JAVA_HOME/bin:$PATH
#export PATH="/Users/java-dev/Library/Python/3.7/bin/:$PATH"
export PATH=/usr/local/bin:$PATH
export PATH=/usr/bin:$PATH
alias sr='source ~/.zshrc'
alias rt='cd /Users/java-dev/rt'
alias dev='cd /Users/java-dev/development'
alias code='cd /Users/java-dev/code'


问:
The solution is executed with error 'out of bounds' on the line 25
Receiving an out of bounds error during compilation, tried alternate approaches still the same. it says error occurred on line 25 which is just a cin statement within bounds. where exactly am I going wrong. Clang, Debugger is generating this error.</p>

```<code>int main ()
{

  int n;

  cin >> n;

  int work[n];

  for (int j = 1; j <= n; j++)
    {
      cin >> work[j];
    }

    int i = -2, j = -1, k = 0, l = 0;

    int ch = 0, bi = 0, ba = 0;

    while (l < n)
    {
      ch = ch + work[i+3];
      l++;

      bi  = bi + work[j+3];
      l++;

      ba = ba + work[k+3];
      l++;

      i+=3;
      j+=3;
      k+=3;
    }

    if (ch > bi && ch > ba)
    cout << "chest" << endl;

    else if (bi > ch && bi > ba)
    cout << "biceps" << endl;

    else
    cout << "back" << endl;

  return 0;
}
</code>```

答:
This is wrong:

```<code>for (int j = 1; j <= n; j++)
    {
      cin >> work[j];
    }
</code>```

Array indexes are from 0 to size-1 (included). Change to:

```<code>for (int j = 0; j < n; j++)
    {
      cin >> work[j];
    }
</code>```

Body:
Receiving an out of bounds error during compilation, tried alternate approaches still the same. it says error occurred on line 25 which is just a cin statement within bounds. where exactly am I going wrong. Clang, Debugger is generating this error.

int main ()
{

  int n;

  cin >> n;

  int work[n];

  for (int j = 1; j <= n; j++)
    {
      cin >> work[j];
    }

    int i = -2, j = -1, k = 0, l = 0;

    int ch = 0, bi = 0, ba = 0;

    while (l < n)
    {
      ch = ch + work[i+3];
      l++;

      bi  = bi + work[j+3];
      l++;

      ba = ba + work[k+3];
      l++;

      i+=3;
      j+=3;
      k+=3;
    }

    if (ch > bi && ch > ba)
    cout << "chest" << endl;

    else if (bi > ch && bi > ba)
    cout << "biceps" << endl;

    else
    cout << "back" << endl;

  return 0;
}

Body:
This is wrong:

for (int j = 1; j <= n; j++)
    {
      cin >> work[j];
    }

Array indexes are from 0 to size-1 (included). Change to:

for (int j = 0; j < n; j++)
    {
      cin >> work[j];
    }


问:
How to identify the changed cell in office js api BindingDataChanged event?
When the data is changed in a binding in excel, the BindingDataChanged event if fired.

```<code>function addHandler() {
    Office.select("bindings#MyBinding").addHandlerAsync(
    Office.EventType.BindingDataChanged, dataChanged);
}
function dataChanged(eventArgs) {
    write('Bound data changed in binding: ' + eventArgs.binding.id);
}
</code>```

But the eventArgs do not have information about what part of the data is changed. Is there any way, we can track this information? We have bindings with large number of cells like 5000 rows * 15 columns or 90 rows * 350 columns. We are using office js api 1.2.

Update 1 Used the code provided by Michael Saunders below. Seeing some strange behavior.I have selected G9:H9 and pressed delete. But the header is always returning as Column1 and Column2 (Look at the toastr notification on top right). I was expecting Column7 and Column8. Is this the expected behavior? (The testing was done on Excel 2016 with a table binding and not on office 365. Will try it next)

答:
As far as I understand your question you want header name of corresponding clicked cell

object.onSelectionChanged.add(selectionChangedCallback)
from EventArgs you can get cell address (G9:h9 in your above case ).So just take reference from these value (like G1 or H1 ,this value depends on your logic if it is a table you can get help from table header range position) and get value of those.

object can be table or worksheet .

Body:
When the data is changed in a binding in excel, the BindingDataChanged event if fired.

function addHandler() {
    Office.select("bindings#MyBinding").addHandlerAsync(
    Office.EventType.BindingDataChanged, dataChanged);
}
function dataChanged(eventArgs) {
    write('Bound data changed in binding: ' + eventArgs.binding.id);
}

But the eventArgs do not have information about what part of the data is changed. Is there any way, we can track this information? We have bindings with large number of cells like 5000 rows * 15 columns or 90 rows * 350 columns. We are using office js api 1.2.

Update 1 Used the code provided by Michael Saunders below. Seeing some strange behavior.I have selected G9:H9 and pressed delete. But the header is always returning as Column1 and Column2 (Look at the toastr notification on top right). I was expecting Column7 and Column8. Is this the expected behavior? (The testing was done on Excel 2016 with a table binding and not on office 365. Will try it next)