问:
Citrus Framework - Cannot successfully build samples
I have been investigating the Citrus Framework and pulled down the samples project folder. The run instructions indicates what to do to build the code, start the Jetty server and run the various tests that are included. I have tried this and the build fails only after the second module. This was done on a Windows 10 box.

The simple maven command to do the build, start the Jetty server and run the integration tests is:

```<code>$ mvn clean install -Dembedded=true
</code>```

Below is an excerpt of the console log.

```<code>[ERROR] Tests run: 4, Failures: 4, Errors: 0, Skipped: 0, Time elapsed: 20.582 s <<< FAILURE! - in TestSuite
[ERROR] routeMessagesContentBased(com.consol.citrus.samples.bakery.RouteMessagesHttpIT)  Time elapsed: 4.259 s  <<< FAILURE!
com.consol.citrus.exceptions.TestCaseFailedException: I/O error on POST request for "http://localhost:18001/bakery/services/order": Connect to localhost:18001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to localhost:18001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
        at com.consol.citrus.samples.bakery.RouteMessagesHttpIT.routeMessagesContentBased(RouteMessagesHttpIT.java:55)
Caused by: org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://localhost:18001/bakery/services/order": Connect to localhost:18001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to localhost:18001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
        at com.consol.citrus.samples.bakery.RouteMessagesHttpIT.routeMessagesContentBased(RouteMessagesHttpIT.java:55)
Caused by: org.apache.http.conn.HttpHostConnectException: Connect to localhost:18001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect

        at com.consol.citrus.samples.bakery.RouteMessagesHttpIT.routeMessagesContentBased(RouteMessagesHttpIT.java:55)
Caused by: java.net.ConnectException: Connection refused: connect
        at com.consol.citrus.samples.bakery.RouteMessagesHttpIT.routeMessagesContentBased(RouteMessagesHttpIT.java:55)

[ERROR] routeUnknownOrderType(com.consol.citrus.samples.bakery.RouteMessagesHttpIT)  Time elapsed: 2.023 s  <<< FAILURE!
com.consol.citrus.exceptions.TestCaseFailedException: I/O error on POST request for "http://localhost:18001/bakery/services/order": Connect to localhost:18001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to localhost:18001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
        at com.consol.citrus.samples.bakery.RouteMessagesHttpIT.routeUnknownOrderType(RouteMessagesHttpIT.java:109)
Caused by: org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://localhost:18001/bakery/services/order": Connect to localhost:18001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to localhost:18001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
        at com.consol.citrus.samples.bakery.RouteMessagesHttpIT.routeUnknownOrderType(RouteMessagesHttpIT.java:109)
Caused by: org.apache.http.conn.HttpHostConnectException: Connect to localhost:18001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect

        at com.consol.citrus.samples.bakery.RouteMessagesHttpIT.routeUnknownOrderType(RouteMessagesHttpIT.java:109)
Caused by: java.net.ConnectException: Connection refused: connect
        at com.consol.citrus.samples.bakery.RouteMessagesHttpIT.routeUnknownOrderType(RouteMessagesHttpIT.java:109)

[ERROR] routeMessagesContentBased(com.consol.citrus.samples.bakery.RouteMessagesJmsIT)  Time elapsed: 5.274 s  <<< FAILURE!
com.consol.citrus.exceptions.TestCaseFailedException: Action timed out while receiving JMS message on 'factory.chocolate.inbound'
        at com.consol.citrus.samples.bakery.RouteMessagesJmsIT.routeMessagesContentBased(RouteMessagesJmsIT.java:55)
Caused by: com.consol.citrus.exceptions.ActionTimeoutException: Action timed out while receiving JMS message on 'factory.chocolate.inbound'
        at com.consol.citrus.samples.bakery.RouteMessagesJmsIT.routeMessagesContentBased(RouteMessagesJmsIT.java:55)

[ERROR] routeUnknownOrderType(com.consol.citrus.samples.bakery.RouteMessagesJmsIT)  Time elapsed: 5.026 s  <<< FAILURE!
com.consol.citrus.exceptions.TestCaseFailedException: Action timed out while receiving JMS message on 'factory.unknown.inbound'
        at com.consol.citrus.samples.bakery.RouteMessagesJmsIT.routeUnknownOrderType(RouteMessagesJmsIT.java:82)
Caused by: com.consol.citrus.exceptions.ActionTimeoutException: Action timed out while receiving JMS message on 'factory.unknown.inbound'
        at com.consol.citrus.samples.bakery.RouteMessagesJmsIT.routeUnknownOrderType(RouteMessagesJmsIT.java:82)

08:39:04,888 INFO  icApplicationContext| Closing org.springframework.context.support.GenericApplicationContext@31190526: startup date [Mon Feb 03 08:38:46 EST 2020]; root of context hierarchy
08:39:04,888 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'lifecycleProcessor'
08:39:04,889 DEBUG tListableBeanFactory| Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@5939a379: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,citrusSpringConfig,com.consol.citrus.functions.FunctionConfig,functionRegistry,environmentPropertyFunction,citrusFunctionLibrary,com.consol.citrus.validation.matcher.ValidationMatcherConfig,matchesPath,hamcrestValidationMatcher,validationMatcherRegistry,xmlValidationMatcher,citrusValidationMatcherLibrary,com.consol.citrus.validation.MessageValidatorConfig,defaultXmlMessageValidator,defaultMessageHeaderValidator,defaultXpathMessageValidator,defaultJsonMessageValidator,defaultJsonPathMessageValidator,defaultPlaintextMessageValidator,defaultBinaryMessageValidator,defaultBinaryBase64MessageValidator,defaultGzipBinaryBase64MessageValidator,defaultXhtmlMessageValidator,defaultXhtmlXpathMessageValidator,defaultGroovyXmlMessageValidator,defaultGroovyJsonMessageValidator,defaultGroovyTextMessageValidator,citrusMessageValidatorRegistry,testContextFactory,endpointFactory,referenceResolver,globalMessageConstructionInterceptors,loggingReporter,htmlReporter,junitReporter,testListeners,testActionListeners,testSuiteListeners,messageListeners,failureStackTestListener,com.consol.citrus.samples.bakery.CitrusEndpointConfig,globalVariables,messageTracingTestListener,connectionFactory,bakeryClient,bakeryOrderEndpoint,workerCaramelEndpoint,workerBlueberryEndpoint,workerChocolateEndpoint]; root of factory hierarchy
08:39:04,889 DEBUG tListableBeanFactory| Retrieved dependent beans for bean 'workerChocolateEndpoint': [com.consol.citrus.samples.bakery.RouteMessagesHttpIT, com.consol.citrus.samples.bakery.RouteMessagesJmsIT]
08:39:04,890 DEBUG isposableBeanAdapter| Invoking destroy() on bean with name 'workerChocolateEndpoint'
08:39:04,890 DEBUG isposableBeanAdapter| Invoking destroy() on bean with name 'workerBlueberryEndpoint'
08:39:04,890 DEBUG isposableBeanAdapter| Invoking destroy() on bean with name 'workerCaramelEndpoint'
08:39:04,890 DEBUG isposableBeanAdapter| Invoking destroy() on bean with name 'bakeryOrderEndpoint'
[INFO]
[INFO] Results:
[INFO]
[ERROR] Failures:
[ERROR]   RouteMessagesHttpIT>TestNGCitrusTest.run:56->TestNGCitrusTest.run:110->TestNGCitrusTest.invokeTestMethod:131 ╗ TestCaseFailed
[ERROR]   RouteMessagesHttpIT>TestNGCitrusTest.run:56->TestNGCitrusTest.run:110->TestNGCitrusTest.invokeTestMethod:131 ╗ TestCaseFailed
[ERROR]   RouteMessagesJmsIT>TestNGCitrusTest.run:56->TestNGCitrusTest.run:110->TestNGCitrusTest.invokeTestMethod:131 ╗ TestCaseFailed
[ERROR]   RouteMessagesJmsIT>TestNGCitrusTest.run:56->TestNGCitrusTest.run:110->TestNGCitrusTest.invokeTestMethod:131 ╗ TestCaseFailed
[INFO]
[ERROR] Tests run: 4, Failures: 4, Errors: 0, Skipped: 0
[INFO]
[INFO]
[INFO] --- maven-failsafe-plugin:2.20.1:verify (integration-tests) @ citrus-bakery-web ---
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] Citrus Samples:: Bakery ............................ SUCCESS [  0.330 s]
[INFO] Citrus Samples:: Bakery Web ........................ FAILURE [ 29.752 s]
[INFO] Citrus Samples:: Bakery Worker ..................... SKIPPED
[INFO] Citrus Samples:: Bakery Report ..................... SKIPPED
[INFO] Citrus Samples:: Bakery Integration ................ SKIPPED
[INFO] Citrus Samples:: Java EE ........................... SKIPPED
[INFO] Citrus Samples:: Flightbooking ..................... SKIPPED
[INFO] Citrus Samples:: Greeting: Java .................... SKIPPED
[INFO] Citrus Samples:: Bookstore ......................... SKIPPED
[INFO] Citrus Samples:: Incident .......................... SKIPPED
[INFO] Citrus Samples:: Demos ............................. SKIPPED
[INFO] Citrus Samples:: Todo App .......................... SKIPPED
[INFO] Citrus Samples:: Apache Camel Context .............. SKIPPED
[INFO] Citrus Samples:: Behaviors ......................... SKIPPED
[INFO] Citrus Samples:: Dictionaries ...................... SKIPPED
[INFO] Citrus Samples:: Message Store ..................... SKIPPED
[INFO] Citrus Samples:: Docker ............................ SKIPPED
[INFO] Citrus Samples:: Kubernetes ........................ SKIPPED
[INFO] Citrus Samples:: Cucumber BDD ...................... SKIPPED
[INFO] Citrus Samples:: Cucumber BDD Spring ............... SKIPPED
[INFO] Citrus Samples:: Cucumber BDD Spring 2 ............. SKIPPED
[INFO] Citrus Samples:: Cucumber Samples .................. SKIPPED
[INFO] Citrus Samples:: Annotation Config ................. SKIPPED
[INFO] Citrus Samples:: Java Config ....................... SKIPPED
[INFO] Citrus Samples:: Mail .............................. SKIPPED
[INFO] Citrus Samples:: Selenium .......................... SKIPPED
[INFO] Citrus Samples:: FTP ............................... SKIPPED
[INFO] Citrus Samples:: SFTP .............................. SKIPPED
[INFO] Citrus Samples:: SCP ............................... SKIPPED
[INFO] Citrus Samples:: FTP Samples ....................... SKIPPED
[INFO] Citrus Samples:: TestNG ............................ SKIPPED
[INFO] Citrus Samples:: Dataprovider ...................... SKIPPED
[INFO] Citrus Samples:: TestNG Samples .................... SKIPPED
[INFO] Citrus Samples:: JUnit ............................. SKIPPED
[INFO] Citrus Samples:: JUnit5 ............................ SKIPPED
[INFO] Citrus Samples:: JUnit Samples ..................... SKIPPED
[INFO] Citrus Samples:: Swagger API ....................... SKIPPED
[INFO] Citrus Samples:: Http .............................. SKIPPED
[INFO] Citrus Samples:: Http Loadtest ..................... SKIPPED
[INFO] Citrus Samples:: Http Static Response .............. SKIPPED
[INFO] Citrus Samples:: Http Query Parameter .............. SKIPPED
[INFO] Citrus Samples:: Http Form Data .................... SKIPPED
[INFO] Citrus Samples:: Http Basic Auth ................... SKIPPED
[INFO] Citrus Samples:: Https ............................. SKIPPED
[INFO] Citrus Samples:: Http Samples ...................... SKIPPED
[INFO] Citrus Samples:: RMI ............................... SKIPPED
[INFO] Citrus Samples:: Reporting ......................... SKIPPED
[INFO] Citrus Samples:: XHTML ............................. SKIPPED
[INFO] Citrus Samples:: XML ............................... SKIPPED
[INFO] Citrus Samples:: OXM ............................... SKIPPED
[INFO] Citrus Samples:: XML Samples ....................... SKIPPED
[INFO] Citrus Samples:: JSON .............................. SKIPPED
[INFO] Citrus Samples:: Databind .......................... SKIPPED
[INFO] Citrus Samples:: Json Samples ...................... SKIPPED
[INFO] Citrus Samples:: Hamcrest .......................... SKIPPED
[INFO] Citrus Samples:: JMS ............................... SKIPPED
[INFO] Citrus Samples:: Kafka ............................. SKIPPED
[INFO] Citrus Samples:: Dynamic Endpoints ................. SKIPPED
[INFO] Citrus Samples:: Binary ............................ SKIPPED
[INFO] Citrus Samples:: WSDL .............................. SKIPPED
[INFO] Citrus Samples:: SOAP .............................. SKIPPED
[INFO] Citrus Samples:: SOAP MTOM ......................... SKIPPED
[INFO] Citrus Samples:: SOAP Attachments .................. SKIPPED
[INFO] Citrus Samples:: SOAP WsSecurity ................... SKIPPED
[INFO] Citrus Samples:: SOAP WsAddressing ................. SKIPPED
[INFO] Citrus Samples:: SOAP SSL .......................... SKIPPED
[INFO] Citrus Samples:: SOAP Static Response .............. SKIPPED
[INFO] Citrus Samples:: SOAP Samples ...................... SKIPPED
[INFO] Citrus Samples:: SQL ............................... SKIPPED
[INFO] Citrus Samples:: JDBC .............................. SKIPPED
[INFO] Citrus Samples:: JDBC Transactions ................. SKIPPED
[INFO] Citrus Samples:: JDBC Callable Statements .......... SKIPPED
[INFO] Citrus Samples:: DB Samples ........................ SKIPPED
[INFO] Citrus Samples:: Test JAR .......................... SKIPPED
[INFO] Citrus Samples:: Test WAR .......................... SKIPPED
[INFO] Citrus Samples:: Remote Samples .................... SKIPPED
[INFO] Citrus Samples:: Parent ............................ SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 30.744 s
[INFO] Finished at: 2020-02-03T08:39:05-05:00
[INFO] Final Memory: 38M/386M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-failsafe-plugin:2.20.1:verify (integration-tests) on project citrus-bakery-web: There are test failures.
[ERROR]
[ERROR] Please refer to C:\Users\JO24447\workspace\citrus\citrus-samples\demo\sample-bakery\web\target\failsafe-reports for the individual test results.
[ERROR] Please refer to dump files (if any exist) [date]-jvmRun[N].dump, [date].dumpstream and [date]-jvmRun[N].dumpstream.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR]   mvn <goals> -rf :citrus-bakery-web
</code>```

When I click on the Samples menu button on the Citrus web site, it takes me to a page with lot of sample test scenarios that seem to all be testing a "to-do" application.

There is obviously a lot in the project I pulled down. It's not clear whether everything in it is related to the to-do app, or if there are other exmaple applications with their own sets of tests. E.g. the "bakery".

Should I build just small portions of this project? Is there an expectation that I need to have other apps/utilities installed and running prior to running the maven build?

UPDATE:

After some trial and error, I finally dropped down into the samples-http/sample-http subdirectory (this is the test scenario I'm initially interested in) and ran the following command:

```<code>mvn clean install -Dsystem.under.test.mode=embedded
</code>```

This built the code and ran the integration test successfully. The originally specified maven command (mvn clean install -Dembedded=true) also worked. Are these command variations the same?

It would be good to know what the requirements and expectations there are to be able to successfully build and run/test everything in the samples project.

答:
I successfully have run the tests with

```<code>mvn clean install -Dsystem.under.test.mode=embedded -fae
</code>```

The -fae flag is not mandatory but it lets you continue with the build and only fail at the end. So you see what samples are working for you and which of them do not.

I am running this on MacOS but I think it is a documentation issue as -Dembedded=true is not valid anymore. So you should be using -Dsystem.under.test.mode=embedded. There was some refactoring on how to run the samples so it also may have issues, too. Please open issues on the samples github repository if anything does not work as expected.Issues regarding the website might go to this github repository

Body:
I have been investigating the Citrus Framework and pulled down the samples project folder. The run instructions indicates what to do to build the code, start the Jetty server and run the various tests that are included. I have tried this and the build fails only after the second module. This was done on a Windows 10 box.

The simple maven command to do the build, start the Jetty server and run the integration tests is:

$ mvn clean install -Dembedded=true

Below is an excerpt of the console log.

[ERROR] Tests run: 4, Failures: 4, Errors: 0, Skipped: 0, Time elapsed: 20.582 s <<< FAILURE! - in TestSuite
[ERROR] routeMessagesContentBased(com.consol.citrus.samples.bakery.RouteMessagesHttpIT)  Time elapsed: 4.259 s  <<< FAILURE!
com.consol.citrus.exceptions.TestCaseFailedException: I/O error on POST request for "http://localhost:18001/bakery/services/order": Connect to localhost:18001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to localhost:18001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
        at com.consol.citrus.samples.bakery.RouteMessagesHttpIT.routeMessagesContentBased(RouteMessagesHttpIT.java:55)
Caused by: org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://localhost:18001/bakery/services/order": Connect to localhost:18001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to localhost:18001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
        at com.consol.citrus.samples.bakery.RouteMessagesHttpIT.routeMessagesContentBased(RouteMessagesHttpIT.java:55)
Caused by: org.apache.http.conn.HttpHostConnectException: Connect to localhost:18001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect

        at com.consol.citrus.samples.bakery.RouteMessagesHttpIT.routeMessagesContentBased(RouteMessagesHttpIT.java:55)
Caused by: java.net.ConnectException: Connection refused: connect
        at com.consol.citrus.samples.bakery.RouteMessagesHttpIT.routeMessagesContentBased(RouteMessagesHttpIT.java:55)

[ERROR] routeUnknownOrderType(com.consol.citrus.samples.bakery.RouteMessagesHttpIT)  Time elapsed: 2.023 s  <<< FAILURE!
com.consol.citrus.exceptions.TestCaseFailedException: I/O error on POST request for "http://localhost:18001/bakery/services/order": Connect to localhost:18001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to localhost:18001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
        at com.consol.citrus.samples.bakery.RouteMessagesHttpIT.routeUnknownOrderType(RouteMessagesHttpIT.java:109)
Caused by: org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://localhost:18001/bakery/services/order": Connect to localhost:18001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to localhost:18001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
        at com.consol.citrus.samples.bakery.RouteMessagesHttpIT.routeUnknownOrderType(RouteMessagesHttpIT.java:109)
Caused by: org.apache.http.conn.HttpHostConnectException: Connect to localhost:18001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect

        at com.consol.citrus.samples.bakery.RouteMessagesHttpIT.routeUnknownOrderType(RouteMessagesHttpIT.java:109)
Caused by: java.net.ConnectException: Connection refused: connect
        at com.consol.citrus.samples.bakery.RouteMessagesHttpIT.routeUnknownOrderType(RouteMessagesHttpIT.java:109)

[ERROR] routeMessagesContentBased(com.consol.citrus.samples.bakery.RouteMessagesJmsIT)  Time elapsed: 5.274 s  <<< FAILURE!
com.consol.citrus.exceptions.TestCaseFailedException: Action timed out while receiving JMS message on 'factory.chocolate.inbound'
        at com.consol.citrus.samples.bakery.RouteMessagesJmsIT.routeMessagesContentBased(RouteMessagesJmsIT.java:55)
Caused by: com.consol.citrus.exceptions.ActionTimeoutException: Action timed out while receiving JMS message on 'factory.chocolate.inbound'
        at com.consol.citrus.samples.bakery.RouteMessagesJmsIT.routeMessagesContentBased(RouteMessagesJmsIT.java:55)

[ERROR] routeUnknownOrderType(com.consol.citrus.samples.bakery.RouteMessagesJmsIT)  Time elapsed: 5.026 s  <<< FAILURE!
com.consol.citrus.exceptions.TestCaseFailedException: Action timed out while receiving JMS message on 'factory.unknown.inbound'
        at com.consol.citrus.samples.bakery.RouteMessagesJmsIT.routeUnknownOrderType(RouteMessagesJmsIT.java:82)
Caused by: com.consol.citrus.exceptions.ActionTimeoutException: Action timed out while receiving JMS message on 'factory.unknown.inbound'
        at com.consol.citrus.samples.bakery.RouteMessagesJmsIT.routeUnknownOrderType(RouteMessagesJmsIT.java:82)

08:39:04,888 INFO  icApplicationContext| Closing org.springframework.context.support.GenericApplicationContext@31190526: startup date [Mon Feb 03 08:38:46 EST 2020]; root of context hierarchy
08:39:04,888 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'lifecycleProcessor'
08:39:04,889 DEBUG tListableBeanFactory| Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@5939a379: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,citrusSpringConfig,com.consol.citrus.functions.FunctionConfig,functionRegistry,environmentPropertyFunction,citrusFunctionLibrary,com.consol.citrus.validation.matcher.ValidationMatcherConfig,matchesPath,hamcrestValidationMatcher,validationMatcherRegistry,xmlValidationMatcher,citrusValidationMatcherLibrary,com.consol.citrus.validation.MessageValidatorConfig,defaultXmlMessageValidator,defaultMessageHeaderValidator,defaultXpathMessageValidator,defaultJsonMessageValidator,defaultJsonPathMessageValidator,defaultPlaintextMessageValidator,defaultBinaryMessageValidator,defaultBinaryBase64MessageValidator,defaultGzipBinaryBase64MessageValidator,defaultXhtmlMessageValidator,defaultXhtmlXpathMessageValidator,defaultGroovyXmlMessageValidator,defaultGroovyJsonMessageValidator,defaultGroovyTextMessageValidator,citrusMessageValidatorRegistry,testContextFactory,endpointFactory,referenceResolver,globalMessageConstructionInterceptors,loggingReporter,htmlReporter,junitReporter,testListeners,testActionListeners,testSuiteListeners,messageListeners,failureStackTestListener,com.consol.citrus.samples.bakery.CitrusEndpointConfig,globalVariables,messageTracingTestListener,connectionFactory,bakeryClient,bakeryOrderEndpoint,workerCaramelEndpoint,workerBlueberryEndpoint,workerChocolateEndpoint]; root of factory hierarchy
08:39:04,889 DEBUG tListableBeanFactory| Retrieved dependent beans for bean 'workerChocolateEndpoint': [com.consol.citrus.samples.bakery.RouteMessagesHttpIT, com.consol.citrus.samples.bakery.RouteMessagesJmsIT]
08:39:04,890 DEBUG isposableBeanAdapter| Invoking destroy() on bean with name 'workerChocolateEndpoint'
08:39:04,890 DEBUG isposableBeanAdapter| Invoking destroy() on bean with name 'workerBlueberryEndpoint'
08:39:04,890 DEBUG isposableBeanAdapter| Invoking destroy() on bean with name 'workerCaramelEndpoint'
08:39:04,890 DEBUG isposableBeanAdapter| Invoking destroy() on bean with name 'bakeryOrderEndpoint'
[INFO]
[INFO] Results:
[INFO]
[ERROR] Failures:
[ERROR]   RouteMessagesHttpIT>TestNGCitrusTest.run:56->TestNGCitrusTest.run:110->TestNGCitrusTest.invokeTestMethod:131 ╗ TestCaseFailed
[ERROR]   RouteMessagesHttpIT>TestNGCitrusTest.run:56->TestNGCitrusTest.run:110->TestNGCitrusTest.invokeTestMethod:131 ╗ TestCaseFailed
[ERROR]   RouteMessagesJmsIT>TestNGCitrusTest.run:56->TestNGCitrusTest.run:110->TestNGCitrusTest.invokeTestMethod:131 ╗ TestCaseFailed
[ERROR]   RouteMessagesJmsIT>TestNGCitrusTest.run:56->TestNGCitrusTest.run:110->TestNGCitrusTest.invokeTestMethod:131 ╗ TestCaseFailed
[INFO]
[ERROR] Tests run: 4, Failures: 4, Errors: 0, Skipped: 0
[INFO]
[INFO]
[INFO] --- maven-failsafe-plugin:2.20.1:verify (integration-tests) @ citrus-bakery-web ---
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] Citrus Samples:: Bakery ............................ SUCCESS [  0.330 s]
[INFO] Citrus Samples:: Bakery Web ........................ FAILURE [ 29.752 s]
[INFO] Citrus Samples:: Bakery Worker ..................... SKIPPED
[INFO] Citrus Samples:: Bakery Report ..................... SKIPPED
[INFO] Citrus Samples:: Bakery Integration ................ SKIPPED
[INFO] Citrus Samples:: Java EE ........................... SKIPPED
[INFO] Citrus Samples:: Flightbooking ..................... SKIPPED
[INFO] Citrus Samples:: Greeting: Java .................... SKIPPED
[INFO] Citrus Samples:: Bookstore ......................... SKIPPED
[INFO] Citrus Samples:: Incident .......................... SKIPPED
[INFO] Citrus Samples:: Demos ............................. SKIPPED
[INFO] Citrus Samples:: Todo App .......................... SKIPPED
[INFO] Citrus Samples:: Apache Camel Context .............. SKIPPED
[INFO] Citrus Samples:: Behaviors ......................... SKIPPED
[INFO] Citrus Samples:: Dictionaries ...................... SKIPPED
[INFO] Citrus Samples:: Message Store ..................... SKIPPED
[INFO] Citrus Samples:: Docker ............................ SKIPPED
[INFO] Citrus Samples:: Kubernetes ........................ SKIPPED
[INFO] Citrus Samples:: Cucumber BDD ...................... SKIPPED
[INFO] Citrus Samples:: Cucumber BDD Spring ............... SKIPPED
[INFO] Citrus Samples:: Cucumber BDD Spring 2 ............. SKIPPED
[INFO] Citrus Samples:: Cucumber Samples .................. SKIPPED
[INFO] Citrus Samples:: Annotation Config ................. SKIPPED
[INFO] Citrus Samples:: Java Config ....................... SKIPPED
[INFO] Citrus Samples:: Mail .............................. SKIPPED
[INFO] Citrus Samples:: Selenium .......................... SKIPPED
[INFO] Citrus Samples:: FTP ............................... SKIPPED
[INFO] Citrus Samples:: SFTP .............................. SKIPPED
[INFO] Citrus Samples:: SCP ............................... SKIPPED
[INFO] Citrus Samples:: FTP Samples ....................... SKIPPED
[INFO] Citrus Samples:: TestNG ............................ SKIPPED
[INFO] Citrus Samples:: Dataprovider ...................... SKIPPED
[INFO] Citrus Samples:: TestNG Samples .................... SKIPPED
[INFO] Citrus Samples:: JUnit ............................. SKIPPED
[INFO] Citrus Samples:: JUnit5 ............................ SKIPPED
[INFO] Citrus Samples:: JUnit Samples ..................... SKIPPED
[INFO] Citrus Samples:: Swagger API ....................... SKIPPED
[INFO] Citrus Samples:: Http .............................. SKIPPED
[INFO] Citrus Samples:: Http Loadtest ..................... SKIPPED
[INFO] Citrus Samples:: Http Static Response .............. SKIPPED
[INFO] Citrus Samples:: Http Query Parameter .............. SKIPPED
[INFO] Citrus Samples:: Http Form Data .................... SKIPPED
[INFO] Citrus Samples:: Http Basic Auth ................... SKIPPED
[INFO] Citrus Samples:: Https ............................. SKIPPED
[INFO] Citrus Samples:: Http Samples ...................... SKIPPED
[INFO] Citrus Samples:: RMI ............................... SKIPPED
[INFO] Citrus Samples:: Reporting ......................... SKIPPED
[INFO] Citrus Samples:: XHTML ............................. SKIPPED
[INFO] Citrus Samples:: XML ............................... SKIPPED
[INFO] Citrus Samples:: OXM ............................... SKIPPED
[INFO] Citrus Samples:: XML Samples ....................... SKIPPED
[INFO] Citrus Samples:: JSON .............................. SKIPPED
[INFO] Citrus Samples:: Databind .......................... SKIPPED
[INFO] Citrus Samples:: Json Samples ...................... SKIPPED
[INFO] Citrus Samples:: Hamcrest .......................... SKIPPED
[INFO] Citrus Samples:: JMS ............................... SKIPPED
[INFO] Citrus Samples:: Kafka ............................. SKIPPED
[INFO] Citrus Samples:: Dynamic Endpoints ................. SKIPPED
[INFO] Citrus Samples:: Binary ............................ SKIPPED
[INFO] Citrus Samples:: WSDL .............................. SKIPPED
[INFO] Citrus Samples:: SOAP .............................. SKIPPED
[INFO] Citrus Samples:: SOAP MTOM ......................... SKIPPED
[INFO] Citrus Samples:: SOAP Attachments .................. SKIPPED
[INFO] Citrus Samples:: SOAP WsSecurity ................... SKIPPED
[INFO] Citrus Samples:: SOAP WsAddressing ................. SKIPPED
[INFO] Citrus Samples:: SOAP SSL .......................... SKIPPED
[INFO] Citrus Samples:: SOAP Static Response .............. SKIPPED
[INFO] Citrus Samples:: SOAP Samples ...................... SKIPPED
[INFO] Citrus Samples:: SQL ............................... SKIPPED
[INFO] Citrus Samples:: JDBC .............................. SKIPPED
[INFO] Citrus Samples:: JDBC Transactions ................. SKIPPED
[INFO] Citrus Samples:: JDBC Callable Statements .......... SKIPPED
[INFO] Citrus Samples:: DB Samples ........................ SKIPPED
[INFO] Citrus Samples:: Test JAR .......................... SKIPPED
[INFO] Citrus Samples:: Test WAR .......................... SKIPPED
[INFO] Citrus Samples:: Remote Samples .................... SKIPPED
[INFO] Citrus Samples:: Parent ............................ SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 30.744 s
[INFO] Finished at: 2020-02-03T08:39:05-05:00
[INFO] Final Memory: 38M/386M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-failsafe-plugin:2.20.1:verify (integration-tests) on project citrus-bakery-web: There are test failures.
[ERROR]
[ERROR] Please refer to C:\Users\JO24447\workspace\citrus\citrus-samples\demo\sample-bakery\web\target\failsafe-reports for the individual test results.
[ERROR] Please refer to dump files (if any exist) [date]-jvmRun[N].dump, [date].dumpstream and [date]-jvmRun[N].dumpstream.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR]   mvn <goals> -rf :citrus-bakery-web

When I click on the Samples menu button on the Citrus web site, it takes me to a page with lot of sample test scenarios that seem to all be testing a "to-do" application.

There is obviously a lot in the project I pulled down. It's not clear whether everything in it is related to the to-do app, or if there are other exmaple applications with their own sets of tests. E.g. the "bakery".

Should I build just small portions of this project? Is there an expectation that I need to have other apps/utilities installed and running prior to running the maven build?

UPDATE:

After some trial and error, I finally dropped down into the samples-http/sample-http subdirectory (this is the test scenario I'm initially interested in) and ran the following command:

mvn clean install -Dsystem.under.test.mode=embedded

This built the code and ran the integration test successfully. The originally specified maven command (mvn clean install -Dembedded=true) also worked. Are these command variations the same?

It would be good to know what the requirements and expectations there are to be able to successfully build and run/test everything in the samples project.

Body:
I successfully have run the tests with

mvn clean install -Dsystem.under.test.mode=embedded -fae

The -fae flag is not mandatory but it lets you continue with the build and only fail at the end. So you see what samples are working for you and which of them do not.

I am running this on MacOS but I think it is a documentation issue as -Dembedded=true is not valid anymore. So you should be using -Dsystem.under.test.mode=embedded. There was some refactoring on how to run the samples so it also may have issues, too. Please open issues on the samples github repository if anything does not work as expected.Issues regarding the website might go to this github repository


来源: stackexchange

问:
In IE7 the first click on a grid causes an ExtJS Ext.grid.GridPanel to jump to the top of the page
I have a strange issue with an Array fed ExtJS gridPanel - in IE7 only, before the rowclick event is fired, when I click on a row, the page scrolls up 2-3 rows. On repeated clicks, the page scrolls up until the page is at the top of the page. Then only the rowclicks are passed through to my handler.
I only have two listeners registered on this grid:

```
        listeners: {
            rowclick:function(grid, rowIndex, e) {
             ... my handler
            },
            sortchange : function(grid, rowIndex, e){}
```

Do you have any ideas?

答: I experienced similar bug in Internet Explorer 7. For me zoom:1; position:relative; on surrounding container helped to force layout property.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a strange issue with an Array fed ExtJS gridPanel - in IE7 only, before the rowclick event is fired, when I click on a row, the page scrolls up 2-3 rows. On repeated clicks, the page scrolls up until the page is at the top of the page. Then only the rowclicks are passed through to my handler.
I only have two listeners registered on this grid:

        listeners: {
            rowclick:function(grid, rowIndex, e) {
             ... my handler
            },
            sortchange : function(grid, rowIndex, e){}

Do you have any ideas?


问:
Python Flask cannot set debug mode to true
I have set up my first Flask project with PyCharm and this is my app.py file:

```<code>from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'TEST'

if __name__ == '__main__':
    app.run(debug=True)
</code>```

I want to run my project in debug mode so that I do not have to restart the server every time something changes. I provide the app.run function with a debug=True parameter, but this does not seem to change the debug flag. The application does start however and I do see "TEST" on the page, but this is with the debug flag set to False.

I also tried to directly change my env variable with os.environ["FLASK_DEBUG"] = "True", but this did not affect the flag also.

Any advice?

答:
If you're using PyCharm, in Run/Debug config you can pass FLASK_DEBUG variable.
Try to set it to "1", not to "True".</p>

ContentLicense: CC BY-SA 4.0

Body:
I have set up my first Flask project with PyCharm and this is my app.py file:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'TEST'

if __name__ == '__main__':
    app.run(debug=True)

I want to run my project in debug mode so that I do not have to restart the server every time something changes. I provide the app.run function with a debug=True parameter, but this does not seem to change the debug flag. The application does start however and I do see "TEST" on the page, but this is with the debug flag set to False.

I also tried to directly change my env variable with os.environ["FLASK_DEBUG"] = "True", but this did not affect the flag also.

Any advice?


问:
How to store the result set of a stored procedure into a table, where the result set from SP is in json path?
I have a stored procedure, where i need to pass the variables with it.

The result set i get is in json path from the above sp.

Now, i want to open the json and stored the result into a table.

i want the syntax for the above?????

In sql server.

答:
Once you get the resultset of the stored procedure into a NVARCHAR(MAX) variable, you can use OPENJSON to get resultset. OPENJSON

```<code>DECLARE @json NVARCHAR(MAX)

EXEC @json = StoredProcedureReturningJSON @parameters...
</code>```

Now, you need to parse the JSON Result into a table structure. Microsoft documentation

See example below

```<code>DECLARE @json NVARCHAR(MAX)
SET @json =
  N'[
       {
         "Order": {
           "Number":"SO43659",
           "Date":"2011-05-31T00:00:00"
         },
         "AccountNumber":"AW29825",
         "Item": {
           "Price":2024.9940,
           "Quantity":1
         }
       },
       {
         "Order": {
           "Number":"SO43661",
           "Date":"2011-06-01T00:00:00"
         },
         "AccountNumber":"AW73565",
         "Item": {
           "Price":2024.9940,
           "Quantity":3
         }
      }
 ]'

SELECT * FROM
 OPENJSON ( @json )
WITH (
              Number   varchar(200) '$.Order.Number' ,
              Date     datetime     '$.Order.Date',
              Customer varchar(200) '$.AccountNumber',
              Quantity int          '$.Item.Quantity'
 )
</code>```

Body:
Once you get the resultset of the stored procedure into a NVARCHAR(MAX) variable, you can use OPENJSON to get resultset. OPENJSON

DECLARE @json NVARCHAR(MAX)

EXEC @json = StoredProcedureReturningJSON @parameters...

Now, you need to parse the JSON Result into a table structure. Microsoft documentation

See example below

DECLARE @json NVARCHAR(MAX)
SET @json =
  N'[
       {
         "Order": {
           "Number":"SO43659",
           "Date":"2011-05-31T00:00:00"
         },
         "AccountNumber":"AW29825",
         "Item": {
           "Price":2024.9940,
           "Quantity":1
         }
       },
       {
         "Order": {
           "Number":"SO43661",
           "Date":"2011-06-01T00:00:00"
         },
         "AccountNumber":"AW73565",
         "Item": {
           "Price":2024.9940,
           "Quantity":3
         }
      }
 ]'

SELECT * FROM
 OPENJSON ( @json )
WITH (
              Number   varchar(200) '$.Order.Number' ,
              Date     datetime     '$.Order.Date',
              Customer varchar(200) '$.AccountNumber',
              Quantity int          '$.Item.Quantity'
 )


问:
Xcode 11.3 does not have latest iOS version
Any reason the latest version of iOS is not available in the update version of Xcode ? 13.3 is missing and this allowed for me to upload a tested version of an application which was subsequently approved and then once released caused a crash.

答:
Downloaded the latest BETA release of Xcode and that has 13.3 as well as 13.4.
The current stable release of Xcode allows my code to build but it will not pass approval in the store because of the missing SDK. Just be aware of this should you have a similar issue. </p>


问:
How to determine which techniques and frameworks are supported by older browsers?
I need to develop a website for a particular device which only has Opera 11 as browser which cannot be updated. For this browser I need to develop a website. Nowadays there are modern frameworks and web techniques but some of them will obviously not be supported by Opera 11. I tried building a really simple Angular application but the corresponding typescript code was converted to Javascript code which turned out to have newer functions then are supported. Even JQuery is not yet supported in this specific browser.

I am wondering if it is a good idea to even use a modern framework like Angular, React or Vue for example. How to determine which techniques and frameworks are supported by older browsers?

Thank you in advance.

Let me know if this question should not be asked on Stackoverflow.

答:
I can see that Opera 11 worked in the year 2010 (16 December, 2010). It is a old browser.

The modern framework don't support old browser:

Angular: As you can see in official documentation https://angular.io/guide/browser-support and another documentation https://ej2.syncfusion.com/angular/documentation/browser/ Opera 50+ is supported but not previous versions.

React https://ej2.syncfusion.com/react/documentation/browser/

Vue: https://ej2.syncfusion.com/vue/documentation/browser/

Old framework Backbone.js (use jQuery) and AngularJs (use a special jQuery Lite) maybe they can work in Opera 11 but you need to try it and more information about you want develop in your website.

I recommend you use jQuery 1.12 or always native javascript. As you can see in official jQuery link: https://jquery.com/browser-support/ and the next image https://imgur.com/UzE6OAi.

You can find problems while developing, this is normal too.

I hope I helped you. Good luck and coding.


问:
Dropdown selected value is not showing after selection flask?
How to use HTML <select> dropdown list which is prepopulated from flask - render_template.

Here is the <select> dropdown list which is prepopulated from flask-jinja2.

```<code><div>
    <select class="test-default" id="testTime">
        {% for option in options %}
        <option value={{ option }}>{{ option }}</option>
        {% endfor %}
    </select>
</div>
</code>```

Script in test.html,

```<code>function fetch_test_data(){
    let test = $("#testTime").val();
    axios({
        method:"get",
        url:"/test",
        params: {
            test
        }
    }).then(function (response) {
        $(document.body).html(response.data)
    });
}
</code>```

And test.py file - with app route and options for dropdown.

```<code>@app.route('/test', methods=["GET"])
@login_required
def transactions_view():
    options = ["0","7","14","30"]

    return render_template("test.html", options=options)
</code>```

In the above case how to use selected attribute to display the selected value.

when a value is selected,
The correct value is returned to the flask and rendered back. But dropdown visualization/list shows the first value instead of selected value?

What I have tried:

I'm able to get dropdown select for defined dropdown.

defined-dropdown - for reference

```<code><div>
    <select class="test-default" id="testTime">
    <option value=0>today</option>
    <option value=7>week</option>
    <option value=14>fortnight</option>
    <option value=30>month</option>
    </select>
</div>

{{ time }}
</code>```

I'm able to use the above dropdown to this:

```<code><div>
    <select class="test-default" id="testTime">
    <option value=0 {% if time == 0 %} selected="selected" {% endif %}>today</option>
    <option value=7 {% if time == 7 %} selected="selected" {% endif %}>week</option>
    <option value=14 {% if time == 14 %} selected="selected" {% endif %}>fortnight</option>
    <option value=30 {% if time == 30 %} selected="selected" {% endif %}>month</option>
    </select>
</div>
</code>```

Where {{ time }} is returned from test.py

```<code>@app.route('/test', methods=["GET"])
@login_required
def transactions_view():
    time = (request.args.get("test"))
    return render_template("test.html", time=time)
</code>```

答:
axios obtains the response with the updated time parameter, however you will need to load the response, which is the updated HTML, to see the updated time.

You can update your fetch_test_data function as shown below to load the HTML response when the drop-down value changes.

```<code>function fetch_test_data(){
    let test = $("#testTime").val();
    axios({
        method:"get",
        url:"/test",
        params: {
            test
        }
    }).then(function (response) {
        $(document.body).html(response.data)
    });
}
</code>```

If using axios is not a requirement for you and you simply want to update the time, the following code will do just that without sending a request.

```<code><span id=timelabel>Default Time</span>

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>

    var label = document.getElementById('timelabel');
    var dropdown = document.getElementById('testTime');

    $("#testTime").on("change",function (evt) {
        label.textContent = dropdown.value;
    })
</script>
</code>```

Body:
How to use HTML <select> dropdown list which is prepopulated from flask - render_template.

Here is the <select> dropdown list which is prepopulated from flask-jinja2.

    <select class="test-default" id="testTime">
        {% for option in options %}
        <option value={{ option }}>{{ option }}</option>
        {% endfor %}
    </select>

Script in test.html,

function fetch_test_data(){
    let test = $("#testTime").val();
    axios({
        method:"get",
        url:"/test",
        params: {
            test
        }
    }).then(function (response) {
        $(document.body).html(response.data)
    });
}

And test.py file - with app route and options for dropdown.

@app.route('/test', methods=["GET"])
@login_required
def transactions_view():
    options = ["0","7","14","30"]

    return render_template("test.html", options=options)

In the above case how to use selected attribute to display the selected value.

when a value is selected,
The correct value is returned to the flask and rendered back. But dropdown visualization/list shows the first value instead of selected value?

What I have tried:

I'm able to get dropdown select for defined dropdown.

defined-dropdown - for reference

    <select class="test-default" id="testTime">
    <option value=0>today</option>
    <option value=7>week</option>
    <option value=14>fortnight</option>
    <option value=30>month</option>
    </select>

{{ time }}

I'm able to use the above dropdown to this:

    <select class="test-default" id="testTime">
    <option value=0 {% if time == 0 %} selected="selected" {% endif %}>today</option>
    <option value=7 {% if time == 7 %} selected="selected" {% endif %}>week</option>
    <option value=14 {% if time == 14 %} selected="selected" {% endif %}>fortnight</option>
    <option value=30 {% if time == 30 %} selected="selected" {% endif %}>month</option>
    </select>

Where {{ time }} is returned from test.py

@app.route('/test', methods=["GET"])
@login_required
def transactions_view():
    time = (request.args.get("test"))
    return render_template("test.html", time=time)

Body:
axios obtains the response with the updated time parameter, however you will need to load the response, which is the updated HTML, to see the updated time.

You can update your fetch_test_data function as shown below to load the HTML response when the drop-down value changes.

function fetch_test_data(){
    let test = $("#testTime").val();
    axios({
        method:"get",
        url:"/test",
        params: {
            test
        }
    }).then(function (response) {
        $(document.body).html(response.data)
    });
}

If using axios is not a requirement for you and you simply want to update the time, the following code will do just that without sending a request.

<span id=timelabel>Default Time</span>

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>

    var label = document.getElementById('timelabel');
    var dropdown = document.getElementById('testTime');

    $("#testTime").on("change",function (evt) {
        label.textContent = dropdown.value;
    })
</script>


问:
Removing obsolete files from server... Could not clean server of obsolete files: Content is not allowed in prolog

I am creating a project which is in jsp,servlet and tomcat v 8.0.upto
    last night it works fine but today it didn't work it gives error in    publishing tomcat server,please give me any suggestions.
    I used Eclipse Mars and Tomcat v8.0
    Actually I try to clean Tomcat Work Directory and also clean project("build/clean"), but still i get this error what should I do??

答:
Here you have to follow some steps:

go to the server and right-click on the server, click on delete

click to remove all servers from the list and press apply & save

add the server (tomcat or other)

start that server

You have to wait for sometime while it configure all data, finally click on restart server.


问:
Class conflict on different dependencies
I have the same class on 2 dependencies on my project. The libraries unit-api-1.0 (which is a dependency of org.geotools) and jscience-4.3.1 both have the class javax.measure.quantity.Length.

```<code> [INFO] +- org.geotools:gt-shapefile:jar:22.3:compile
 [INFO] |  +- org.geotools:gt-main:jar:22.3:compile
 [INFO] |  |  +- org.geotools:gt-referencing:jar:22.3:compile
 [INFO] |  |  |  +- org.ejml:ejml-ddense:jar:0.34:compile
 [INFO] |  |  |  |  \- org.ejml:ejml-core:jar:0.34:compile
 [INFO] |  |  |  +- commons-pool:commons-pool:jar:1.5.4:compile
 [INFO] |  |  |  +- org.geotools:gt-metadata:jar:22.3:compile
 [INFO] |  |  |  |  \- org.geotools:gt-opengis:jar:22.3:compile
 [INFO] |  |  |  |     \- systems.uom:systems-common-java8:jar:0.7.2:compile
 [INFO] |  |  |  |        +- tec.uom:uom-se:jar:1.0.8:compile
 [INFO] |  |  |  |        |  +- javax.measure:unit-api:jar:1.0:compile

 [INFO] \- org.jscience:jscience:jar:4.3.1:compile
 [INFO]    \- org.javolution:javolution:jar:5.2.3:compile
</code>```

When I try to use Length to parameterize Measure, I get the error:

```<code>[ERROR]   error: type argument Length is not within bounds of type-variable Q
[ERROR]   where Q is a type-variable:
[ERROR]     Q extends Quantity declared in class Measure
</code>```

Basically both interfaces Length extend the interface Quantity, as seen here:

https://www.javadoc.io/static/javax.measure/unit-api/1.0/javax/measure/quantity/Length.html
http://jscience.org/api/javax/measure/quantity/Length.html

But one of them extends Quantity, while the other extends Quantity. Somehow, they are not compatible with each other and the compiler is using the wrong one and giving me this error.

It there a way to somehow manage this situation?

答:
The GeoTools upgrade FAQ covers the changes needed to use Units after version 20.0.

You need the following dependency:

```<code><dependency>
   <groupId>systems.uom</groupId>
   <artifactId>systems-common-java8</artifactId>
   <version>0.7.2</version>
</dependency>
</code>```

and to make these changes:

Package names have changed, resulting in some common search and replaces when upgrading:

Search javax.measure.unit.Unit replace javax.measure.Unit

Search ConversionException replace IncommensurableException

This is a checked exception, in areas of the GeoTools library where this was found we now return an IllegalArgument exception.

Search converter == UnitConverter.IDENTITY replace converter.isIdentity()

Search javax.measure.unit.NonSI replace import si.uom.NonSI

Search javax.measure.unit.SI replace import si.uom.SI

Search SI.METER replace SI.METRE

Search javax.measure.converter.UnitConverter replace javax.measure.UnitConverter

Search javax.measure.unit.UnitFormat replace import javax.measure.format.UnitFormat

Search Unit.ONE replace AbstractUnit.ONE

Search Dimensionless.UNIT replace AbstractUnit.ONE

Search Unit.valueOf(unitString) replace Units.parseUnit(unitString)

Body:
I have the same class on 2 dependencies on my project. The libraries unit-api-1.0 (which is a dependency of org.geotools) and jscience-4.3.1 both have the class javax.measure.quantity.Length.

 [INFO] +- org.geotools:gt-shapefile:jar:22.3:compile
 [INFO] |  +- org.geotools:gt-main:jar:22.3:compile
 [INFO] |  |  +- org.geotools:gt-referencing:jar:22.3:compile
 [INFO] |  |  |  +- org.ejml:ejml-ddense:jar:0.34:compile
 [INFO] |  |  |  |  \- org.ejml:ejml-core:jar:0.34:compile
 [INFO] |  |  |  +- commons-pool:commons-pool:jar:1.5.4:compile
 [INFO] |  |  |  +- org.geotools:gt-metadata:jar:22.3:compile
 [INFO] |  |  |  |  \- org.geotools:gt-opengis:jar:22.3:compile
 [INFO] |  |  |  |     \- systems.uom:systems-common-java8:jar:0.7.2:compile
 [INFO] |  |  |  |        +- tec.uom:uom-se:jar:1.0.8:compile
 [INFO] |  |  |  |        |  +- javax.measure:unit-api:jar:1.0:compile

 [INFO] \- org.jscience:jscience:jar:4.3.1:compile
 [INFO]    \- org.javolution:javolution:jar:5.2.3:compile

When I try to use Length to parameterize Measure, I get the error:

[ERROR]   error: type argument Length is not within bounds of type-variable Q
[ERROR]   where Q is a type-variable:
[ERROR]     Q extends Quantity declared in class Measure

Basically both interfaces Length extend the interface Quantity, as seen here:

https://www.javadoc.io/static/javax.measure/unit-api/1.0/javax/measure/quantity/Length.html
http://jscience.org/api/javax/measure/quantity/Length.html

But one of them extends Quantity, while the other extends Quantity. Somehow, they are not compatible with each other and the compiler is using the wrong one and giving me this error.

It there a way to somehow manage this situation?

Body:
The GeoTools upgrade FAQ covers the changes needed to use Units after version 20.0.

You need the following dependency:

<dependency>
   <groupId>systems.uom</groupId>
   <artifactId>systems-common-java8</artifactId>
   <version>0.7.2</version>
</dependency>

and to make these changes:

Package names have changed, resulting in some common search and replaces when upgrading:

Search javax.measure.unit.Unit replace javax.measure.Unit

Search ConversionException replace IncommensurableException

This is a checked exception, in areas of the GeoTools library where this was found we now return an IllegalArgument exception.

Search converter == UnitConverter.IDENTITY replace converter.isIdentity()

Search javax.measure.unit.NonSI replace import si.uom.NonSI

Search javax.measure.unit.SI replace import si.uom.SI

Search SI.METER replace SI.METRE

Search javax.measure.converter.UnitConverter replace javax.measure.UnitConverter

Search javax.measure.unit.UnitFormat replace import javax.measure.format.UnitFormat

Search Unit.ONE replace AbstractUnit.ONE

Search Dimensionless.UNIT replace AbstractUnit.ONE

Search Unit.valueOf(unitString) replace Units.parseUnit(unitString)


问:
How to correctly replace line in text from a referenced line
I have written some code to take in users and assign tasks to them using a text file. The problem I am having is as the user inputs a task number to edit, but I don't know how to replace the line of text 12 lines above the task number that is input and this replaces the username. If there are two tasks in the text file I need to be able to use the task number line as a reference point and then replace the 12th line above that to a new username. So I basically need to replace the 12th line above the users input for every task.
I have written some code to just replace the name but its erasing my whole text file.

Example of text file: (tasks.txt)

User assigned to task:

jack

Task Title :

Fly

Task Description:

Fly to the moon

Task Due Date:

2020-02-20
  Date Assigned:

2020-02-18

Task Completed:

No

Task number:

1

The code of the effected block so far is:

```<code>with open('tasks.txt') as xxaz:
                 main2 = "Task number:" + "\n" + str(review)
                 aa = xxaz.read()
                 if main2 in aa:
                         print(str(main2) + "\n")
                         edit = input("Enter ""1"" to edit the user assigned to task, ""2"" to change the due date or ""3"" to change the completion status.\n")
                         if edit == "1":
                             new_name = input("Please enter a new user name")
                             lines = open('tasks.txt').read().splitlines()
                             lines[2] = new_name
                             open('tasks.txt','w').write
</code>```

答:
Is this what you are looking for?
Personally I will adopt pandas for this. But this is aligned to your approach.

Sample input file:

```<code>User assigned to task:
jack
Task Title :
Fly
Task Description:
Fly to the moon
Task Due Date:
2020-02-20
Date Assigned:
2020-02-18
Task Completed:
No
Task number:
1
User assigned to task:
jill
Task Title :
Walk
Task Description:
Walk to the moon
Task Due Date:
2020-03-20
Date Assigned:
2020-02-19
Task Completed:
No
Task number:
2
User assigned to task:
Brenda
Task Title :
Run
Task Description:
Run to the moon
Task Due Date:
2020-03-16
Date Assigned:
2020-04-19
Task Completed:
Yes
Task number:
3
</code>```

Code

```<code>#Take the user inputs
review = input('Enter the task number you want to modify: ')
field = input('''Enter:
1: To change the user assigned to task.
2: To change the due date.
3: To change the completion status
''')
value = input('Enter the value: ')

#Create a function which returns the field name as per the number provided by the user
def switchdic(num):
    dic = {'1':'User assigned to task:',
          '2':'Task Due Date:',
          '3':'Task Completed:'
          }
    return dic.get(num,'Invalid entry')

#code block to read and write the modified content to a new file
with open('user_task_data.txt') as fh,open('new_task_data.txt','w') as fw :
    lines = fh.readlines()
    for line in lines:
        #Skip the lines if they do not match the 'Task number:' as the previous line
        if (lines[lines.index(line)-1].strip() != "Task number:"):
            continue
        data = lines[lines.index(line)-13:lines.index(line)+1] #Assign the whole block of the given task number to variable data
        #Modify the values as per the given input and write to the new file
        if review == str(line.strip()):
            data[lines.index(switchdic(field)+"\n")+1] = value+"\n"
            fw.write(''.join(data))
        #Write the values as they are if they are not connected to the input task number
        else:
            fw.write(''.join(data))
print('The file is modified and new file is"new_task_data.txt" ')
</code>```

O/P

```<code>Enter the task number you want to modify: 3
Enter:
1: To change the user assigned to task.
2: To change the due date.
3: To change the completion status
3
Enter the value: No
The file is modified and new file is"new_task_data.txt"
</code>```

Body:
I have written some code to take in users and assign tasks to them using a text file. The problem I am having is as the user inputs a task number to edit, but I don't know how to replace the line of text 12 lines above the task number that is input and this replaces the username. If there are two tasks in the text file I need to be able to use the task number line as a reference point and then replace the 12th line above that to a new username. So I basically need to replace the 12th line above the users input for every task.
I have written some code to just replace the name but its erasing my whole text file.

Example of text file: (tasks.txt)

User assigned to task:

jack

Task Title :

Fly

Task Description:

Fly to the moon

Task Due Date:

2020-02-20
  Date Assigned:

2020-02-18

Task Completed:

No

Task number:

1

The code of the effected block so far is:

with open('tasks.txt') as xxaz:
                 main2 = "Task number:" + "\n" + str(review)
                 aa = xxaz.read()
                 if main2 in aa:
                         print(str(main2) + "\n")
                         edit = input("Enter ""1"" to edit the user assigned to task, ""2"" to change the due date or ""3"" to change the completion status.\n")
                         if edit == "1":
                             new_name = input("Please enter a new user name")
                             lines = open('tasks.txt').read().splitlines()
                             lines[2] = new_name
                             open('tasks.txt','w').write

Body:
Is this what you are looking for?
Personally I will adopt pandas for this. But this is aligned to your approach.

Sample input file:

User assigned to task:
jack
Task Title :
Fly
Task Description:
Fly to the moon
Task Due Date:
2020-02-20
Date Assigned:
2020-02-18
Task Completed:
No
Task number:
1
User assigned to task:
jill
Task Title :
Walk
Task Description:
Walk to the moon
Task Due Date:
2020-03-20
Date Assigned:
2020-02-19
Task Completed:
No
Task number:
2
User assigned to task:
Brenda
Task Title :
Run
Task Description:
Run to the moon
Task Due Date:
2020-03-16
Date Assigned:
2020-04-19
Task Completed:
Yes
Task number:
3

Code

#Take the user inputs
review = input('Enter the task number you want to modify: ')
field = input('''Enter:
1: To change the user assigned to task.
2: To change the due date.
3: To change the completion status
''')
value = input('Enter the value: ')

#Create a function which returns the field name as per the number provided by the user
def switchdic(num):
    dic = {'1':'User assigned to task:',
          '2':'Task Due Date:',
          '3':'Task Completed:'
          }
    return dic.get(num,'Invalid entry')

#code block to read and write the modified content to a new file
with open('user_task_data.txt') as fh,open('new_task_data.txt','w') as fw :
    lines = fh.readlines()
    for line in lines:
        #Skip the lines if they do not match the 'Task number:' as the previous line
        if (lines[lines.index(line)-1].strip() != "Task number:"):
            continue
        data = lines[lines.index(line)-13:lines.index(line)+1] #Assign the whole block of the given task number to variable data
        #Modify the values as per the given input and write to the new file
        if review == str(line.strip()):
            data[lines.index(switchdic(field)+"\n")+1] = value+"\n"
            fw.write(''.join(data))
        #Write the values as they are if they are not connected to the input task number
        else:
            fw.write(''.join(data))
print('The file is modified and new file is"new_task_data.txt" ')

O/P

Enter the task number you want to modify: 3
Enter:
1: To change the user assigned to task.
2: To change the due date.
3: To change the completion status
3
Enter the value: No
The file is modified and new file is"new_task_data.txt"


问:
Ocaml: How to "easy" map a list of records to a list of record.field?
Suppose that I have the following record:

```<code>type t = {a:int}
</code>```

In order to select the values of field a from a list I do the following:

```<code>let x = [{a=1};{a=2}]
let y = List.map (fun t -> t.a) x
</code>```

This is a bit "unclean" to me. As a comparison, In Haskell I would do the following:

```<code>data T = T { a :: Int}
x = [T {a = 1}, T {a = 2}]
y = map a x
</code>```

Is there a way to write something similar in Ocaml (maybe using external libraries)?
If not possible can someone explain why this limitation?

答:
Haskell implicitly creates selector functions for field names. OCaml doesn't do this. You could just manually define them whenever you create record types, and it would be equivalent to what the Haskell code does.</p>

```<code>type t = {a:int, b:int}
let a x = x.a
let b x = x.b
</code>```

Body:
Suppose that I have the following record:

type t = {a:int}

In order to select the values of field a from a list I do the following:

let x = [{a=1};{a=2}]
let y = List.map (fun t -> t.a) x

This is a bit "unclean" to me. As a comparison, In Haskell I would do the following:

data T = T { a :: Int}
x = [T {a = 1}, T {a = 2}]
y = map a x

Is there a way to write something similar in Ocaml (maybe using external libraries)?
If not possible can someone explain why this limitation?

Body:
Haskell implicitly creates selector functions for field names. OCaml doesn't do this. You could just manually define them whenever you create record types, and it would be equivalent to what the Haskell code does.

type t = {a:int, b:int}
let a x = x.a
let b x = x.b


问:
Covert Unix Timestamp to AOE
I am trying to convert a Unix timestamp to AoE time. I tried pytz but it seems that there is no AoE time in pytz. Is there any way that I can do it?</p>

```<code>tz = pytz.timezone('AOE')
timestamp_aoe = datetime.fromtimestamp(timestamp, tz).isoformat()
</code>```

答:
The AoE timezone (Anywhere on Earth; UTC-12) is not defined in the IANA tz database as far as I can tell. It's a time zone with static UTC offset of -12 h, you can also find it under "yankee" or "NATO" time, see military time zones.

Since the UTC offset never changed in the past (no DST etc.), you can simply define it by yourself:

```<code>from datetime import datetime, timezone, timedelta

timestamp = 1582013600.5 # example UNIX time
tz = timezone(timedelta(hours=-12), name='AOE')
dt_aoe = datetime.fromtimestamp(timestamp, tz)

print(repr(dt_aoe), dt_aoe.isoformat())
# datetime.datetime(2020, 2, 17, 20, 13, 20, 500000, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=43200), 'AOE'))
# 2020-02-17T20:13:20.500000-12:00
</code>```

Title: Covert Unix Timestamp to AOE

Body:
I am trying to convert a Unix timestamp to AoE time. I tried pytz but it seems that there is no AoE time in pytz. Is there any way that I can do it?

tz = pytz.timezone('AOE')
timestamp_aoe = datetime.fromtimestamp(timestamp, tz).isoformat()

Body:
The AoE timezone (Anywhere on Earth; UTC-12) is not defined in the IANA tz database as far as I can tell. It's a time zone with static UTC offset of -12 h, you can also find it under "yankee" or "NATO" time, see military time zones.

Since the UTC offset never changed in the past (no DST etc.), you can simply define it by yourself:

from datetime import datetime, timezone, timedelta

timestamp = 1582013600.5 # example UNIX time
tz = timezone(timedelta(hours=-12), name='AOE')
dt_aoe = datetime.fromtimestamp(timestamp, tz)

print(repr(dt_aoe), dt_aoe.isoformat())
# datetime.datetime(2020, 2, 17, 20, 13, 20, 500000, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=43200), 'AOE'))
# 2020-02-17T20:13:20.500000-12:00


问:
How Determine the LOWEST build target for a class you wish to use- VS 201
I would like to "use" the proximitydevice class in a simple app that I am testing. But I would also like to try and make that app as compatible with as many Windows versions as possible.

Currently my build target was .NET 2.0 but when trying to add the proximitydevice class, I have errors saying that not in namepsace.

How do I in visual studio 2019 (or elsewhere) match the lowest version of .net to the class I would like to use

AND where can I find the HIGHEST .net supported by windows versions.

Cheers,
Courtney.

答:
make that app as compatible with as many Windows versions as possible

For your requirement, you could create .NET Standard library and write the processing logic in it. .NET Standard  is a formal specification of .NET APIs that are intended to be available on all .NET implementations. However, ProximityDevice api is xbox device only, so it could not use in a desktop app. Please check this list available to desktop apps. Unfortunately, Windows.Networking.Proximity is not in the above list.

I now have a better understanding of .net CORE .NET UWP - frameworks and their dependencies. Although it would be great to see an interactive dependency chart if anyone knows of one.

For better understand, you could refer Immo's Making it easier to port to .NET Core Microsoft dev blog.


问:
Key Presses in Python
Is it possible to make it appear to a system that a key was pressed, for example I need to  make A key be pressed thousands of times, and it is much to time consuming to do it manually, I would like to write something to do it for me, and the only thing I know well enough is Python.

A better way to put it, I need to emulate a key press, I.E. not capture a key press.

More Info (as requested):
I am running windows XP and need to send the keys to another application.

答:
PyAutoGui also lets you press a button multiple times:</p>

```<code>pyautogui.press('tab', presses=5)   # press TAB five times in a row

pyautogui.press('A', presses=1000)   # press A a thousand times in a row
</code>```

OwnerDisplayName: Unkwntech

Title: Key Presses in Python

LastEditorDisplayName: Unkwntech

Body:
PyAutoGui also lets you press a button multiple times:

pyautogui.press('tab', presses=5)   # press TAB five times in a row

pyautogui.press('A', presses=1000)   # press A a thousand times in a row


问:
Create element, and add parent attributes to innerHTML
I'm creating a button that opens a modal for editing a document. I add attributes to the button and grab them when the button is clicked. I've added an icon to the innerHTML of my button, but that doesn't inherit the attributes (ie if the icon within the button is clicked, the modal doesn't have the data, while clicking outside the icon but still inside the button works fine).

```<code>const edit = document.createElement('button')
edit.innerHTML = '<svg class="review__icon"><use xlink:href="/img/icons.svg#icon-edit"></use></svg>'

edit.setAttribute('data-key', el._id)
edit.setAttribute('data-title', el.title)
...
</code>```

Now obviously I could just add the same attributes to the icon, but that seems daft. Is there some way to have the icon in my innerHTML inherit the data-attributes of its parent, the button?

答:
Rather than repeating the attributes again, or setting attributes at all, how about simply referencing the el in the listener?

```<code>const edit = document.createElement('button')
edit.innerHTML = '<svg class="review__icon"><use xlink:href="/img/icons.svg#icon-edit"></use></svg>'
edit.addEventListener('click', () => {
  console.log(el._id);
  console.log(el.title);
});
</code>```

(if this is inside a loop, make sure el is declared with const or let)

Body:
I'm creating a button that opens a modal for editing a document. I add attributes to the button and grab them when the button is clicked. I've added an icon to the innerHTML of my button, but that doesn't inherit the attributes (ie if the icon within the button is clicked, the modal doesn't have the data, while clicking outside the icon but still inside the button works fine).

const edit = document.createElement('button')
edit.innerHTML = '<svg class="review__icon"><use xlink:href="/img/icons.svg#icon-edit"></use></svg>'

edit.setAttribute('data-key', el._id)
edit.setAttribute('data-title', el.title)
...

Now obviously I could just add the same attributes to the icon, but that seems daft. Is there some way to have the icon in my innerHTML inherit the data-attributes of its parent, the button?

Body:
Rather than repeating the attributes again, or setting attributes at all, how about simply referencing the el in the listener?

const edit = document.createElement('button')
edit.innerHTML = '<svg class="review__icon"><use xlink:href="/img/icons.svg#icon-edit"></use></svg>'
edit.addEventListener('click', () => {
  console.log(el._id);
  console.log(el.title);
});

(if this is inside a loop, make sure el is declared with const or let)


问:
How can I retrieve all rows which depend on other rows in the same table?
So I have this table scheme

|id| item_id | dependency_item_id | completed |

The idea is to have rows in this table to point to other rows in the same table by dependency_item_id -> item_id.

What I want is to retrieve all records which have a dependency_item_id with a value of NULL and completed with a value of 0

AND

All records which have their parent, row which is the one with the item_id = dependency_item_id, with status completed = 1 and their status completed = 0

Example:

```<code>These are the records in the database.
|id|task_id|dependency_item_id|completed|
|1 |1      |null              |1        |
|2 |2      |null              |0        |
|3 |3      |1                 |0        |
|4 |4      |2                 |0        |
|5 |5      |2                 |0        |

With the query we should get only the second record
|id|task_id|dependency_item_id|completed|
|2 |2      |null              |0        |
|3 |3      |1                 |0        |
</code>```

The query I have by this point is the following:

```<code>SELECT process.*
    FROM tasks AS tasks
        JOIN tasks AS dep ON dep.dependency_item_id = process.task_id
    WHERE (dep.completed = 1 and tasks.completed = 0) OR tasks.dependency_item_id IS NULL
</code>```

答:
You can self-join the table:</p>

```<code>select t.*
from mytable t
left join mytable d on d.id = t.dependency_item_id
where
    (t.dependency_item_id is null and t.completed = 0)
    or (d.dependency_item_id is null and d.completed = 0)
</code>```

Body:
So I have this table scheme

|id| item_id | dependency_item_id | completed |

The idea is to have rows in this table to point to other rows in the same table by dependency_item_id -> item_id.

What I want is to retrieve all records which have a dependency_item_id with a value of NULL and completed with a value of 0

AND

All records which have their parent, row which is the one with the item_id = dependency_item_id, with status completed = 1 and their status completed = 0

Example:

These are the records in the database.
|id|task_id|dependency_item_id|completed|
|1 |1      |null              |1        |
|2 |2      |null              |0        |
|3 |3      |1                 |0        |
|4 |4      |2                 |0        |
|5 |5      |2                 |0        |

With the query we should get only the second record
|id|task_id|dependency_item_id|completed|
|2 |2      |null              |0        |
|3 |3      |1                 |0        |

The query I have by this point is the following:

SELECT process.*
    FROM tasks AS tasks
        JOIN tasks AS dep ON dep.dependency_item_id = process.task_id
    WHERE (dep.completed = 1 and tasks.completed = 0) OR tasks.dependency_item_id IS NULL

Body:
You can self-join the table:

select t.*
from mytable t
left join mytable d on d.id = t.dependency_item_id
where
    (t.dependency_item_id is null and t.completed = 0)
    or (d.dependency_item_id is null and d.completed = 0)


问:
I want a way to hide the cursor from EditText
How to make the cursor automatically disappear from EditText when not writing ?

I want something easy to understand. I am not a much programming expert

```<code><android.support.design.widget.TextInputEditText
                                android:id="@+id/name1"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginTop="8dp"
                                android:ems="8"
                                android:fontFamily="@font/bahij_janna"
                                android:hint="@string/team_2"
                                android:lines="1"
                                android:textColor="?attr/textColor"
                                android:inputType="textCapWords"
                                />
</code>```

See an example of the problem via the link

答:
To remove the cursor from edittext you need to set

text.setFocusable(false);

text.setOnTouchListener(new View.OnTouchListener() {

```<code>        @Override
        public boolean onTouch(View v, MotionEvent event) {

            text.setFocusableInTouchMode(true);
            return false;
        }
</code>```

});

Body:
How to make the cursor automatically disappear from EditText when not writing ?

I want something easy to understand. I am not a much programming expert

<android.support.design.widget.TextInputEditText
                                android:id="@+id/name1"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginTop="8dp"
                                android:ems="8"
                                android:fontFamily="@font/bahij_janna"
                                android:hint="@string/team_2"
                                android:lines="1"
                                android:textColor="?attr/textColor"
                                android:inputType="textCapWords"
                                />

See an example of the problem via the link

Body:
To remove the cursor from edittext you need to set

text.setFocusable(false);

text.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            text.setFocusableInTouchMode(true);
            return false;
        }

});


问:
How to decide between Composition and Generalization when designing objects and their relationships?
I thought to seek this answer from stackoverflow community that how to decide to go for composition or generalization when we are designing classes.</p>

答:
You use composition when you have a class that has a set of another objects, in any quantity. Use generalization when you have a class that shares common properties with a set of objects, but can also have other diferent properties or behavior.

For example, a Car has components like the engine, wheels, etc. This a composition relationship. But a Vehicle is a generalization of a Car, because you can have another types of Vehicles with diferent properties, like a Truck. Car and Truck are derived classes of Vehicle.

OwnerDisplayName: Kunal

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: El Cheicon


问:
Keyboard is hidden on orientation change
My keyboard is hidden when the orientation of the android phone changes to landscape. What should I do in order to show my keyboard?</p>

答:
Hi can you try AndroidManifest.xml

android:windowSoftInputMode="stateAlwaysVisible"  put this.


问:
Slow initial connection to Google Cloud App Engine
Initial connections to my website are extremely slow (100+ seconds). How can I diagnose the issue?

Using the Chrome dev tool network tab, I see that the issue is "initial connection" and not things like SSL or Waiting/TTFB.

This only happens for the first page visit to the website for a given device; after the first page loads, everything on the website is very fast. This consistently happens for new devices, on the same device if I don't visit the website for X days, and on the same device if I clear the cache and browsing history.

The website is a Django app is hosted using Google Cloud App Engine with 2 flexible instances.

User traffic to the website is low, so I doubt the issue is load balancing or traffic spikes.

Thanks!

答:
Yesterday I tried opening the page and I noticed 1.8min to load the main page and 2.1min to make a search, later attempts were faster as you mentioned. I also tried accessing the page today and it loaded quite fast.

From my understanding the high latency of the first connection might be related to session handling, database connections, ssl certificates problem, huge amount of uncached data, expensive operations run before the server sends the response. It's nearly impossible for us to determine it without access to your code, logs and database configurations.

As for how to narrow down the issue I might suggest the following:

Examine your logs for possible causes.

Add timeit logging interleaved with each of the statements that handle the requests and watch for bottlenecks or long-running code.

Deploy the same endpoint without logos, images and other data that would be browser-cached and see if it makes a difference.

Create a hello-world simple endpoint and check it's latency. Keep slowly evolving the endpoint to resemble your actual handling code with hopes on finding what's the issue.


问:
Is there a way to trigger a Rxjs timer on demand in addition to the preset n milliseconds?
I created an app that, among other things, shows scores of a certain product. I want to update those scores every 5 seconds, but only when the page is shown. If the user is on another page, the updating should stop.

I created a polling function using the timer from rxjs in my ScoresService. When the ScoresComponent (that shows the scores) is loaded (ngOnInit), it subscribes to scores$. When ScoreComponent is destroyed (ngOnDestroy) it unsubscribes from scores$.

```<code>
@Injectable({
  providedIn: 'root'
})
export class ScoresService {

  product: Product;
  scores$: Observable<Score[]>

  constructor(
    private http: HttpClient,
    private mainService: MainService
  ) {
    // set a timer for every 5 seconds, starting now, to get scores
    this.scores$ = timer(0, 5000).pipe(
      switchMap(() => this.getScores())
    );

    // when the product is set or changed, update this.product
    this.mainService.product$.subscribe((product) => {
       this.product = product;
       // fire the timer again?
    }
  }

  getScores(): Observable<Score[]> {
    const params = {
      order: 'best',
      from: moment().startOf('week').format('YYYY-MM-DD HH:mm:ss'),
      till: moment().endOf('week').format('YYYY-MM-DD HH:mm:ss'),
      limit: '100',
      product: this.product.id
    };

    return this.http.get<Score[]>(`${api_url}`', { params });
  }

}
</code>```

So the timer works, when the product is set of course. It only fetches new scores when ScoreComponent subscribes to scores$. But the problem occurs when the product is changed, because it takes between 0 and 5 seconds to get the new scores. Is there a way to fire the timer on demand, for instance when the product is changed. If there are other ways to achieve this, I would hear about it. The only thing that should be noted is that only when someone is subscribed to scores$ the polling should occur. I don't want endless polling of the endpoint if no one needs the new scores.

答:
You can combine the observables from product and the timer. This will fire the getScores everytime there is a new product, and start a new timer for every 5 seconds to get the scores.

```<code>export class ScoresService {
  product: Product;
  scores$: Observable<Score[]>;

  constructor(
    private http: HttpClient,
    private mainService: MainService
  ) {
    // set a timer for every 5 seconds, starting now, to get scores
    this.scores$ = this.mainService.product$.pipe(
      switchMap(() => timer(0, 5000)),
      switchMap(() => this.getScores())
    );

    this.mainService.product$.subscribe((product) => {
       this.product = product;
    }
  }

  getScores(): Observable<Score[]> {
   // ...
  }
}
</code>```

It feels like you should not use a product property in this service though, and let it all be streams. This will prevent unnecessary subscriptions. You can also add a shareReplay to have any subsequent subscriptions receive the latest emitted value from the http call:

```<code>export class ScoresService {
  readonly product$: Observable<Product> = this.mainService.product$;

  readonly scores$: Observable<Score[]> = this.product$.pipe(
    switchMap((product) => timer(0, 5000).pipe(
      switchMap(() => this.getScores(product.id))
    )),
    shareReplay({ refCount: true, bufferSize: 1 })
  );

  constructor(private http: HttpClient, private mainService: MainService) {}

  getScores(id: number): Observable<Score[]> {
   // ...
  }
}
</code>```

Body:
I created an app that, among other things, shows scores of a certain product. I want to update those scores every 5 seconds, but only when the page is shown. If the user is on another page, the updating should stop.

I created a polling function using the timer from rxjs in my ScoresService. When the ScoresComponent (that shows the scores) is loaded (ngOnInit), it subscribes to scores$. When ScoreComponent is destroyed (ngOnDestroy) it unsubscribes from scores$.

@Injectable({
  providedIn: 'root'
})
export class ScoresService {

  product: Product;
  scores$: Observable<Score[]>

  constructor(
    private http: HttpClient,
    private mainService: MainService
  ) {
    // set a timer for every 5 seconds, starting now, to get scores
    this.scores$ = timer(0, 5000).pipe(
      switchMap(() => this.getScores())
    );

    // when the product is set or changed, update this.product
    this.mainService.product$.subscribe((product) => {
       this.product = product;
       // fire the timer again?
    }
  }

  getScores(): Observable<Score[]> {
    const params = {
      order: 'best',
      from: moment().startOf('week').format('YYYY-MM-DD HH:mm:ss'),
      till: moment().endOf('week').format('YYYY-MM-DD HH:mm:ss'),
      limit: '100',
      product: this.product.id
    };

    return this.http.get<Score[]>(`${api_url}`', { params });
  }

}

So the timer works, when the product is set of course. It only fetches new scores when ScoreComponent subscribes to scores$. But the problem occurs when the product is changed, because it takes between 0 and 5 seconds to get the new scores. Is there a way to fire the timer on demand, for instance when the product is changed. If there are other ways to achieve this, I would hear about it. The only thing that should be noted is that only when someone is subscribed to scores$ the polling should occur. I don't want endless polling of the endpoint if no one needs the new scores.

Body:
You can combine the observables from product and the timer. This will fire the getScores everytime there is a new product, and start a new timer for every 5 seconds to get the scores.

export class ScoresService {
  product: Product;
  scores$: Observable<Score[]>;

  constructor(
    private http: HttpClient,
    private mainService: MainService
  ) {
    // set a timer for every 5 seconds, starting now, to get scores
    this.scores$ = this.mainService.product$.pipe(
      switchMap(() => timer(0, 5000)),
      switchMap(() => this.getScores())
    );

    this.mainService.product$.subscribe((product) => {
       this.product = product;
    }
  }

  getScores(): Observable<Score[]> {
   // ...
  }
}

It feels like you should not use a product property in this service though, and let it all be streams. This will prevent unnecessary subscriptions. You can also add a shareReplay to have any subsequent subscriptions receive the latest emitted value from the http call:

export class ScoresService {
  readonly product$: Observable<Product> = this.mainService.product$;

  readonly scores$: Observable<Score[]> = this.product$.pipe(
    switchMap((product) => timer(0, 5000).pipe(
      switchMap(() => this.getScores(product.id))
    )),
    shareReplay({ refCount: true, bufferSize: 1 })
  );

  constructor(private http: HttpClient, private mainService: MainService) {}

  getScores(id: number): Observable<Score[]> {
   // ...
  }
}


问:
Swift Decoding Error - ( suspect: Some Field Sometime Empty)
If I remove variable options the code will work, but I need it. I think the problem is because options array may/can empty.

Model

struct Schedule: Codable {
    let batch: String
    let menu: SubSchedule?
}

struct SubSchedule: Codable {
    let name: String
    let price: Int

    let options: [Options]?  //  <--- If I remove this, it'll work
}

struct Options: Codable {
    let field: String?
    let options: [SubOption]?
}

struct SubOption: Codable {
    let _id: String
    let addPrice: Int
    let value: String
}
```

<p><strong>Service</strong></p>

```URLSession.shared.dataTask(with: url) { data, _, _ in
    let result = try? JSONSerialization.jsonObject(with: data!, options: [])

    print(result as Any) // print decoded json

    let schedules = try!
                JSONDecoder().decode([Schedule].self, from: data!)
                DispatchQueue.main.sync {
                    completion(schedules)
                }
    }.resume()
```

<p><strong>JSON</strong></p>

```{
    "batch": "Lunch",
    "menu": {
        "name": "Dailysuki Tomyam Soup",
        "options": [{
            "field": "Tambah Nasi",
            "options": [{
                "addPrice": 0,
                "value": "None"
            }]
        }],

        // options not always have a value (may empty)
        //
        // options: ['']
        //

        "price": 25000
    }
}

```

<p><strong>ERROR</strong></p>

```Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "menu", intValue: nil), CodingKeys(stringValue: "options", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "Expected to decode Dictionary<String, Any> but found a string/data instead.", underlyingError: nil)): file /PROJECT/Services/Webservices.swift, line 23
```

答:
Try to make the _id variable in your SubOption struct to optional and tell me if it works

```<code>struct SubOption: Codable {
    let _id: String?
    let addPrice: Int
    let value: String
}
</code>```

Body:
If I remove variable options the code will work, but I need it. I think the problem is because options array may/can empty.

Model

struct Schedule: Codable {
    let batch: String
    let menu: SubSchedule?
}

struct SubSchedule: Codable {
    let name: String
    let price: Int

    let options: [Options]?  //  <--- If I remove this, it'll work
}

struct Options: Codable {
    let field: String?
    let options: [SubOption]?
}

struct SubOption: Codable {
    let _id: String
    let addPrice: Int
    let value: String
}

Service

URLSession.shared.dataTask(with: url) { data, _, _ in
    let result = try? JSONSerialization.jsonObject(with: data!, options: [])

    print(result as Any) // print decoded json

    let schedules = try!
                JSONDecoder().decode([Schedule].self, from: data!)
                DispatchQueue.main.sync {
                    completion(schedules)
                }
    }.resume()

JSON

{
    "batch": "Lunch",
    "menu": {
        "name": "Dailysuki Tomyam Soup",
        "options": [{
            "field": "Tambah Nasi",
            "options": [{
                "addPrice": 0,
                "value": "None"
            }]
        }],

        // options not always have a value (may empty)
        //
        // options: ['']
        //

        "price": 25000
    }
}

ERROR

Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "menu", intValue: nil), CodingKeys(stringValue: "options", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "Expected to decode Dictionary<String, Any> but found a string/data instead.", underlyingError: nil)): file /PROJECT/Services/Webservices.swift, line 23

Body:
Try to make the _id variable in your SubOption struct to optional and tell me if it works

struct SubOption: Codable {
    let _id: String?
    let addPrice: Int
    let value: String
}


问:
How to define a type when I only know the pattern for that object's keys?
I have a function expecting an object with keys like 'mykey-0', 'myotherkey-0', 'mykey-1', 'myotherkey-1', etc.

The thing is that I don't know if there will be any of these two keys, and I don't know what the number will be (it increases)

How can I express a TS type for these optional keys? Something like { 'mykey-*'?: string, 'myotherkey-*'?: string, otherprop: string }.

答:
Use Object.keys(obj)

This function will return array of keys

So you will be able to make your process over them.


问:
Using EXEC() AT [Linked Server] for Insert data from local server
let me first explain a little abot my setup before letting you know the issue Im dealing with:

I have two database servers: SQL 2008 and MySql. I have a procedure in SQL that first, deletes a table in MySql and then populates it with some data from the SQL itself. For both actions im using OPENQUERY. But, as you know, it doesnt know support large data. It becomes really slow eventhou for truncating the table in MySql (it was taking like 14 minutes to delete 60k rows... insane!).

So i found out i could use this syntax for truncating:

EXEC ('TRUNCATE TABLE table_name') AT LINKEDSERVER

But i havent been able to find the syntax for inserting the results of the SQL table to my MySql table thru this. It works correct when I insert static data, like this example:

EXEC ('INSERT INTO table_name (row1, row2) VALUES (value1, value2)') AT LINKEDSERVER

But I want to insert the results from a SQL, as I said, something like this:

EXEC ('INSERT INTO table_name (row1, row2) SELECT r1, r2 FROM SQL_DB.sql_table_name') AT LINKEDSERVER

I bet that i cannot do it because in that syntax, Im executing the exec in the MySql server and the SQL table doesnt exist there. So how can i referrence my SQL table inside the "EXEC() AT" syntax?

Thank you.

答:
you have to use "OPENQUERY" to do this - see

https://learn.microsoft.com/de-de/sql/t-sql/functions/openquery-transact-sql?view=sql-server-ver15


问:
OAuth 2.0 two-legged authentication vs SSL/TLS
I have two enterprise servers which need to communicate in a secure way, and am comparing using SSL (with client/server certs to validate both sides) vs two-legged authentication using OAuth 2.0 (optionally with MAC tokens or JWT tokens).

Historically OAuth seems to have been created for a totally different purpose (the 3-legged case where a user is allowing a service to access some data somewhere), and although two-legged is now integrated into the OAuth 2.0 spec, from what I have seen two-legged OAuth 2.0 doesn't seem to offer much additional protection over SSL.

The only point I can think of is that OAuth is potentially easier to configure than SSL, and it is easy to make mistakes with things like accepting bad SSL certs which can compromise security. However I am not sure if this is reason enough to go with OAuth.

Note that I mention these as separate options, but I think using OAuth would probably entail using it on top of HTTPS/SSL, so both would be used.

Is there any real advantage of using OAuth 2.0 two-legged scheme for server-to-server communication (no user involved)?

Note: I did find a a somewhat similar post here, but that is quite old but I don't feel that gave a satisfactory answer on this matter.

答:
To answer your question "what value would using OAuth (2 legged or similar) on top of that to authorize the servers to one another (assuming there is no user involved)."

You may refer below

https://salesforce.stackexchange.com/questions/93887/mutual-authentication-two-way-ssl-oauth


问:
Amazon Redshift : Best way to compare dates
I have a sample table in redshift. I want to generate a report with the month wise data. I found the below three ways so far.

trunc(created_at_date) between '2014-06-01' and '2014-06-30'

created_at_date like '2014-06%'

created_at_date >= '2014-06-01 00:00:00' and created_at_date <= '2014-06-30 23:59:59'

What is the best and optimal way to do so?

答:
Not the 1st one as it perform unnecessary (unless you really have such unprocessed data) truncate.

```<code> 1. trunc(created_at_date) between '2014-06-01' and '2014-06-30';
</code>```

Definitely not this one for obvious reasons (like)

```<code> 2. created_at_date like '2014-06%'
</code>```

May be this one:

```<code> 3. created_at_date >= '2014-06-01 00:00:00' and created_at_date <= '2014-06-30 23:59:59'
</code>```

However, since the requirement is to generate monthly reports which I would assume to be a recurring task and on multiple data sources, I would suggest creating a one time calendar table.

This table would have mapping of a date to a month value and then you can simply join your source data with that table and group by the "month" column.

P.S. Just realized I replied to a very 'ancient' question :p

Body:
Not the 1st one as it perform unnecessary (unless you really have such unprocessed data) truncate.

 1. trunc(created_at_date) between '2014-06-01' and '2014-06-30';

Definitely not this one for obvious reasons (like)

 2. created_at_date like '2014-06%'

May be this one:

 3. created_at_date >= '2014-06-01 00:00:00' and created_at_date <= '2014-06-30 23:59:59'

However, since the requirement is to generate monthly reports which I would assume to be a recurring task and on multiple data sources, I would suggest creating a one time calendar table.

This table would have mapping of a date to a month value and then you can simply join your source data with that table and group by the "month" column.

P.S. Just realized I replied to a very 'ancient' question :p