问:
How to use the Directory.GetFiles() method to choose between today's date and another date?
I am trying to find files using XML Reader which meet some conditions including if the File Age is Younger than a certain number. I am getting an error for CreationTime but I do not understand how to get through it. d1 is the current date and d2 is the date range for the youngest file

Error   CS1061  'string' does not contain a definition for 'CreationTime' and no accessible extension method 'CreationTime' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)

```<code> public int FileAgeYounger
            {
                get
                {
                    return FileAgeYounger;
                }
                set
                {
                    DateTime d1 = DateTime.Now;
                    d2 = d1.AddDays(FileAgeYounger);

                    if (subfolders == true & FileExtension != null & Fileprefix != null & FileUseRelativeAgeYounger == true)
                    {
                        FolderLocation2 = Directory.GetFiles(FolderLocation, Fileprefix + FileExtension, SearchOption.AllDirectories).Where(f => f.CreationTime >= d2 && f.CreationTime <= d1));
                    }
                }
</code>```

答:
Directory.GetFiles returns collection of string and on this strings collection (please refer MSDN documentaiton here) you are trying to use file (System.IO.File) methods like CreationTime and hence the error.

If you want sort on CreationTime, please use DirectoryInfo.

```<code>DirectoryInfo info = new DirectoryInfo(FolderLocation);
FileInfo[] files = info.GetFiles().OrderBy(p => p.CreationTime).ToArray();
</code>```

Body:
I am trying to find files using XML Reader which meet some conditions including if the File Age is Younger than a certain number. I am getting an error for CreationTime but I do not understand how to get through it. d1 is the current date and d2 is the date range for the youngest file

Error   CS1061  'string' does not contain a definition for 'CreationTime' and no accessible extension method 'CreationTime' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)

 public int FileAgeYounger
            {
                get
                {
                    return FileAgeYounger;
                }
                set
                {
                    DateTime d1 = DateTime.Now;
                    d2 = d1.AddDays(FileAgeYounger);

                    if (subfolders == true & FileExtension != null & Fileprefix != null & FileUseRelativeAgeYounger == true)
                    {
                        FolderLocation2 = Directory.GetFiles(FolderLocation, Fileprefix + FileExtension, SearchOption.AllDirectories).Where(f => f.CreationTime >= d2 && f.CreationTime <= d1));
                    }
                }

Body:
Directory.GetFiles returns collection of string and on this strings collection (please refer MSDN documentaiton here) you are trying to use file (System.IO.File) methods like CreationTime and hence the error.

If you want sort on CreationTime, please use DirectoryInfo.

DirectoryInfo info = new DirectoryInfo(FolderLocation);
FileInfo[] files = info.GetFiles().OrderBy(p => p.CreationTime).ToArray();


来源: stackexchange

问:
Visual Studio Code with OpenCV libraries

#include "opencv2/opencv.hpp"
#include "Eigen/Dense"
```

I need to import these libraries in Visual Studio Code in Ubuntu.
OpenCV is present. Also C++14 libraries should be present in the editor.

答:
Go to the terminal and use
locate <file you want to include>

Get the path of the file and ensure it is inside some include folder. For example:
/usr/local/include/opencv4/opencv2

Go to VS code press CTRL+SHIFT+P search for c/c++ edit configuration.

Inside c_cpp_properties.json file under include path add the path as shown:
{
"configurations": [
    {
        "name": "Linux",
        "includePath": [
            "${workspaceFolder}/**",
            "/usr/local/include/opencv4"
        ],
        "defines": [],
        "compilerPath": "/usr/bin/gcc",
        "cStandard": "c11",
        "cppStandard": "c++17",
        "intelliSenseMode": "clang-x64"
    }
],
"version": 4
}
This is what worked for me.

ContentLicense: CC BY-SA 3.0

Body:
#include "opencv2/opencv.hpp"
#include "Eigen/Dense"

I need to import these libraries in Visual Studio Code in Ubuntu.
OpenCV is present. Also C++14 libraries should be present in the editor.

ContentLicense: CC BY-SA 4.0


问:
Wildfly starts with error. javax.faces.FacesException: Unable to find CDI BeanManager
I have coded my first JSF hello world program in eclipse with WildFly 18, jdk-13.0.1. , windows 10.

Wildfly home and admin console working find but While executing program from url http://localhost:8080/jsf1/faces/WEB-INF/helloworld.xhtml it gives 404 - Not Found error. I get same error on url http://localhost:8080/jsf1

This is web.xml file

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>jsf1</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>
</web-app>
</code>```

and below is wildfly server log

```<code>2020-01-06 10:59:19,677 INFO  [org.jboss.as.patching] (MSC service thread 1-2) WFLYPAT0050: WildFly Full cumulative patch ID is: base, one-off patches include: none
2020-01-06 10:59:19,694 WARN  [org.jboss.as.domain.management.security] (MSC service thread 1-6) WFLYDM0111: Keystore C:\Program Files\wildfly-18.0.1.Final\standalone\configuration\application.keystore not found, it will be auto generated on first use with a self signed certificate for host localhost
2020-01-06 10:59:19,702 INFO  [org.jboss.as.server.deployment.scanner] (MSC service thread 1-3) WFLYDS0013: Started FileSystemDeploymentService for directory C:\Program Files\wildfly-18.0.1.Final\standalone\deployments
2020-01-06 10:59:19,723 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-5) WFLYSRV0027: Starting deployment of "jsf2.war" (runtime-name: "jsf2.war")
2020-01-06 10:59:19,720 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-2) WFLYSRV0027: Starting deployment of "jsf1.war" (runtime-name: "jsf1.war")
2020-01-06 10:59:19,827 INFO  [org.wildfly.extension.undertow] (MSC service thread 1-7) WFLYUT0006: Undertow HTTPS listener https listening on 127.0.0.1:8443
2020-01-06 10:59:20,856 INFO  [org.jboss.ws.common.management] (MSC service thread 1-7) JBWS022052: Starting JBossWS 5.3.0.Final (Apache CXF 3.3.3)
2020-01-06 10:59:25,045 INFO  [org.infinispan.factories.GlobalComponentRegistry] (MSC service thread 1-6) ISPN000128: Infinispan version: Infinispan 'Infinity Minus ONE +2' 9.4.16.Final
2020-01-06 10:59:25,635 INFO  [org.jboss.as.clustering.infinispan] (ServerService Thread Pool -- 77) WFLYCLINF0002: Started client-mappings cache from ejb container
2020-01-06 10:59:26,604 INFO  [javax.enterprise.resource.webcontainer.jsf.config] (ServerService Thread Pool -- 80) Initializing Mojarra 2.3.9.SP04 for context '/jsf1'
2020-01-06 10:59:26,610 INFO  [javax.enterprise.resource.webcontainer.jsf.config] (ServerService Thread Pool -- 78) Initializing Mojarra 2.3.9.SP04 for context '/jsf2'
2020-01-06 10:59:27,168 ERROR [stderr] (ServerService Thread Pool -- 80) javax.faces.FacesException: Unable to find CDI BeanManager

2020-01-06 10:59:27,169 ERROR [stderr] (ServerService Thread Pool -- 80)    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.application.applicationimpl.Version.isJsf23(Version.java:62)

2020-01-06 10:59:27,169 ERROR [stderr] (ServerService Thread Pool -- 80)    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.application.applicationimpl.ExpressionLanguage.addELResolver(ExpressionLanguage.java:136)

2020-01-06 10:59:27,170 ERROR [stderr] (ServerService Thread Pool -- 80)    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.application.ApplicationImpl.addELResolver(ApplicationImpl.java:221)

2020-01-06 10:59:27,170 ERROR [stderr] (ServerService Thread Pool -- 80)    at org.jboss.as.jsf-injection//org.jboss.as.jsf.injection.weld.WeldApplication.<init>(WeldApplication.java:60)

2020-01-06 10:59:27,171 ERROR [stderr] (ServerService Thread Pool -- 80)    at org.jboss.as.jsf-injection//org.jboss.as.jsf.injection.weld.WeldApplicationFactory.getApplication(WeldApplicationFactory.java:52)

2020-01-06 10:59:27,171 ERROR [stderr] (ServerService Thread Pool -- 80)    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.application.InjectionApplicationFactory.getApplication(InjectionApplicationFactory.java:61)

2020-01-06 10:59:27,172 ERROR [stderr] (ServerService Thread Pool -- 80)    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.config.InitFacesContext.getApplication(InitFacesContext.java:109)

2020-01-06 10:59:27,173 ERROR [stderr] (ServerService Thread Pool -- 80)    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.lifecycle.ClientWindowFactoryImpl.<init>(ClientWindowFactoryImpl.java:39)

2020-01-06 10:59:27,173 ERROR [stderr] (ServerService Thread Pool -- 80)    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

2020-01-06 10:59:27,174 ERROR [stderr] (ServerService Thread Pool -- 80)    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)

2020-01-06 10:59:27,174 ERROR [stderr] (ServerService Thread Pool -- 80)    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)

2020-01-06 10:59:27,174 ERROR [stderr] (ServerService Thread Pool -- 80)    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)

2020-01-06 10:59:27,175 ERROR [stderr] (ServerService Thread Pool -- 80)    at java.base/java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:166)

2020-01-06 10:59:27,175 ERROR [stderr] (ServerService Thread Pool -- 80)    at java.base/jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:404)

2020-01-06 10:59:27,176 ERROR [stderr] (ServerService Thread Pool -- 80)    at java.base/java.lang.Class.newInstance(Class.java:591)

</code>```

last lines of log

```<code>Caused by: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! null
    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.config.ConfigManager.initialize(ConfigManager.java:357)
    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:205)
    ... 21 more
Caused by: java.lang.NullPointerException
    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.facelets.impl.DefaultResourceResolver.resolveUrl(DefaultResourceResolver.java:40)
    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.facelets.impl.DefaultFaceletFactory.init(DefaultFaceletFactory.java:129)
    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.application.ApplicationAssociate.createFaceletFactory(ApplicationAssociate.java:849)
    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.application.ApplicationAssociate.initializeFacelets(ApplicationAssociate.java:342)
    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.application.ApplicationAssociate.getCompiler(ApplicationAssociate.java:420)
    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.config.processor.FaceletTaglibConfigProcessor.process(FaceletTaglibConfigProcessor.java:217)
    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.config.ConfigManager.initialize(ConfigManager.java:341)
    ... 22 more

2020-01-06 10:59:28,236 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "jsf1.war")]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"jsf1.war\".undertow-deployment" => "java.lang.RuntimeException: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! null
    Caused by: java.lang.RuntimeException: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! null
    Caused by: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! null
    Caused by: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! null
    Caused by: java.lang.NullPointerException"}}
2020-01-06 10:59:28,466 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "jsf2.war")]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"jsf2.war\".undertow-deployment" => "java.lang.RuntimeException: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! null
    Caused by: java.lang.RuntimeException: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! null
    Caused by: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! null
    Caused by: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! null
    Caused by: java.lang.NullPointerException"}}
2020-01-06 10:59:28,518 INFO  [org.jboss.as.server] (ServerService Thread Pool -- 44) WFLYSRV0010: Deployed "jsf2.war" (runtime-name : "jsf2.war")
2020-01-06 10:59:28,519 INFO  [org.jboss.as.server] (ServerService Thread Pool -- 44) WFLYSRV0010: Deployed "jsf1.war" (runtime-name : "jsf1.war")
2020-01-06 10:59:28,521 INFO  [org.jboss.as.controller] (Controller Boot Thread) WFLYCTL0183: Service status report
WFLYCTL0186:   Services which failed to start:      service jboss.deployment.unit."jsf2.war".undertow-deployment: java.lang.RuntimeException: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! null
      service jboss.deployment.unit."jsf1.war".undertow-deployment: java.lang.RuntimeException: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! null
WFLYCTL0448: 2 additional services are down due to their dependencies being missing or failed
2020-01-06 10:59:28,735 INFO  [org.jboss.as.server] (Controller Boot Thread) WFLYSRV0212: Resuming server
2020-01-06 10:59:28,745 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0060: Http management interface listening on http://127.0.0.1:9990/management
2020-01-06 10:59:28,745 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0051: Admin console listening on http://127.0.0.1:9990
2020-01-06 10:59:28,745 ERROR [org.jboss.as] (Controller Boot Thread) WFLYSRV0026: WildFly Full 18.0.1.Final (WildFly Core 10.0.3.Final) started (with errors) in 29279ms - Started 496 of 731 services (6 services failed or missing dependencies, 379 services are lazy, passive or on-demand)

</code>```

folder tree:

答:
I have added beans.xml file in WEB-INF directory with the following contents and the errors are gone. Finally I am able to run my hello world program in "Dynamic Web Module version 4.0" and "Java Server Faces version 2.3".

beans.xml contents

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
       version="2.0" bean-discovery-mode="annotated">

</beans>
</code>```

Body:
I have coded my first JSF hello world program in eclipse with WildFly 18, jdk-13.0.1. , windows 10.

Wildfly home and admin console working find but While executing program from url http://localhost:8080/jsf1/faces/WEB-INF/helloworld.xhtml it gives 404 - Not Found error. I get same error on url http://localhost:8080/jsf1

This is web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>jsf1</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>
</web-app>

and below is wildfly server log

2020-01-06 10:59:19,677 INFO  [org.jboss.as.patching] (MSC service thread 1-2) WFLYPAT0050: WildFly Full cumulative patch ID is: base, one-off patches include: none
2020-01-06 10:59:19,694 WARN  [org.jboss.as.domain.management.security] (MSC service thread 1-6) WFLYDM0111: Keystore C:\Program Files\wildfly-18.0.1.Final\standalone\configuration\application.keystore not found, it will be auto generated on first use with a self signed certificate for host localhost
2020-01-06 10:59:19,702 INFO  [org.jboss.as.server.deployment.scanner] (MSC service thread 1-3) WFLYDS0013: Started FileSystemDeploymentService for directory C:\Program Files\wildfly-18.0.1.Final\standalone\deployments
2020-01-06 10:59:19,723 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-5) WFLYSRV0027: Starting deployment of "jsf2.war" (runtime-name: "jsf2.war")
2020-01-06 10:59:19,720 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-2) WFLYSRV0027: Starting deployment of "jsf1.war" (runtime-name: "jsf1.war")
2020-01-06 10:59:19,827 INFO  [org.wildfly.extension.undertow] (MSC service thread 1-7) WFLYUT0006: Undertow HTTPS listener https listening on 127.0.0.1:8443
2020-01-06 10:59:20,856 INFO  [org.jboss.ws.common.management] (MSC service thread 1-7) JBWS022052: Starting JBossWS 5.3.0.Final (Apache CXF 3.3.3)
2020-01-06 10:59:25,045 INFO  [org.infinispan.factories.GlobalComponentRegistry] (MSC service thread 1-6) ISPN000128: Infinispan version: Infinispan 'Infinity Minus ONE +2' 9.4.16.Final
2020-01-06 10:59:25,635 INFO  [org.jboss.as.clustering.infinispan] (ServerService Thread Pool -- 77) WFLYCLINF0002: Started client-mappings cache from ejb container
2020-01-06 10:59:26,604 INFO  [javax.enterprise.resource.webcontainer.jsf.config] (ServerService Thread Pool -- 80) Initializing Mojarra 2.3.9.SP04 for context '/jsf1'
2020-01-06 10:59:26,610 INFO  [javax.enterprise.resource.webcontainer.jsf.config] (ServerService Thread Pool -- 78) Initializing Mojarra 2.3.9.SP04 for context '/jsf2'
2020-01-06 10:59:27,168 ERROR [stderr] (ServerService Thread Pool -- 80) javax.faces.FacesException: Unable to find CDI BeanManager

2020-01-06 10:59:27,169 ERROR [stderr] (ServerService Thread Pool -- 80)    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.application.applicationimpl.Version.isJsf23(Version.java:62)

2020-01-06 10:59:27,169 ERROR [stderr] (ServerService Thread Pool -- 80)    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.application.applicationimpl.ExpressionLanguage.addELResolver(ExpressionLanguage.java:136)

2020-01-06 10:59:27,170 ERROR [stderr] (ServerService Thread Pool -- 80)    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.application.ApplicationImpl.addELResolver(ApplicationImpl.java:221)

2020-01-06 10:59:27,170 ERROR [stderr] (ServerService Thread Pool -- 80)    at org.jboss.as.jsf-injection//org.jboss.as.jsf.injection.weld.WeldApplication.<init>(WeldApplication.java:60)

2020-01-06 10:59:27,171 ERROR [stderr] (ServerService Thread Pool -- 80)    at org.jboss.as.jsf-injection//org.jboss.as.jsf.injection.weld.WeldApplicationFactory.getApplication(WeldApplicationFactory.java:52)

2020-01-06 10:59:27,171 ERROR [stderr] (ServerService Thread Pool -- 80)    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.application.InjectionApplicationFactory.getApplication(InjectionApplicationFactory.java:61)

2020-01-06 10:59:27,172 ERROR [stderr] (ServerService Thread Pool -- 80)    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.config.InitFacesContext.getApplication(InitFacesContext.java:109)

2020-01-06 10:59:27,173 ERROR [stderr] (ServerService Thread Pool -- 80)    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.lifecycle.ClientWindowFactoryImpl.<init>(ClientWindowFactoryImpl.java:39)

2020-01-06 10:59:27,173 ERROR [stderr] (ServerService Thread Pool -- 80)    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

2020-01-06 10:59:27,174 ERROR [stderr] (ServerService Thread Pool -- 80)    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)

2020-01-06 10:59:27,174 ERROR [stderr] (ServerService Thread Pool -- 80)    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)

2020-01-06 10:59:27,174 ERROR [stderr] (ServerService Thread Pool -- 80)    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)

2020-01-06 10:59:27,175 ERROR [stderr] (ServerService Thread Pool -- 80)    at java.base/java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:166)

2020-01-06 10:59:27,175 ERROR [stderr] (ServerService Thread Pool -- 80)    at java.base/jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:404)

2020-01-06 10:59:27,176 ERROR [stderr] (ServerService Thread Pool -- 80)    at java.base/java.lang.Class.newInstance(Class.java:591)

last lines of log

Caused by: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! null
    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.config.ConfigManager.initialize(ConfigManager.java:357)
    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:205)
    ... 21 more
Caused by: java.lang.NullPointerException
    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.facelets.impl.DefaultResourceResolver.resolveUrl(DefaultResourceResolver.java:40)
    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.facelets.impl.DefaultFaceletFactory.init(DefaultFaceletFactory.java:129)
    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.application.ApplicationAssociate.createFaceletFactory(ApplicationAssociate.java:849)
    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.application.ApplicationAssociate.initializeFacelets(ApplicationAssociate.java:342)
    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.application.ApplicationAssociate.getCompiler(ApplicationAssociate.java:420)
    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.config.processor.FaceletTaglibConfigProcessor.process(FaceletTaglibConfigProcessor.java:217)
    at com.sun.jsf-impl@2.3.9.SP04//com.sun.faces.config.ConfigManager.initialize(ConfigManager.java:341)
    ... 22 more

2020-01-06 10:59:28,236 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "jsf1.war")]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"jsf1.war\".undertow-deployment" => "java.lang.RuntimeException: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! null
    Caused by: java.lang.RuntimeException: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! null
    Caused by: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! null
    Caused by: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! null
    Caused by: java.lang.NullPointerException"}}
2020-01-06 10:59:28,466 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "jsf2.war")]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"jsf2.war\".undertow-deployment" => "java.lang.RuntimeException: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! null
    Caused by: java.lang.RuntimeException: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! null
    Caused by: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! null
    Caused by: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! null
    Caused by: java.lang.NullPointerException"}}
2020-01-06 10:59:28,518 INFO  [org.jboss.as.server] (ServerService Thread Pool -- 44) WFLYSRV0010: Deployed "jsf2.war" (runtime-name : "jsf2.war")
2020-01-06 10:59:28,519 INFO  [org.jboss.as.server] (ServerService Thread Pool -- 44) WFLYSRV0010: Deployed "jsf1.war" (runtime-name : "jsf1.war")
2020-01-06 10:59:28,521 INFO  [org.jboss.as.controller] (Controller Boot Thread) WFLYCTL0183: Service status report
WFLYCTL0186:   Services which failed to start:      service jboss.deployment.unit."jsf2.war".undertow-deployment: java.lang.RuntimeException: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! null
      service jboss.deployment.unit."jsf1.war".undertow-deployment: java.lang.RuntimeException: java.lang.RuntimeException: com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! null
WFLYCTL0448: 2 additional services are down due to their dependencies being missing or failed
2020-01-06 10:59:28,735 INFO  [org.jboss.as.server] (Controller Boot Thread) WFLYSRV0212: Resuming server
2020-01-06 10:59:28,745 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0060: Http management interface listening on http://127.0.0.1:9990/management
2020-01-06 10:59:28,745 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0051: Admin console listening on http://127.0.0.1:9990
2020-01-06 10:59:28,745 ERROR [org.jboss.as] (Controller Boot Thread) WFLYSRV0026: WildFly Full 18.0.1.Final (WildFly Core 10.0.3.Final) started (with errors) in 29279ms - Started 496 of 731 services (6 services failed or missing dependencies, 379 services are lazy, passive or on-demand)

folder tree:

Body:
I have added beans.xml file in WEB-INF directory with the following contents and the errors are gone. Finally I am able to run my hello world program in "Dynamic Web Module version 4.0" and "Java Server Faces version 2.3".

beans.xml contents

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
       version="2.0" bean-discovery-mode="annotated">

</beans>


问:
SameSite=None .htaccess regex issue
The latest Chrome update requires cross domain cookies to be explicitly set to SameSite=None. The the following regex for .htaccess works except for OSX 10.14 Safari 13.0.5. (This browser has a bug with SameSite=None) and must be ignored.

```<code><If "%{HTTP_USER_AGENT} !~ /(iPhone; CPU iPhone OS 1[0-2]|iPad; CPU OS 1[0-2]|iPod touch; CPU iPhone OS 1[0-2]|Macintosh; Intel Mac OS X.*Version\x2F1[0-2].*Safari)/i">
Header edit Set-Cookie ^(.*)$ $1;SameSite=None;Secure</If>
</code>```

Does anyone know how to modify the regex above to exclude the Osx 10.14 Safari version?

Furthermore can anyone combine all of the additional incompatible clients into the regex above - a single regex to fix the SameSite=None issue would be amazing for everyone! Thanks

https://www.chromium.org/updates/same-site/incompatible-clients

```<code>    bool isSameSiteNoneIncompatible(string useragent):
    return hasWebKitSameSiteBug(useragent) ||
           dropsUnrecognizedSameSiteCookies(useragent)

bool hasWebKitSameSiteBug(string useragent):
    return isIosVersion(major:12, useragent) ||
           (isMacosxVersion(major:10, minor:14, useragent) &&
            (isSafari(useragent) || isMacEmbeddedBrowser(useragent)))

bool dropsUnrecognizedSameSiteCookies(string useragent):
    if isUcBrowser(useragent):
        return !isUcBrowserVersionAtLeast(major:12, minor:13, build:2, useragent)
    return isChromiumBased(useragent) &&
           isChromiumVersionAtLeast(major:51, useragent) &&
           !isChromiumVersionAtLeast(major:67, useragent)

// Regex parsing of User-Agent string. (See note above!)

bool isIosVersion(int major, string useragent):
    string regex = "\(iP.+; CPU .*OS (\d+)[_\d]*.*\) AppleWebKit\/"
    // Extract digits from first capturing group.
    return useragent.regexMatch(regex)[0] == intToString(major)

bool isMacosxVersion(int major, int minor, string useragent):
    string regex = "\(Macintosh;.*Mac OS X (\d+)_(\d+)[_\d]*.*\) AppleWebKit\/"
    // Extract digits from first and second capturing groups.
    return (useragent.regexMatch(regex)[0] == intToString(major)) &&
           (useragent.regexMatch(regex)[1] == intToString(minor))

bool isSafari(string useragent):
    string safari_regex = "Version\/.* Safari\/"
    return useragent.regexContains(safari_regex) &&
           !isChromiumBased(useragent)

bool isMacEmbeddedBrowser(string useragent):
    string regex = "^Mozilla\/[\.\d]+ \(Macintosh;.*Mac OS X [_\d]+\) "
                     + "AppleWebKit\/[\.\d]+ \(KHTML, like Gecko\)$"
    return useragent.regexContains(regex)

bool isChromiumBased(string useragent):
    string regex = "Chrom(e|ium)"
    return useragent.regexContains(regex)

bool isChromiumVersionAtLeast(int major, string useragent):
    string regex = "Chrom[^ \/]+\/(\d+)[\.\d]* "
    // Extract digits from first capturing group.
    int version = stringToInt(useragent.regexMatch(regex)[0])
    return version >= major

bool isUcBrowser(string useragent):
    string regex = "UCBrowser\/"
    return useragent.regexContains(regex)

bool isUcBrowserVersionAtLeast(int major, int minor, int build, string useragent):
    string regex = "UCBrowser\/(\d+)\.(\d+)\.(\d+)[\.\d]* "
    // Extract digits from three capturing groups.
    int major_version = stringToInt(useragent.regexMatch(regex)[0])
    int minor_version = stringToInt(useragent.regexMatch(regex)[1])
    int build_version = stringToInt(useragent.regexMatch(regex)[2])
    if major_version != major:
        return major_version > major
    if minor_version != minor:
        return minor_version > minor
    return build_version >= build
</code>```

答:
This should fix the issue for safari v13 on osx 10.14.x

```<code><If "%{HTTP_USER_AGENT} !~ /(iPhone; CPU iPhone OS 1[0-2]|iPad; CPU OS 1[0-2]|iPod touch; CPU iPhone OS 1[0-2]|Macintosh; Intel Mac OS X.*Version\x2F1[0-2].*Safari|Macintosh;.*Mac OS X 10_14.* AppleWebKit.*Version\x2F1[0-3].*Safari)/i">
Header edit Set-Cookie ^(.*)$ $1;SameSite=None;Secure</If>
</code>```

Still haven't included all the chromium patches though...

Title: SameSite=None .htaccess regex issue

Body:
The latest Chrome update requires cross domain cookies to be explicitly set to SameSite=None. The the following regex for .htaccess works except for OSX 10.14 Safari 13.0.5. (This browser has a bug with SameSite=None) and must be ignored.

<If "%{HTTP_USER_AGENT} !~ /(iPhone; CPU iPhone OS 1[0-2]|iPad; CPU OS 1[0-2]|iPod touch; CPU iPhone OS 1[0-2]|Macintosh; Intel Mac OS X.*Version\x2F1[0-2].*Safari)/i">
Header edit Set-Cookie ^(.*)$ $1;SameSite=None;Secure</If>

Does anyone know how to modify the regex above to exclude the Osx 10.14 Safari version?

Furthermore can anyone combine all of the additional incompatible clients into the regex above - a single regex to fix the SameSite=None issue would be amazing for everyone! Thanks

https://www.chromium.org/updates/same-site/incompatible-clients

    bool isSameSiteNoneIncompatible(string useragent):
    return hasWebKitSameSiteBug(useragent) ||
           dropsUnrecognizedSameSiteCookies(useragent)

bool hasWebKitSameSiteBug(string useragent):
    return isIosVersion(major:12, useragent) ||
           (isMacosxVersion(major:10, minor:14, useragent) &&
            (isSafari(useragent) || isMacEmbeddedBrowser(useragent)))

bool dropsUnrecognizedSameSiteCookies(string useragent):
    if isUcBrowser(useragent):
        return !isUcBrowserVersionAtLeast(major:12, minor:13, build:2, useragent)
    return isChromiumBased(useragent) &&
           isChromiumVersionAtLeast(major:51, useragent) &&
           !isChromiumVersionAtLeast(major:67, useragent)

// Regex parsing of User-Agent string. (See note above!)

bool isIosVersion(int major, string useragent):
    string regex = "\(iP.+; CPU .*OS (\d+)[_\d]*.*\) AppleWebKit\/"
    // Extract digits from first capturing group.
    return useragent.regexMatch(regex)[0] == intToString(major)

bool isMacosxVersion(int major, int minor, string useragent):
    string regex = "\(Macintosh;.*Mac OS X (\d+)_(\d+)[_\d]*.*\) AppleWebKit\/"
    // Extract digits from first and second capturing groups.
    return (useragent.regexMatch(regex)[0] == intToString(major)) &&
           (useragent.regexMatch(regex)[1] == intToString(minor))

bool isSafari(string useragent):
    string safari_regex = "Version\/.* Safari\/"
    return useragent.regexContains(safari_regex) &&
           !isChromiumBased(useragent)

bool isMacEmbeddedBrowser(string useragent):
    string regex = "^Mozilla\/[\.\d]+ \(Macintosh;.*Mac OS X [_\d]+\) "
                     + "AppleWebKit\/[\.\d]+ \(KHTML, like Gecko\)$"
    return useragent.regexContains(regex)

bool isChromiumBased(string useragent):
    string regex = "Chrom(e|ium)"
    return useragent.regexContains(regex)

bool isChromiumVersionAtLeast(int major, string useragent):
    string regex = "Chrom[^ \/]+\/(\d+)[\.\d]* "
    // Extract digits from first capturing group.
    int version = stringToInt(useragent.regexMatch(regex)[0])
    return version >= major

bool isUcBrowser(string useragent):
    string regex = "UCBrowser\/"
    return useragent.regexContains(regex)

bool isUcBrowserVersionAtLeast(int major, int minor, int build, string useragent):
    string regex = "UCBrowser\/(\d+)\.(\d+)\.(\d+)[\.\d]* "
    // Extract digits from three capturing groups.
    int major_version = stringToInt(useragent.regexMatch(regex)[0])
    int minor_version = stringToInt(useragent.regexMatch(regex)[1])
    int build_version = stringToInt(useragent.regexMatch(regex)[2])
    if major_version != major:
        return major_version > major
    if minor_version != minor:
        return minor_version > minor
    return build_version >= build

Body:
This should fix the issue for safari v13 on osx 10.14.x

<If "%{HTTP_USER_AGENT} !~ /(iPhone; CPU iPhone OS 1[0-2]|iPad; CPU OS 1[0-2]|iPod touch; CPU iPhone OS 1[0-2]|Macintosh; Intel Mac OS X.*Version\x2F1[0-2].*Safari|Macintosh;.*Mac OS X 10_14.* AppleWebKit.*Version\x2F1[0-3].*Safari)/i">
Header edit Set-Cookie ^(.*)$ $1;SameSite=None;Secure</If>

Still haven't included all the chromium patches though...


问:
HTTP timeout when making long running HTTP request from Azure Function
I am currently writing an Azure Function application to generate large PDF’s from HTML. I have an Azure Service Bus queue that gets pushed to via a website and then the queue messages get processed by the Azure Function (Basic Tier App Service Plan)

To generate the PDF’s, I make a HTTP request to an Azure Cloud Service from within the Azure function which generates me a byte array for which I write to Azure Blob Storage.

Sometimes the HTTP request can take up to 30 minutes. When I make any HTTP request at the moment that is longer than 4 minutes 30 seconds, I never get a response back. If my assumptions are correct, it’s due to the connection between the Cloud Service and the Azure Function timing out.

Has anyone got any suggestions which would allow for longer running HTTP requests using this infrastructure?

答:
You are likely hitting the idle timeout on the cloud service side.  To fix this, set the idleTimeoutInMinutes on the InputEndpoint (https://learn.microsoft.com/en-us/azure/cloud-services/cloud-services-configuration-and-management-faq#how-do-i-set-the-idle-timeout-for-azure-load-balancer):

```<code><Endpoints>
   <InputEndpoint name="Endpoint1" protocol="tcp" port="10100" idleTimeoutInMinutes="30" />
</Endpoints>
</code>```

However this is probably the wrong solution.  You should not design a system that requires a response from an active HTTP connection for 30 minutes.  There are too many variables that can cause the connection to fail.  You should use an async model where you call the cloud service to start the job which will return a jobid, then periodically call the cloud service to check the status of the job.  See https://learn.microsoft.com/en-us/azure/architecture/patterns/async-request-reply for a design pattern.

Body:
You are likely hitting the idle timeout on the cloud service side.  To fix this, set the idleTimeoutInMinutes on the InputEndpoint (https://learn.microsoft.com/en-us/azure/cloud-services/cloud-services-configuration-and-management-faq#how-do-i-set-the-idle-timeout-for-azure-load-balancer):

<Endpoints>
   <InputEndpoint name="Endpoint1" protocol="tcp" port="10100" idleTimeoutInMinutes="30" />
</Endpoints>

However this is probably the wrong solution.  You should not design a system that requires a response from an active HTTP connection for 30 minutes.  There are too many variables that can cause the connection to fail.  You should use an async model where you call the cloud service to start the job which will return a jobid, then periodically call the cloud service to check the status of the job.  See https://learn.microsoft.com/en-us/azure/architecture/patterns/async-request-reply for a design pattern.


问:
What's the preferred method in the community for having python 2.x and 3.x in the same codebase?
I am starting a project in Python 3.x, (I'm quite new to Python) and there exists the possibility that I will need to use say Thrift or any other library that is not yet ported to Python 3.x.

I don't mind about devoting some (substantial) amount of time to convert an external library to Python 3.x if with that others can benefit from that, but I'm curious if there's any preferred way in the Open Source community to deal with this problem.

I have been reading here and there in the python.org site and in some other websites, but I haven't found anything conclusive.  The only thing that I found is that this is a chicken-and-egg problem.

It's out of the question (unless there's no other option) that I ship a dump of a library with my own modifications just to make it 3.x compliant.

Should I...

prepare all the code with __future imports and change here and there appropriately and leave it ready to work with both 2.x and 3.x?  Am I going to find any problem with this, other than the natural resistance of upstream to integrate such amount of changes?

create another branch of the code?  That, to me, should be quite useless, as nobody will maintain that branch except me, probably, and it's a huge duplication effort.

use some type of wrapper that I am not aware of to use those libraries as-is (like using some intermediate bindings in another language) and just create the glue in my code?

Many thanks!

答:
I Can't talk for the community but these from __future__ import ... don't work for all python versions or aren't reliable on some cases.

print_function and unicode_literals were added on Python2.6, with_statement on Python2.5 and the others on Python2.2

So, if you want to support 2.6 or later, you're fine. If you still need to support 2.5 or, even worst, 2.4, you will need another approach.

Using from __future__ import unicode_literals won't work properly because Python2 let you do conversion from byte to unicode without encoding while Python3 don't. Also, calling str or bytes has different arguments.

The difference of treatment on strings seems to be the main problem to make a program compatible with both Python2 and Python3.


问:
IPython: ipywidgets bug - Code working on Goolge Colab, but not on Jupyter Notebook (tested on 2 different PCs)?
This code is a "Filter as you type" textbox example. It works fine on Google Colab, but not on Jupyter Notebook. I tried it on 2 different computers (and on 2 different browsers) that have Jupyter Notebook installed and the 'out' widget only displays the textbox but nothing else. Any idea how to fix this?

I have tried pip uninstall ipywidgets then install again without success.

Thanks.

```<code>import pandas as pd, IPython.display, ipywidgets as widgets
out = widgets.Output()

df = pd.DataFrame ({'PLAYER':['MOHAMED SALAH', 'MESSI', 'MO SALAH', 'RONALDO', 'PELE', 'PEPE', 'MANE', 'RAMREZ']})

textbox = widgets.Text(value='', description='Player:')
display(textbox)

def display_result(value):
    value = str(value['new']).upper()
    if "{" not in value:
        result = df[(df['PLAYER'].str.contains(value))]
        if result.shape[0]>0:
            with out:
                out.clear_output()
                display(result)

display(out)
textbox.observe(display_result)
</code>```

This is the output from Google Colab:

This is the output from Jupyter Notebook:

答: I have discovered that this is caused by the "Limit Output" extension in NbExtensions. When I disabled it, the output widget worked.

Body:
This code is a "Filter as you type" textbox example. It works fine on Google Colab, but not on Jupyter Notebook. I tried it on 2 different computers (and on 2 different browsers) that have Jupyter Notebook installed and the 'out' widget only displays the textbox but nothing else. Any idea how to fix this?

I have tried pip uninstall ipywidgets then install again without success.

Thanks.

import pandas as pd, IPython.display, ipywidgets as widgets
out = widgets.Output()

df = pd.DataFrame ({'PLAYER':['MOHAMED SALAH', 'MESSI', 'MO SALAH', 'RONALDO', 'PELE', 'PEPE', 'MANE', 'RAMREZ']})

textbox = widgets.Text(value='', description='Player:')
display(textbox)

def display_result(value):
    value = str(value['new']).upper()
    if "{" not in value:
        result = df[(df['PLAYER'].str.contains(value))]
        if result.shape[0]>0:
            with out:
                out.clear_output()
                display(result)

display(out)
textbox.observe(display_result)

This is the output from Google Colab:

This is the output from Jupyter Notebook:


问:
command line interface for background python process
How can I create a command line interface that persists as a background process and only executes commands when specific commands are entered? The following is pseudo code:

def startup():
   # costly startup that loads objects into memory once in a background process

def tear_down()
   # shut down; generally not needed, as main is acting like a service

def main():
    startup()

    # pseudo code that checks shell input for a match; after execution releases back to shell
    while True:
        usr_in = get_current_bash_command()
        if usr_in == "option a":
            # blocking action that release control back to shell when complete
        if usr_in == "option b":
            # something else with handling like option a
        if usr_in == "quit":
            # shuts down background process; will not be used frequently
            tear_down()
            break
   print("service has been shut down.  Bye!")

if __name__ == "__main__":
    # run non-blocking in background, only executing code if usr_in matches commands:
    main()
```

Note what this is not:

typical example of argparse or click, that runs a (blocking) python process until all commands are completed

a series of one-off scripts for each command; they utilize objects in memory instantiated in the background process with startup()

a completely different shell, like ipython; I'd like to integrate this with a standard shell, e.g. bash.

I am familiar with click, argparse, subprocess, etc., and as far as I can tell they accept a single command and block until completion.  I specifically seek something that interacts with a background process so that expensive startup (loading objects into memory) is handled only once.  I have looked at both python daemon and service packages, but I'm unsure if these are the right tool for the job also.

How can I accomplish this?  I feel as though I don't know what to google to get the answer I need...

答:
this is just one way you might do this... (there are other ways as well, this is just a pretty simple method)

you could use a server as your long running process (you would then turn it into a service using init systemV or upstart)

hardworker.py

```<code>import flask

app = flask.Flask("__main__")

@app.route("/command1")
def do_something():
    time.sleep(20)
    return json.dumps({"result":"OK"})

@app.route("/command2")
def do_something_else():
    time.sleep(26)
    return json.dumps({"result":"OK","reason":"Updated"})

if __name__ == "__main__":
   app.run(port=5000)
</code>```

then your client could just make simple http requests against your "service"

thin_client.sh

```<code>if [[ $1 == "command1" ]]; then
   curl http://localhost:5000/command1
else if [[ $1 == "command2" ]]; then
   curl http://localhost:5000/command2
fi;
</code>```

Body:
How can I create a command line interface that persists as a background process and only executes commands when specific commands are entered? The following is pseudo code:

def startup():
   # costly startup that loads objects into memory once in a background process

def tear_down()
   # shut down; generally not needed, as main is acting like a service

def main():
    startup()

    # pseudo code that checks shell input for a match; after execution releases back to shell
    while True:
        usr_in = get_current_bash_command()
        if usr_in == "option a":
            # blocking action that release control back to shell when complete
        if usr_in == "option b":
            # something else with handling like option a
        if usr_in == "quit":
            # shuts down background process; will not be used frequently
            tear_down()
            break
   print("service has been shut down.  Bye!")

if __name__ == "__main__":
    # run non-blocking in background, only executing code if usr_in matches commands:
    main()

Note what this is not:

typical example of argparse or click, that runs a (blocking) python process until all commands are completed

a series of one-off scripts for each command; they utilize objects in memory instantiated in the background process with startup()

a completely different shell, like ipython; I'd like to integrate this with a standard shell, e.g. bash.

I am familiar with click, argparse, subprocess, etc., and as far as I can tell they accept a single command and block until completion.  I specifically seek something that interacts with a background process so that expensive startup (loading objects into memory) is handled only once.  I have looked at both python daemon and service packages, but I'm unsure if these are the right tool for the job also.

How can I accomplish this?  I feel as though I don't know what to google to get the answer I need...

Body:
this is just one way you might do this... (there are other ways as well, this is just a pretty simple method)

you could use a server as your long running process (you would then turn it into a service using init systemV or upstart)

hardworker.py

import flask

app = flask.Flask("__main__")

@app.route("/command1")
def do_something():
    time.sleep(20)
    return json.dumps({"result":"OK"})

@app.route("/command2")
def do_something_else():
    time.sleep(26)
    return json.dumps({"result":"OK","reason":"Updated"})

if __name__ == "__main__":
   app.run(port=5000)

then your client could just make simple http requests against your "service"

thin_client.sh

if [[ $1 == "command1" ]]; then
   curl http://localhost:5000/command1
else if [[ $1 == "command2" ]]; then
   curl http://localhost:5000/command2
fi;


问:
Is HLS encryption needed over HTTPS?
HLS offers the possibility to encrypt the transfered video data. Is it really needed to use that encryption if I'm running the web server over HTTPS? By using HTTPS the data stream is already encrypted, so why would I use an extra layer?</p>

答:
It serves a totally different purpose. SSL is terminated (decrypted) by the browser/http client. Encrypted video is decrypted by the player/app. Basically, this allows for putting the video itself on a server accessible to anyone (with or without TLS) but unless you have the decryption key, the files are useless.

TLS is for your benefit (privacy), encryption is for the video owners benefit (control of decryption key)

Title: Is HLS encryption needed over HTTPS?


问:
Prevent HTML5 video from being downloaded (right-click saved)?
How can I disable "Save Video As..." from a browser's right-click menu to prevent clients from downloading a video?

Are there more complete solutions that prevent the client from accessing a file path directly?

答:
You can use

```<code><video src="..." ... controlsList="nodownload">
</code>```

https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/controlsList

It doesn't prevent saving the video, but it does remove the download button and the "Save as" option in the context menu.

Body:
You can use

<video src="..." ... controlsList="nodownload">

https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/controlsList

It doesn't prevent saving the video, but it does remove the download button and the "Save as" option in the context menu.


问:
String manipulation in jQuery
I have a div which collapses clicking on a text header. I want to change the header from "+ filters" to "- filters" accordingly (when the div is collapsed or expanded)

How can I perform this with jQuery?

```<code>if (headerDiv.text() starts with "+")
    replace "+" with "-"
else
    replace "-" with "+"
</code>```

答:
Never mind, I figured it out

```<code>if ($(header).text().trim().charAt(0) == "+")
    $(header).text($(header).text().replace("+", "-"));
else
    $(header).text($(header).text().replace("-", "+"));
</code>```

If this is not the correct way, I'd appreciate a heads up

OwnerDisplayName: Juan Manuel

Title: String manipulation in jQuery

Body:
I have a div which collapses clicking on a text header. I want to change the header from "+ filters" to "- filters" accordingly (when the div is collapsed or expanded)

How can I perform this with jQuery?

if (headerDiv.text() starts with "+")
    replace "+" with "-"
else
    replace "-" with "+"

Body:
Never mind, I figured it out

if ($(header).text().trim().charAt(0) == "+")
    $(header).text($(header).text().replace("+", "-"));
else
    $(header).text($(header).text().replace("-", "+"));

If this is not the correct way, I'd appreciate a heads up

ContentLicense: CC BY-SA 2.5


问:
Using a webservice from my Zend project
I'm working with an external API webservice that returns a json output true or false. I visit a URL like

```<code>http://site.com/api/valid
</code>```

and it gives me something like this, which looks like json

```<code>"true"
</code>```

Right now I'm visiting the url manually, but I want to now do it programmatically from within my zend project. What should I use to get the result correctly

答:
Sounds like you need a method that can grab the endpoint. Well, there's many ways but since you are already using Zend, you might as well read up on http://framework.zend.com/manual/1.11/en/zend.http.client.adapters.html

Here's a static method:

```<code>    static function curl($url, $method, $params = array()){
            $client = new Zend_Http_Client($url);
            if($method == "POST"){
                $client->setParameterPOST($params);
            }else{
                $client->setParameterGet($params);
            }
            $response = $client->request($method);
            return $response->getBody();
        }
</code>```

Or use php's native method $response = file_get_contents($url);

Make sure to json_decode() your responses.

Title: Using a webservice from my Zend project

Body:
I'm working with an external API webservice that returns a json output true or false. I visit a URL like

http://site.com/api/valid

and it gives me something like this, which looks like json

"true"

Right now I'm visiting the url manually, but I want to now do it programmatically from within my zend project. What should I use to get the result correctly

Body:
Sounds like you need a method that can grab the endpoint. Well, there's many ways but since you are already using Zend, you might as well read up on http://framework.zend.com/manual/1.11/en/zend.http.client.adapters.html

Here's a static method:

    static function curl($url, $method, $params = array()){
            $client = new Zend_Http_Client($url);
            if($method == "POST"){
                $client->setParameterPOST($params);
            }else{
                $client->setParameterGet($params);
            }
            $response = $client->request($method);
            return $response->getBody();
        }

Or use php's native method $response = file_get_contents($url);

Make sure to json_decode() your responses.


问:
How to do date time picker with respected timezone with selected dropdown?
I need a calendar with time select as well as timezone selection. Like below image:

Here is my code:

$('#datetimepicker').datetimepicker({
    // format:'d.m.Y H:i',
    // timepicker:false,
    // allowTimes: []
    // onSelectDate:function(ct,$i){ // only to select time the changed date highlighted
    //     alert(ct.dateFormat('d/m/Y'));
    // },
    inline:true,
    step: 30,
    lang:'ru',
    disabledWeekDays: [0,6]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.full.js"></script>

<div>
    <input id="datetimepicker" type="text" >
</div></code>```

I got the datetimepicker plungin to do this. But can't able to add calendar based on timezone. Here i'm attached my working code, but not added any timezone dropdown here. Can anyone suggest to achieve this:

答:
One option is to use control groups. In the snippet below, I used the CSS classes ui-controlgroup and ui-controlgroup-vertical to achieve this. However, you can also use scripting as shown in the documentation. As you will observe, I took the liberty to demonstrate the dropdown using specific timezones, but, you can use Moment in conjunction with Luxon to achieve your needs. The datetimepicker plugin does not have a built-in ability to refresh after update, but I attempted a hack using blur to achieve that.

<!DOCTYPE html>

    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.css"/>

   <input id="datetimepicker" type="text" class="ui-controlgroup-item">
   <select id="timezonepicker" class="ui-controlgroup-item">
    <option value="Europe/Moscow" selected>Moscow Standard Time</option>
    <option value="Asia/Omsk">Omsk Time</option>
    <option value="Asia/Novosibirsk">Novosibirsk Time</option>
   </select>

```

Body:
I need a calendar with time select as well as timezone selection. Like below image:

Here is my code:

$('#datetimepicker').datetimepicker({
    // format:'d.m.Y H:i',
    // timepicker:false,
    // allowTimes: []
    // onSelectDate:function(ct,$i){ // only to select time the changed date highlighted
    //     alert(ct.dateFormat('d/m/Y'));
    // },
    inline:true,
    step: 30,
    lang:'ru',
    disabledWeekDays: [0,6]
});

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.css"/>

    <input id="datetimepicker" type="text" >

I got the datetimepicker plungin to do this. But can't able to add calendar based on timezone. Here i'm attached my working code, but not added any timezone dropdown here. Can anyone suggest to achieve this:

Body:
One option is to use control groups. In the snippet below, I used the CSS classes ui-controlgroup and ui-controlgroup-vertical to achieve this. However, you can also use scripting as shown in the documentation. As you will observe, I took the liberty to demonstrate the dropdown using specific timezones, but, you can use Moment in conjunction with Luxon to achieve your needs. The datetimepicker plugin does not have a built-in ability to refresh after update, but I attempted a hack using blur to achieve that.

<!DOCTYPE html>
<html>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.css"/>
 <script src="https://cdn.jsdelivr.net/npm/luxon@1.22.0/build/global/luxon.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.full.js"></script>
 <body>
  <!-- https://jqueryui.com/controlgroup/ -->
  <div class="ui-controlgroup ui-controlgroup-vertical">
   <input id="datetimepicker" type="text" class="ui-controlgroup-item">
   <select id="timezonepicker" class="ui-controlgroup-item">
    <option value="Europe/Moscow" selected>Moscow Standard Time</option>
    <option value="Asia/Omsk">Omsk Time</option>
    <option value="Asia/Novosibirsk">Novosibirsk Time</option>
   </select>
  </div>
  <script>
   $('#datetimepicker').datetimepicker({
                            inline:true,
                            step: 30,
                            lang:'ru',
                            disabledWeekDays: [0,6]
   });
   $('#timezonepicker').change(function() {

                                let newDate = luxon.DateTime.fromISO(luxon.DateTime.local(), {zone: $(this).val()}).toFormat('yyyy/MM/dd hh:mm');
    $('#datetimepicker').val(newDate);
    $('#datetimepicker').trigger('blur');
   });
  </script>
 </body>
</html>


问:
'react-scripts' is not recognized as an internal or external command
I've got a maven project, within which is JavaScript project cloned as a git sub-module. So the directory structure looks like mavenapp/src/main/javascript/[npm project files]

Inside my package.json, the test looks like this:

```<code>"test": "react-scripts test --env=jsdom",
</code>```

but when I try to run npm test, it says

'react-scripts' is not recognized as an internal or external command,

Interestingly, when I clone the javascript project independently I don't get this error. I've tried re-running npm install.

NPM version: 5.5.1

Node.js version: 9.3.0

答: Running the npm update command solved my problem.

Body:
I've got a maven project, within which is JavaScript project cloned as a git sub-module. So the directory structure looks like mavenapp/src/main/javascript/[npm project files]

Inside my package.json, the test looks like this:

"test": "react-scripts test --env=jsdom",

but when I try to run npm test, it says

'react-scripts' is not recognized as an internal or external command,

Interestingly, when I clone the javascript project independently I don't get this error. I've tried re-running npm install.

NPM version: 5.5.1

Node.js version: 9.3.0


问:
relation *db_name* does not exist postgres
I am trying to set up an ubuntu server with postgres(following digitalocean tuorial).

I ssh'd to the server as root user, from there created a user named 'justin', gave that user admin privileges as instructed. Switched to 'justin', installed python, django, pip, etc and postgres. From here the tutorial said type sudo -u postgres psql
, I did this. From here I created a db 'jobzumodb' and user 'jobzumojustin'. I am now trying to grant privileges of that db to this new user: GRANT ALL PRIVILEGES ON jobzumodb TO jobzumojustin; and it returns ERROR:  relation "jobzumodb" does not exist. However if I postgres=#  \l I see:

```<code>                              List of databases
   Name    |  Owner   | Encoding | Collate |  Ctype  |   Access privileges
-----------+----------+----------+---------+---------+-----------------------
 jobzumodb | postgres | UTF8     | C.UTF-8 | C.UTF-8 | =Tc/postgres         +
           |          |          |         |         | postgres=CTc/postgres+
           |          |          |         |         | admin=CTc/postgres
 postgres  | postgres | UTF8     | C.UTF-8 | C.UTF-8 |
</code>```

Anyone know what is causing this?

Note: when I created the db I created it with: CREATE DATABASE jobzumoDB;. And was trying to access it for a long time as 'jobzumoDB' and not 'jobzumodb', before learning the \l command and that it saved as 'jobzumodb' because I did not pass it in quotes. Anyway, not sure if this could be having an effect.

Thanks for any help.

Another edit: upon rereading this I realized I am using the 'postgres' user (I see postgres=#), should I be using the 'jobzumojustin' user and jobzumojustin=# ? Also, I checked to see if 'jobzumojustin' exists, it does, but does not have anything listed under 'list of roles and attributes'.

答:
I think you forgot the database keyword. It should be:</p>

```<code>GRANT ALL PRIVILEGES ON DATABASE jobzumodb TO jobzumojustin;
</code>```

Body:
I am trying to set up an ubuntu server with postgres(following digitalocean tuorial).

I ssh'd to the server as root user, from there created a user named 'justin', gave that user admin privileges as instructed. Switched to 'justin', installed python, django, pip, etc and postgres. From here the tutorial said type sudo -u postgres psql
, I did this. From here I created a db 'jobzumodb' and user 'jobzumojustin'. I am now trying to grant privileges of that db to this new user: GRANT ALL PRIVILEGES ON jobzumodb TO jobzumojustin; and it returns ERROR:  relation "jobzumodb" does not exist. However if I postgres=#  \l I see:

                              List of databases
   Name    |  Owner   | Encoding | Collate |  Ctype  |   Access privileges
-----------+----------+----------+---------+---------+-----------------------
 jobzumodb | postgres | UTF8     | C.UTF-8 | C.UTF-8 | =Tc/postgres         +
           |          |          |         |         | postgres=CTc/postgres+
           |          |          |         |         | admin=CTc/postgres
 postgres  | postgres | UTF8     | C.UTF-8 | C.UTF-8 |

Anyone know what is causing this?

Note: when I created the db I created it with: CREATE DATABASE jobzumoDB;. And was trying to access it for a long time as 'jobzumoDB' and not 'jobzumodb', before learning the \l command and that it saved as 'jobzumodb' because I did not pass it in quotes. Anyway, not sure if this could be having an effect.

Thanks for any help.

Another edit: upon rereading this I realized I am using the 'postgres' user (I see postgres=#), should I be using the 'jobzumojustin' user and jobzumojustin=# ? Also, I checked to see if 'jobzumojustin' exists, it does, but does not have anything listed under 'list of roles and attributes'.

Body:
I think you forgot the database keyword. It should be:

GRANT ALL PRIVILEGES ON DATABASE jobzumodb TO jobzumojustin;


问:
p4 sync -p does not work under certain conditions in Perforce
I have a Perforce depot and connect to a replica server. Therefore I use p4 sync with the -p flag since replicas don't have a "have-list" of client workspaces. Example:

```<code>$ p4 sync -p //depot/path/to/branch/...@12345,12345
</code>```

Because I would like to apply all changes from that change list to my current workspace I add the ...@CHANGELISTID,CHANGELISTID expression to the end.

That works for all sync operations and all branches, but if the change list has a file that gets deleted, I receive this error:

```<code>//depot/path/to/branch/foo - can't sync -p a file that's synced
</code>```

But I want to delete it. Why does that not work?

From the documentation about p4 sync:

-p

Populate a client workspace, but do not update the have list. Any file
  that is already synced or opened is bypassed with a warning message.

This option is typically used for workspaces used in processes (such
  as certain build or publication environments) where there is no need
  to track the state of the workspace after it has first been synced.

I understand that the file got already synced, but in the given change list its state actually switched to "deleted". For reference, here is the output of p4 describe:

```<code>$ p4 describe -s 12345
Change 12345 by daniel@my_workspace on 2020/02/15 23:09:38

    delete test

Affected files ...

... //depot/path/to/branch/foo#2 delete
</code>```

答:
If you use p4 sync -p, you need to use it consistently -- state is not tracked by sync -p, and so if you try to sync -p a workspace that has existing sync state, it probably means that you're in a bad place, and sync -p will just refuse to do anything (issuing the error message that you saw).

If the error message is accurate, you have not been using p4 sync -p consistently (maybe you used this workspace with the main server?).  Here's how to tell:

```<code>p4 have
</code>```

If you've only ever been using p4 sync -p, this will return nothing.  If it returns a list of synced files, it means that at least some of your workspace state is being tracked, and when sync -p sees it, it will get concerned that it's making your local files inconsistent with that state.

To discard all your workspace state you can do:

```<code>p4 revert -k //...
p4 flush #none
</code>```

If p4 have says that you have no synced files but p4 sync -p says that you do, you may be encountering some sort of bug, and should contact support@perforce.com.

Body:
I have a Perforce depot and connect to a replica server. Therefore I use p4 sync with the -p flag since replicas don't have a "have-list" of client workspaces. Example:

$ p4 sync -p //depot/path/to/branch/...@12345,12345

Because I would like to apply all changes from that change list to my current workspace I add the ...@CHANGELISTID,CHANGELISTID expression to the end.

That works for all sync operations and all branches, but if the change list has a file that gets deleted, I receive this error:

//depot/path/to/branch/foo - can't sync -p a file that's synced

But I want to delete it. Why does that not work?

From the documentation about p4 sync:

-p

Populate a client workspace, but do not update the have list. Any file
  that is already synced or opened is bypassed with a warning message.

This option is typically used for workspaces used in processes (such
  as certain build or publication environments) where there is no need
  to track the state of the workspace after it has first been synced.

I understand that the file got already synced, but in the given change list its state actually switched to "deleted". For reference, here is the output of p4 describe:

$ p4 describe -s 12345
Change 12345 by daniel@my_workspace on 2020/02/15 23:09:38

    delete test

Affected files ...

... //depot/path/to/branch/foo#2 delete

Body:
If you use p4 sync -p, you need to use it consistently -- state is not tracked by sync -p, and so if you try to sync -p a workspace that has existing sync state, it probably means that you're in a bad place, and sync -p will just refuse to do anything (issuing the error message that you saw).

If the error message is accurate, you have not been using p4 sync -p consistently (maybe you used this workspace with the main server?).  Here's how to tell:

p4 have

If you've only ever been using p4 sync -p, this will return nothing.  If it returns a list of synced files, it means that at least some of your workspace state is being tracked, and when sync -p sees it, it will get concerned that it's making your local files inconsistent with that state.

To discard all your workspace state you can do:

p4 revert -k //...
p4 flush #none

If p4 have says that you have no synced files but p4 sync -p says that you do, you may be encountering some sort of bug, and should contact support@perforce.com.


问:
Why does the "for" loop skip elements from a list?
I was doing a kind of simple Python exercise, the idea was to create a function that adds the numbers of a list. The problem is that when I run it the for loop skips several integers and I don't know why.

```<code>def simplearraysum(ar):
    sum = 0
    for number in ar:
        sum = sum + number
        ar.remove(number)
    return sum

list = [1, 2, 3, 4, 10, 11]

print(simplearraysum(list))
</code>```

The output is 14, but it should be 31.

答:
You should not modifying the list when it is being iterated. The for loop will take care of the elements in the list. Just comment the line and you will get the correct output:

def simplearraysum(ar):
    sum = 0
    for number in ar:
        sum = sum + number
        #ar.remove(number)
    return sum

list = [1, 2, 3, 4, 10, 11]

print(simplearraysum(list))

```

Body:
I was doing a kind of simple Python exercise, the idea was to create a function that adds the numbers of a list. The problem is that when I run it the for loop skips several integers and I don't know why.

def simplearraysum(ar):
    sum = 0
    for number in ar:
        sum = sum + number
        ar.remove(number)
    return sum

list = [1, 2, 3, 4, 10, 11]

print(simplearraysum(list))

The output is 14, but it should be 31.


问:
Is there any way to call a specific variable based on user input?
I want to be able to call a certain variable based off which variable the user asked for.
I'm aware I can use if/else statements but I feel like there's a better way. In the last line of my code, I want the input variables in the curly braces to complete the variable call.
Sorry if this was a poor explanation as it's hard to explain.</p>

```<code>class Bed:
    def __init__(self, size, color, price):
        self.size = size
        self.color = color
        self.price = price

    def bed_size(self):
        print('This bed is {}'.format(self.size))

    def bed_color(self):
        print('This bed is {}'.format(self.color))

    def bed_price(self):
        print('This bed is {}'.format(self.price))

king_bed = Bed('very big', 'turquoise', '$1000')
queen_bed = Bed("medium size", 'magenta', '$700')
twin_bed = Bed('quite small', 'azure', '$400')

bed = input('Which of our fine beds would you like to gain more knowledge of? The king, queen or twin bed?')
attribute = input("Would you like to know the price, size or color?")

{bed}_bed.bed_{attribute}()
</code>```

答:
You can use exec(), it will convert a string to a python code.

Example 1:

```<code>string = "print('Hello world')"
exec(string)
</code>```

Output:

```<code>Hello world
</code>```

Example 2:

```<code>num = input("Enter your number: ")
exec("result = %s + 12")
print("The answer is " + result)
</code>```

Output:

```<code>Enter your number: 6
The answer is 18
</code>```

Body:
I want to be able to call a certain variable based off which variable the user asked for.
I'm aware I can use if/else statements but I feel like there's a better way. In the last line of my code, I want the input variables in the curly braces to complete the variable call.
Sorry if this was a poor explanation as it's hard to explain.

class Bed:
    def __init__(self, size, color, price):
        self.size = size
        self.color = color
        self.price = price

    def bed_size(self):
        print('This bed is {}'.format(self.size))

    def bed_color(self):
        print('This bed is {}'.format(self.color))

    def bed_price(self):
        print('This bed is {}'.format(self.price))

king_bed = Bed('very big', 'turquoise', '$1000')
queen_bed = Bed("medium size", 'magenta', '$700')
twin_bed = Bed('quite small', 'azure', '$400')

bed = input('Which of our fine beds would you like to gain more knowledge of? The king, queen or twin bed?')
attribute = input("Would you like to know the price, size or color?")

{bed}_bed.bed_{attribute}()

Body:
You can use exec(), it will convert a string to a python code.

Example 1:

string = "print('Hello world')"
exec(string)

Output:

Hello world

Example 2:

num = input("Enter your number: ")
exec("result = %s + 12")
print("The answer is " + result)

Output:

Enter your number: 6
The answer is 18


问:
Execute tregsvr.exe through Delphi with parameters
I am using the tregsvr.exe program that comes with Delphi to register an OCX.

The reason for using this program instead of regsrv32.exe is that a -c parameter can be passed which would allow registration only for the current user.

I execute the program through the ExecAndWait() function, copied below. It uses ShellExecuteEx() (instead of CreateProcess()), precisely because (as long as I don't manage to pass the parameter for current user) I must ask for elevation and this is done by passing the boolean Adm which fixes 'runas' (I read about an alternative way with the app manifest, but did not manage to get it working, maybe that is for another question).

function ExecAndWait(const ExecuteFile, ParamString : string; Adm: boolean): boolean;
var
  SEInfo: TShellExecuteInfo;
  ExitCode: DWORD;
begin
  FillChar(SEInfo, SizeOf(SEInfo), 0);
  SEInfo.cbSize := SizeOf(TShellExecuteInfo);
  with SEInfo do
  begin
    fMask := SEE_MASK_NOCLOSEPROCESS;
    Wnd := Application.Handle;
    lpFile := PChar(ExecuteFile);
    lpParameters := PChar(ParamString);
    If Adm then lpVerb:='runas';
    nShow := SW_HIDE;
  end;
  if ShellExecuteEx(@SEInfo) then
  begin
    repeat
      Application.ProcessMessages;
      GetExitCodeProcess(SEInfo.hProcess, ExitCode);
    until (ExitCode = STILL_ACTIVE) or Application.Terminated;
    Result:=True;
  end
  else Result:=False;
end;
```

<p>In this example of usage, the variable <code>Path</code> is the full path to <code>tregsvr.exe</code> and <code>Server</code> is the full path to the OCX. It works well (it does the job of registration):</p>

<pre class="lang-pascal prettyprint-override"><code>ExecandWait(Path,Chr(9)+Server+Chr(9), True);
</code>```

But my problem comes when I try to pass -c or other parameters, like in any of these attempts, where the function is unsuccessful:

ExecandWait(Path,'-c '+Chr(9)+Server+Chr(9), True);
ExecandWait(Path,'\c '+Chr(9)+Server+Chr(9), True);
```

答:
Your Chr(9)+Server+Chr(9) is almost certainly incorrect, in a minor and a major way:

The minor problem: Chr(9) is a tab. While that is a perfectly legitimate whitespace character, it's rather uncommon to encounter it as a part of a command line and as a result, I would not be surprised if the application you are trying to run failed to process it correctly.

The major problem: If Server contains spaces, you will actually pass multiple command line arguments to tregsvr.exe rather than one argument, and quite unsurprisingly tregsrv.exe will not be able to understand them.

Solution: Put the argument into quotes to signal that it is actually one argument, not many: AnsiQuotedStr(Server, '"').

Body:
I am using the tregsvr.exe program that comes with Delphi to register an OCX.

The reason for using this program instead of regsrv32.exe is that a -c parameter can be passed which would allow registration only for the current user.

I execute the program through the ExecAndWait() function, copied below. It uses ShellExecuteEx() (instead of CreateProcess()), precisely because (as long as I don't manage to pass the parameter for current user) I must ask for elevation and this is done by passing the boolean Adm which fixes 'runas' (I read about an alternative way with the app manifest, but did not manage to get it working, maybe that is for another question).

function ExecAndWait(const ExecuteFile, ParamString : string; Adm: boolean): boolean;
var
  SEInfo: TShellExecuteInfo;
  ExitCode: DWORD;
begin
  FillChar(SEInfo, SizeOf(SEInfo), 0);
  SEInfo.cbSize := SizeOf(TShellExecuteInfo);
  with SEInfo do
  begin
    fMask := SEE_MASK_NOCLOSEPROCESS;
    Wnd := Application.Handle;
    lpFile := PChar(ExecuteFile);
    lpParameters := PChar(ParamString);
    If Adm then lpVerb:='runas';
    nShow := SW_HIDE;
  end;
  if ShellExecuteEx(@SEInfo) then
  begin
    repeat
      Application.ProcessMessages;
      GetExitCodeProcess(SEInfo.hProcess, ExitCode);
    until (ExitCode = STILL_ACTIVE) or Application.Terminated;
    Result:=True;
  end
  else Result:=False;
end;

In this example of usage, the variable Path is the full path to tregsvr.exe and Server is the full path to the OCX. It works well (it does the job of registration):

ExecandWait(Path,Chr(9)+Server+Chr(9), True);

But my problem comes when I try to pass -c or other parameters, like in any of these attempts, where the function is unsuccessful:

ExecandWait(Path,'-c '+Chr(9)+Server+Chr(9), True);
ExecandWait(Path,'\c '+Chr(9)+Server+Chr(9), True);


问:
What it does when we write for(;;) ? What does the double semicolon in the for loop does?
And also only one semi colon inside the for loop in the given code?
Without closing the loop it writes another statement with scope resolution. I would be very thankful if you answer my queries.</p>

```<code>class D : public A,B,C
{
    int val;
    public:

        D()
        {
            val=1;
        }

        void update_val(int new_val)
        {
            for(;new_val%2==0;new_val/=2)A::func(val);
            for(;new_val%3==0;new_val/=3)B::func(val);
            for(;new_val%5==0;new_val/=5)C::func(val);
        }

        void check(int);
};
</code>```

答:
What does the double semicolon in the for loop does?

for statement has this syntax:

```<code>for( initialization ; condition ; increment ) body;
</code>```

Any part can be ommited but you must keep semicolon. So when you write:

```<code>for(;;) body;
</code>```

it means that all three parts are omitted, but required by syntax semicolons are still there.

What it does when we write for(;;) ?

It is equal to:

```<code>while( true )
</code>```

In this statement:

```<code>for(;new_val%2==0;new_val/=2)A::func(val);
</code>```

only first part - the initialization is skipped, but semicolon is still there.

Note that since C++11 there is another syntax is available - for range loop when instead of 2 semicolons you have only one colon:

```<code>for( int i : int_array ) do_something( i );
</code>```

Body:
And also only one semi colon inside the for loop in the given code?
Without closing the loop it writes another statement with scope resolution. I would be very thankful if you answer my queries.

class D : public A,B,C
{
    int val;
    public:

        D()
        {
            val=1;
        }

        void update_val(int new_val)
        {
            for(;new_val%2==0;new_val/=2)A::func(val);
            for(;new_val%3==0;new_val/=3)B::func(val);
            for(;new_val%5==0;new_val/=5)C::func(val);
        }

        void check(int);
};

Body:
What does the double semicolon in the for loop does?

for statement has this syntax:

for( initialization ; condition ; increment ) body;

Any part can be ommited but you must keep semicolon. So when you write:

for(;;) body;

it means that all three parts are omitted, but required by syntax semicolons are still there.

What it does when we write for(;;) ?

It is equal to:

while( true )

In this statement:

for(;new_val%2==0;new_val/=2)A::func(val);

only first part - the initialization is skipped, but semicolon is still there.

Note that since C++11 there is another syntax is available - for range loop when instead of 2 semicolons you have only one colon:

for( int i : int_array ) do_something( i );


问:
Writing custom validator in Rails 3
I'm trying to write a custom validator that will check for the number of words entered into a text field.

I was trying to follow the example in railscasts episode 211 - http://railscasts.com/episodes/211-validations-in-rails-3

So I made a file /lib/word_limit_validator.rb and copied in the same code from the tutorial. I know that this code doesn't count the number of words, I am just trying to use it because I know how it is supposed to behave.

```<code>class WordLimitValidator < ActiveModel::EachValidator
  def validate_each(object, attribute, value)
    unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
      object.errors[attribute] << (options[:message] || "is not formatted properly")
    end
  end
end
</code>```

Here's the line I used in my validation:

```<code>  validates :body, :presence => true,
                   :word_limit => true
</code>```

When I tried to load the form I got the following error:

Unknown validator: 'word_limit'

How do I get rails to recognize my validator?

System spec:
Mac OS 10.6.7
Rails 3.0.4
ruby 1.9.2p136

答:
Files in lib/ aren't autoloaded anymore in Rails.  So, you have a few options.

You can add lib to your autoload paths in your application.rb:

config.autoload_paths += %W( #{config.root}/lib )

You can include by adding file with something like this to config/initializers:
require File.join( Rails.root, 'lib', 'word_limit_validator')

If you only need it one place, you can just put it in the same file as your model.

Title: Writing custom validator in Rails 3

Body:
I'm trying to write a custom validator that will check for the number of words entered into a text field.

I was trying to follow the example in railscasts episode 211 - http://railscasts.com/episodes/211-validations-in-rails-3

So I made a file /lib/word_limit_validator.rb and copied in the same code from the tutorial. I know that this code doesn't count the number of words, I am just trying to use it because I know how it is supposed to behave.

class WordLimitValidator < ActiveModel::EachValidator
  def validate_each(object, attribute, value)
    unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
      object.errors[attribute] << (options[:message] || "is not formatted properly")
    end
  end
end

Here's the line I used in my validation:

  validates :body, :presence => true,
                   :word_limit => true

When I tried to load the form I got the following error:

Unknown validator: 'word_limit'

How do I get rails to recognize my validator?

System spec:
Mac OS 10.6.7
Rails 3.0.4
ruby 1.9.2p136


问:
Spinner won't display string entries
My program should use a spinner to show a list of color names, and have the background color of it. For example in the image shown, the color red should have a black text displayed saying "Red" to specify it.
https://i.stack.imgur.com/BT0dW.jpg

I have android:entries="@array/myStrings" that shows the first color's text (without color, plain white background) on design mode, but once I run the program, the text does not display for any of the colors.

strings.xml

```<code><resources>
    <string name="app_name">Color Activity</string>
    <string-array name="myStrings">
        <item>Silver</item>
        <item>Pink</item>
        <item>Red</item>
        <item>Orange</item>
        <item>Yellow</item>
        <item>Green</item>
        <item>Blue</item>
        <item>Indigo</item>
        <item>Violet</item>
        <item>Brown</item>
    </string-array>
</resources>
</code>```

colors.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#008577</color>
    <color name="colorPrimaryDark">#00574B</color>
    <color name="colorAccent">#D81B60</color>

    <color name="silver" type="color">#c0c0c0</color>
    <color name="pink" type="color">#ffc0cb</color>
    <color name="red" type="color">#ff0000</color>
    <color name="orange" type="color">#ffa500</color>
    <color name="yellow" type="color">#ffff00</color>
    <color name="green" type="color">#00ff00</color>
    <color name="blue" type="color">#0000ff</color>
    <color name="indigo" type="color">#4b0082</color>
    <color name="violet" type="color">#7f00ff</color>
    <color name="brown" type="color">#654321</color>
    <color name="white" type="color">#FFFFFF</color>
    <integer-array name="myColors">
        <item>@color/silver</item>
        <item>@color/pink</item>
        <item>@color/red</item>
        <item>@color/orange</item>
        <item>@color/yellow</item>
        <item>@color/green</item>
        <item>@color/blue</item>
        <item>@color/indigo</item>
        <item>@color/violet</item>
        <item>@color/brown</item>
    </integer-array>

</resources>
</code>```

MainActivity

```<code>import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Color;
import android.media.session.PlaybackState;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;

public class ColorActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        final View newBackground;

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Spinner spinner = findViewById(R.id.spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.myColors, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(
                android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(new ColorAdapter(this));
        newBackground = this.getWindow().getDecorView();

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                ArrayList<Integer> colors;
                colors = new ArrayList<Integer>();
                int retrieve []= getResources().getIntArray(R.array.myColors);
                for(int i:retrieve)
                {
                    colors.add(i);
                }

                if(position == 0){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.silver);
                }else if(position == 1){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.pink);
                }else if(position == 2){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.red);

                }else if(position == 3){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.orange);
                }else if(position == 4){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.yellow);
                }else if(position == 5){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.green);
                }else if(position == 6){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.blue);
                }else if(position == 7){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.indigo);
                }else if(position == 8){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.violet);
                }else if(position == 9){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.brown);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

}
</code>```

Color Adapter:

```<code>import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class ColorAdapter extends BaseAdapter {
    ArrayList<Integer> colors;
    Context context;

    public ColorAdapter(Context context){

        this.context=context;
        colors = new ArrayList<Integer>();
        int retrieve []=context.getResources().getIntArray(R.array.myColors);

        for(int i:retrieve)
        {
            colors.add(i);
        }
    }
    @Override
    public int getCount() {
        return colors.size();
    }

    @Override
    public Object getItem(int args) {
        return colors.get(args);
    }

    @Override
    public long getItemId(int args) {
        return args;
    }

    public String getElementFromColors(int position){
        String retrieve []=context.getResources().getStringArray(R.array.myColors);
        return retrieve[position];
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater=LayoutInflater.from(context);
        convertView=inflater.inflate(android.R.layout.simple_spinner_dropdown_item, null);
        TextView txv=(TextView)convertView.findViewById(android.R.id.text1);
        txv.setBackgroundColor(colors.get(position));
        txv.setTextSize(20f);
        txv.setText(getElementFromColors(position));
        return convertView;
    }

}
</code>```

答:
You just have a miss-typing of R.array.myColors in your adapter instead of R.array.myStrings

To Solve this, replace below line of code within getElementFromColors() method of your ColorAdapter

```<code>String retrieve[] = context.getResources().getStringArray(R.array.myColors);
</code>```

with:

```<code>String retrieve[] = context.getResources().getStringArray(R.array.myStrings);
</code>```

Title: Spinner won't display string entries

Body:
My program should use a spinner to show a list of color names, and have the background color of it. For example in the image shown, the color red should have a black text displayed saying "Red" to specify it.
https://i.stack.imgur.com/BT0dW.jpg

I have android:entries="@array/myStrings" that shows the first color's text (without color, plain white background) on design mode, but once I run the program, the text does not display for any of the colors.

strings.xml

<resources>
    <string name="app_name">Color Activity</string>
    <string-array name="myStrings">
        <item>Silver</item>
        <item>Pink</item>
        <item>Red</item>
        <item>Orange</item>
        <item>Yellow</item>
        <item>Green</item>
        <item>Blue</item>
        <item>Indigo</item>
        <item>Violet</item>
        <item>Brown</item>
    </string-array>
</resources>

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#008577</color>
    <color name="colorPrimaryDark">#00574B</color>
    <color name="colorAccent">#D81B60</color>

    <color name="silver" type="color">#c0c0c0</color>
    <color name="pink" type="color">#ffc0cb</color>
    <color name="red" type="color">#ff0000</color>
    <color name="orange" type="color">#ffa500</color>
    <color name="yellow" type="color">#ffff00</color>
    <color name="green" type="color">#00ff00</color>
    <color name="blue" type="color">#0000ff</color>
    <color name="indigo" type="color">#4b0082</color>
    <color name="violet" type="color">#7f00ff</color>
    <color name="brown" type="color">#654321</color>
    <color name="white" type="color">#FFFFFF</color>
    <integer-array name="myColors">
        <item>@color/silver</item>
        <item>@color/pink</item>
        <item>@color/red</item>
        <item>@color/orange</item>
        <item>@color/yellow</item>
        <item>@color/green</item>
        <item>@color/blue</item>
        <item>@color/indigo</item>
        <item>@color/violet</item>
        <item>@color/brown</item>
    </integer-array>

</resources>

MainActivity

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Color;
import android.media.session.PlaybackState;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;

public class ColorActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        final View newBackground;

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Spinner spinner = findViewById(R.id.spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.myColors, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(
                android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(new ColorAdapter(this));
        newBackground = this.getWindow().getDecorView();

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                ArrayList<Integer> colors;
                colors = new ArrayList<Integer>();
                int retrieve []= getResources().getIntArray(R.array.myColors);
                for(int i:retrieve)
                {
                    colors.add(i);
                }

                if(position == 0){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.silver);
                }else if(position == 1){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.pink);
                }else if(position == 2){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.red);

                }else if(position == 3){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.orange);
                }else if(position == 4){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.yellow);
                }else if(position == 5){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.green);
                }else if(position == 6){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.blue);
                }else if(position == 7){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.indigo);
                }else if(position == 8){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.violet);
                }else if(position == 9){
                    view.setBackgroundResource(R.color.white);
                    newBackground.setBackgroundResource(R.color.brown);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

}

Color Adapter:

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class ColorAdapter extends BaseAdapter {
    ArrayList<Integer> colors;
    Context context;

    public ColorAdapter(Context context){

        this.context=context;
        colors = new ArrayList<Integer>();
        int retrieve []=context.getResources().getIntArray(R.array.myColors);

        for(int i:retrieve)
        {
            colors.add(i);
        }
    }
    @Override
    public int getCount() {
        return colors.size();
    }

    @Override
    public Object getItem(int args) {
        return colors.get(args);
    }

    @Override
    public long getItemId(int args) {
        return args;
    }

    public String getElementFromColors(int position){
        String retrieve []=context.getResources().getStringArray(R.array.myColors);
        return retrieve[position];
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater=LayoutInflater.from(context);
        convertView=inflater.inflate(android.R.layout.simple_spinner_dropdown_item, null);
        TextView txv=(TextView)convertView.findViewById(android.R.id.text1);
        txv.setBackgroundColor(colors.get(position));
        txv.setTextSize(20f);
        txv.setText(getElementFromColors(position));
        return convertView;
    }

}

Body:
You just have a miss-typing of R.array.myColors in your adapter instead of R.array.myStrings

To Solve this, replace below line of code within getElementFromColors() method of your ColorAdapter

String retrieve[] = context.getResources().getStringArray(R.array.myColors);

with:

String retrieve[] = context.getResources().getStringArray(R.array.myStrings);


问:
Why isn't this factorial finding algorithm O(n!) run-time complexity?
I discovered this issue by implemented the algorithm from this post: Example of O(n!)?

I tried counting the operations though, and the algorithm loops 64 times when calculating 4! (which is 24).

Is there something I'm missing? Or does this algorithm really just have a run-time complexity that is not O(n!)

var operations = 0;

function factorial(n) {
    for (let i = 0; i < n; i++) {
        operations++;
        factorial(n - 1);
    }
}

console.log(factorial(4))
console.log('operations: ', operations) // prints 64 operations```

答:
There is probably a good theoretical analysis, but here is an empirical one.

I ran the program for numbers 0 to 12 and tracked operations. Notice that very quickly the operations tend to be really close to n times the previous entry. And the ratio of operations to n! appears to tend to e. Thus, if the limit of operations is e (or some constant) times n!, we are O(n!). We need not = n! to make that so.