问:
Atmosphere is unable to configure JSR-356
I created Java web application and trying to force atmosphere to use JSR-356 since, as I understood, it's the only way to use original javax.servlet.HttpSession from AtmosphereResource object.

When I deploy my application to Jetty (v. 9.3.7), I get the following errors:

```<code>16:45:16.535 [Scanner-1] ERROR org.atmosphere.util.IOUtils -
java.lang.IllegalStateException: Unable to configure jsr356 at that stage. No Servlet associated with Key[type=org.atmosphere.guice.AtmosphereGuiceServlet, annotation=[none]]
    at org.atmosphere.util.IOUtils.guestRawServletPath(IOUtils.java:274) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.util.IOUtils.guestServletPath(IOUtils.java:248) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.container.JSR356AsyncSupport.<init>(JSR356AsyncSupport.java:63) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.container.JSR356AsyncSupport.<init>(JSR356AsyncSupport.java:40) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) [na:1.8.0_74]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) [na:1.8.0_74]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) [na:1.8.0_74]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) [na:1.8.0_74]
    at org.atmosphere.cpr.DefaultAsyncSupportResolver.newCometSupport(DefaultAsyncSupportResolver.java:234) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.DefaultAsyncSupportResolver.resolveWebSocket(DefaultAsyncSupportResolver.java:306) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.DefaultAsyncSupportResolver.resolve(DefaultAsyncSupportResolver.java:292) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereFramework.autoDetectContainer(AtmosphereFramework.java:2082) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereFramework.init(AtmosphereFramework.java:914) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereFramework.init(AtmosphereFramework.java:838) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereFrameworkInitializer.configureFramework(AtmosphereFrameworkInitializer.java:75) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereServlet.configureFramework(AtmosphereServlet.java:84) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereServlet.configureFramework(AtmosphereServlet.java:80) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereServlet.init(AtmosphereServlet.java:75) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at com.google.inject.servlet.ServletDefinition.init(ServletDefinition.java:121) [guice-servlet-4.0.jar:na]
    at com.google.inject.servlet.ManagedServletPipeline.init(ManagedServletPipeline.java:82) [guice-servlet-4.0.jar:na]
    at com.google.inject.servlet.ManagedFilterPipeline.initPipeline(ManagedFilterPipeline.java:103) [guice-servlet-4.0.jar:na]
    at com.google.inject.servlet.GuiceFilter.init(GuiceFilter.java:220) [guice-servlet-4.0.jar:na]
    at org.eclipse.jetty.servlet.FilterHolder.initialize(FilterHolder.java:137) [jetty-servlet-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:856) [jetty-servlet-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:350) [jetty-servlet-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1379) [jetty-webapp-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1341) [jetty-webapp-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:772) [jetty-server-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:263) [jetty-servlet-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:517) [jetty-webapp-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68) [jetty-util-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:41) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:188) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:499) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:147) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.providers.ScanningAppProvider.fileAdded(ScanningAppProvider.java:180) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.providers.WebAppProvider.fileAdded(WebAppProvider.java:458) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.providers.ScanningAppProvider$1.fileAdded(ScanningAppProvider.java:64) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.util.Scanner.reportAddition(Scanner.java:610) [jetty-util-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.util.Scanner.reportDifferences(Scanner.java:529) [jetty-util-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.util.Scanner.scan(Scanner.java:392) [jetty-util-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.util.Scanner$1.run(Scanner.java:329) [jetty-util-9.3.7.v20160115.jar:9.3.7.v20160115]
    at java.util.TimerThread.mainLoop(Timer.java:555) [na:1.8.0_74]
    at java.util.TimerThread.run(Timer.java:505) [na:1.8.0_74]
16:45:16.536 [Scanner-1] ERROR o.a.cpr.DefaultAsyncSupportResolver - Real error: Unable to configure jsr356 at that stage
java.lang.IllegalStateException: Unable to configure jsr356 at that stage
    at org.atmosphere.util.IOUtils.guestRawServletPath(IOUtils.java:292) ~[atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.util.IOUtils.guestServletPath(IOUtils.java:248) ~[atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.container.JSR356AsyncSupport.<init>(JSR356AsyncSupport.java:63) ~[atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.container.JSR356AsyncSupport.<init>(JSR356AsyncSupport.java:40) ~[atmosphere-runtime-2.4.3.jar:2.4.3]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_74]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_74]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_74]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_74]
    at org.atmosphere.cpr.DefaultAsyncSupportResolver.newCometSupport(DefaultAsyncSupportResolver.java:234) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.DefaultAsyncSupportResolver.resolveWebSocket(DefaultAsyncSupportResolver.java:306) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.DefaultAsyncSupportResolver.resolve(DefaultAsyncSupportResolver.java:292) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereFramework.autoDetectContainer(AtmosphereFramework.java:2082) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereFramework.init(AtmosphereFramework.java:914) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereFramework.init(AtmosphereFramework.java:838) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereFrameworkInitializer.configureFramework(AtmosphereFrameworkInitializer.java:75) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereServlet.configureFramework(AtmosphereServlet.java:84) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereServlet.configureFramework(AtmosphereServlet.java:80) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereServlet.init(AtmosphereServlet.java:75) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at com.google.inject.servlet.ServletDefinition.init(ServletDefinition.java:121) [guice-servlet-4.0.jar:na]
    at com.google.inject.servlet.ManagedServletPipeline.init(ManagedServletPipeline.java:82) [guice-servlet-4.0.jar:na]
    at com.google.inject.servlet.ManagedFilterPipeline.initPipeline(ManagedFilterPipeline.java:103) [guice-servlet-4.0.jar:na]
    at com.google.inject.servlet.GuiceFilter.init(GuiceFilter.java:220) [guice-servlet-4.0.jar:na]
    at org.eclipse.jetty.servlet.FilterHolder.initialize(FilterHolder.java:137) [jetty-servlet-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:856) [jetty-servlet-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:350) [jetty-servlet-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1379) [jetty-webapp-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1341) [jetty-webapp-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:772) [jetty-server-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:263) [jetty-servlet-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:517) [jetty-webapp-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68) [jetty-util-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:41) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:188) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:499) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:147) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.providers.ScanningAppProvider.fileAdded(ScanningAppProvider.java:180) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.providers.WebAppProvider.fileAdded(WebAppProvider.java:458) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.providers.ScanningAppProvider$1.fileAdded(ScanningAppProvider.java:64) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.util.Scanner.reportAddition(Scanner.java:610) [jetty-util-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.util.Scanner.reportDifferences(Scanner.java:529) [jetty-util-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.util.Scanner.scan(Scanner.java:392) [jetty-util-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.util.Scanner$1.run(Scanner.java:329) [jetty-util-9.3.7.v20160115.jar:9.3.7.v20160115]
    at java.util.TimerThread.mainLoop(Timer.java:555) [na:1.8.0_74]
    at java.util.TimerThread.run(Timer.java:505) [na:1.8.0_74]
</code>```

If I force native API to take the precedence with the following code

```<code>params.put(ApplicationConfig.WEBSOCKET_SUPPRESS_JSR356, "true");
</code>```

then everything works fine.

Here is my deployment descriptor:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                             http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <listener>
        <listener-class>com.sample.guice.GuiceContextListener</listener-class>
    </listener>

    <filter>
        <filter-name>guiceFilter</filter-name>
        <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>guiceFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
</code>```

The module used to provide all the bindings:

```<code>public class ServerModule extends AbstractModule
{
    @Override
    protected void configure()
    {
        install(new ServletModule() {
            @Override
            protected void configureServlets()
            {
                Map<String, String> params = new HashMap<>();
                // params.put(ApplicationConfig.WEBSOCKET_SUPPRESS_JSR356, "true");
                serve("/atmosphere").with(AtmosphereGuiceServlet.class, params);
            }
        });
    }
}
</code>```

I omitted the class annotated with @ManagedService and some other code since there are no problems. As I said, everything works fine with native websocket API.

答:
the message:
Unable to configure jsr356 at that stage

means, that the jsr356 support needs to be added during ServletContextInitialization phase, the best in a ServletContextListener

my problem is that jetty 9.4 native websocket is not compatible with atmosphere anymore, on the other hand jsr356 is not compatible with guice

I managed to make jsr356 work with vaadin 8.8.1 and jetty 9.4, but it requires the VaadinServlet to be directly managed by Jetty. This doesn't work with Guice, which installs it's own GuiceFilter, and the servlets are not registered to Jetty directly.

look at JSR356WebsocketInitializer.initAtmosphereForVaadinServlet for more information

Body:
I created Java web application and trying to force atmosphere to use JSR-356 since, as I understood, it's the only way to use original javax.servlet.HttpSession from AtmosphereResource object.

When I deploy my application to Jetty (v. 9.3.7), I get the following errors:

16:45:16.535 [Scanner-1] ERROR org.atmosphere.util.IOUtils -
java.lang.IllegalStateException: Unable to configure jsr356 at that stage. No Servlet associated with Key[type=org.atmosphere.guice.AtmosphereGuiceServlet, annotation=[none]]
    at org.atmosphere.util.IOUtils.guestRawServletPath(IOUtils.java:274) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.util.IOUtils.guestServletPath(IOUtils.java:248) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.container.JSR356AsyncSupport.<init>(JSR356AsyncSupport.java:63) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.container.JSR356AsyncSupport.<init>(JSR356AsyncSupport.java:40) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) [na:1.8.0_74]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) [na:1.8.0_74]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) [na:1.8.0_74]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) [na:1.8.0_74]
    at org.atmosphere.cpr.DefaultAsyncSupportResolver.newCometSupport(DefaultAsyncSupportResolver.java:234) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.DefaultAsyncSupportResolver.resolveWebSocket(DefaultAsyncSupportResolver.java:306) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.DefaultAsyncSupportResolver.resolve(DefaultAsyncSupportResolver.java:292) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereFramework.autoDetectContainer(AtmosphereFramework.java:2082) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereFramework.init(AtmosphereFramework.java:914) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereFramework.init(AtmosphereFramework.java:838) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereFrameworkInitializer.configureFramework(AtmosphereFrameworkInitializer.java:75) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereServlet.configureFramework(AtmosphereServlet.java:84) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereServlet.configureFramework(AtmosphereServlet.java:80) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereServlet.init(AtmosphereServlet.java:75) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at com.google.inject.servlet.ServletDefinition.init(ServletDefinition.java:121) [guice-servlet-4.0.jar:na]
    at com.google.inject.servlet.ManagedServletPipeline.init(ManagedServletPipeline.java:82) [guice-servlet-4.0.jar:na]
    at com.google.inject.servlet.ManagedFilterPipeline.initPipeline(ManagedFilterPipeline.java:103) [guice-servlet-4.0.jar:na]
    at com.google.inject.servlet.GuiceFilter.init(GuiceFilter.java:220) [guice-servlet-4.0.jar:na]
    at org.eclipse.jetty.servlet.FilterHolder.initialize(FilterHolder.java:137) [jetty-servlet-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:856) [jetty-servlet-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:350) [jetty-servlet-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1379) [jetty-webapp-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1341) [jetty-webapp-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:772) [jetty-server-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:263) [jetty-servlet-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:517) [jetty-webapp-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68) [jetty-util-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:41) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:188) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:499) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:147) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.providers.ScanningAppProvider.fileAdded(ScanningAppProvider.java:180) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.providers.WebAppProvider.fileAdded(WebAppProvider.java:458) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.providers.ScanningAppProvider$1.fileAdded(ScanningAppProvider.java:64) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.util.Scanner.reportAddition(Scanner.java:610) [jetty-util-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.util.Scanner.reportDifferences(Scanner.java:529) [jetty-util-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.util.Scanner.scan(Scanner.java:392) [jetty-util-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.util.Scanner$1.run(Scanner.java:329) [jetty-util-9.3.7.v20160115.jar:9.3.7.v20160115]
    at java.util.TimerThread.mainLoop(Timer.java:555) [na:1.8.0_74]
    at java.util.TimerThread.run(Timer.java:505) [na:1.8.0_74]
16:45:16.536 [Scanner-1] ERROR o.a.cpr.DefaultAsyncSupportResolver - Real error: Unable to configure jsr356 at that stage
java.lang.IllegalStateException: Unable to configure jsr356 at that stage
    at org.atmosphere.util.IOUtils.guestRawServletPath(IOUtils.java:292) ~[atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.util.IOUtils.guestServletPath(IOUtils.java:248) ~[atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.container.JSR356AsyncSupport.<init>(JSR356AsyncSupport.java:63) ~[atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.container.JSR356AsyncSupport.<init>(JSR356AsyncSupport.java:40) ~[atmosphere-runtime-2.4.3.jar:2.4.3]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_74]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_74]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_74]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_74]
    at org.atmosphere.cpr.DefaultAsyncSupportResolver.newCometSupport(DefaultAsyncSupportResolver.java:234) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.DefaultAsyncSupportResolver.resolveWebSocket(DefaultAsyncSupportResolver.java:306) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.DefaultAsyncSupportResolver.resolve(DefaultAsyncSupportResolver.java:292) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereFramework.autoDetectContainer(AtmosphereFramework.java:2082) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereFramework.init(AtmosphereFramework.java:914) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereFramework.init(AtmosphereFramework.java:838) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereFrameworkInitializer.configureFramework(AtmosphereFrameworkInitializer.java:75) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereServlet.configureFramework(AtmosphereServlet.java:84) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereServlet.configureFramework(AtmosphereServlet.java:80) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at org.atmosphere.cpr.AtmosphereServlet.init(AtmosphereServlet.java:75) [atmosphere-runtime-2.4.3.jar:2.4.3]
    at com.google.inject.servlet.ServletDefinition.init(ServletDefinition.java:121) [guice-servlet-4.0.jar:na]
    at com.google.inject.servlet.ManagedServletPipeline.init(ManagedServletPipeline.java:82) [guice-servlet-4.0.jar:na]
    at com.google.inject.servlet.ManagedFilterPipeline.initPipeline(ManagedFilterPipeline.java:103) [guice-servlet-4.0.jar:na]
    at com.google.inject.servlet.GuiceFilter.init(GuiceFilter.java:220) [guice-servlet-4.0.jar:na]
    at org.eclipse.jetty.servlet.FilterHolder.initialize(FilterHolder.java:137) [jetty-servlet-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:856) [jetty-servlet-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:350) [jetty-servlet-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1379) [jetty-webapp-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1341) [jetty-webapp-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:772) [jetty-server-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:263) [jetty-servlet-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:517) [jetty-webapp-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68) [jetty-util-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:41) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:188) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:499) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:147) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.providers.ScanningAppProvider.fileAdded(ScanningAppProvider.java:180) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.providers.WebAppProvider.fileAdded(WebAppProvider.java:458) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.deploy.providers.ScanningAppProvider$1.fileAdded(ScanningAppProvider.java:64) [jetty-deploy-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.util.Scanner.reportAddition(Scanner.java:610) [jetty-util-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.util.Scanner.reportDifferences(Scanner.java:529) [jetty-util-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.util.Scanner.scan(Scanner.java:392) [jetty-util-9.3.7.v20160115.jar:9.3.7.v20160115]
    at org.eclipse.jetty.util.Scanner$1.run(Scanner.java:329) [jetty-util-9.3.7.v20160115.jar:9.3.7.v20160115]
    at java.util.TimerThread.mainLoop(Timer.java:555) [na:1.8.0_74]
    at java.util.TimerThread.run(Timer.java:505) [na:1.8.0_74]

If I force native API to take the precedence with the following code

params.put(ApplicationConfig.WEBSOCKET_SUPPRESS_JSR356, "true");

then everything works fine.

Here is my deployment descriptor:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                             http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <listener>
        <listener-class>com.sample.guice.GuiceContextListener</listener-class>
    </listener>

    <filter>
        <filter-name>guiceFilter</filter-name>
        <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>guiceFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

The module used to provide all the bindings:

public class ServerModule extends AbstractModule
{
    @Override
    protected void configure()
    {
        install(new ServletModule() {
            @Override
            protected void configureServlets()
            {
                Map<String, String> params = new HashMap<>();
                // params.put(ApplicationConfig.WEBSOCKET_SUPPRESS_JSR356, "true");
                serve("/atmosphere").with(AtmosphereGuiceServlet.class, params);
            }
        });
    }
}

I omitted the class annotated with @ManagedService and some other code since there are no problems. As I said, everything works fine with native websocket API.


来源: stackexchange

问:
React router and full page overlay transitions
I have a simple application setup so far uses react router and an external API. I have some post archives of different types and when a user requests a detail page the API makes a request, and if it gets a page displays it if not displays a 404.

I'm able to set up transition groups to do nice cross fades between these pages, however the designer wants to do something a bit more old fashioned. He wants to slide over a blank overlay over the page, then slide it off to reveal the new page. Ideally with the title of the new page in this overlay.

I can't find a way to handle doing this with a react however. If this wasn't react I might just animate over a div while loading the other pages entire HTML with JS and then swap the required content sections.

Im currently using React 16.3 with react router DOM 5.0

答:
You can do this with CSS keyframes

```<code>this.state = {
    visible: false
}

componentDidMount() {
      this.setState({visible: true})
}

  <div className={this.state.visible
                    ? "backdrop"
                    :  null}>
 </div>

.backdrop {
  z-index: 1;
  background-color: white;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  animation-name: animate-backdrop;
  animation-duration: 2s;
  animation-timing-function: linear;
}

@keyframes animate-backdrop {
  0% {
    transform: translateX(-100%);
  }

  100% {
    transform: translateX(0%);
  }
}
</code>```

Not sure what your skill level with CSS is, but z index 1 will make sure the backdrop is over all your content. The actual animating will be done with transform and translateX.

React Router doesnt have to play any part in this. You can do the animating in the component itself when the component first loads by changing the state of a property of visible from false to true, this will give that empty div the CSS classname which will trigger the animation.

So essentially when the component loads the state is changed and the animation will take place.

you did not provide your code, but the code here should be enough to allow you to implement that functionality.

ContentLicense: CC BY-SA 4.0

Body:
You can do this with CSS keyframes

this.state = {
    visible: false
}

componentDidMount() {
      this.setState({visible: true})
}

  <div className={this.state.visible
                    ? "backdrop"
                    :  null}>
 </div>

.backdrop {
  z-index: 1;
  background-color: white;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  animation-name: animate-backdrop;
  animation-duration: 2s;
  animation-timing-function: linear;
}

@keyframes animate-backdrop {
  0% {
    transform: translateX(-100%);
  }

  100% {
    transform: translateX(0%);
  }
}

Not sure what your skill level with CSS is, but z index 1 will make sure the backdrop is over all your content. The actual animating will be done with transform and translateX.

React Router doesnt have to play any part in this. You can do the animating in the component itself when the component first loads by changing the state of a property of visible from false to true, this will give that empty div the CSS classname which will trigger the animation.

So essentially when the component loads the state is changed and the animation will take place.

you did not provide your code, but the code here should be enough to allow you to implement that functionality.


问:
How to get first value by alphabet from array or order that array by alphabet?
I have character array with surnames

```<code>character(SNAME_LEN, kind=CH_) :: Surnames(SNAME_AMOUNT) = ""
</code>```

and I must to write minimal surname by alphabet to the file.

I can't to find function for my problem. Fortran has regular function MINVAL, but array for his must be INTEGER or REAL only.

Thanks for anything ideas :-)

UPD:
GFortran shows error

src/main.f90:73:22:

    write (*,*) MINVAL(Surnames(:))
                      1
Error: ‘array’ argument of ‘minval’ intrinsic at (1) must be INTEGER or REAL
```

<p>UPD2:
The main part of program</p>

<p>lr1.f90</p>

```program lr1_1

    implicit none
    integer, parameter      :: CH_= Selected_Char_Kind("ISO_10646")
    character(*), parameter :: E_ = "UTF-8"

    integer, parameter :: SNAME_AMOUNT = 23, SNAME_LEN = 15, TEL_LEN = 10

    character(:), allocatable :: input_file, output_file

    character(SNAME_LEN, kind=CH_) :: Surnames(SNAME_AMOUNT) = ""
    character(TEL_LEN, kind=CH_) :: Tel(SNAME_AMOUNT) = ""

    integer :: In, Out, IO, i, j

    input_file = "input.txt"
    output_file = "output.txt"

    open (file=input_file, encoding=E_, newunit=In)
       read (In, '(3(a), 3(a))', iostat=IO) (Surnames(i), Tel(i), i = 1, SNAME_AMOUNT)
    close (In)

    write (*,*) MINVAL(Surnames(:))

end program lr1_1
```

<p>input.txt</p>

```Дудиков         9111630001
Тихонов         9111630002
Степин          9111630003
Садовникова     9111630004
Воробъёва       9111630005
Дудиков         9111630006
Тихонов         9111630007
Степин          9111630008
Садовникова     9111630009
Воробъёва       9111630010
Петров          9111630011
Фёдоров         9111630012
Петров          9111630013
Воробъёва       9111630014
```

答:
The missing MINVAL for the character type was tracked in bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=36313 It is a new feature of Fortran 2003, in Fortran 95 these functions were only for real and integer. Update your compiler to GCC version 8 or more recent.

```<code>> cat minvalchar.f90
print *,minval(["a"])
end
> gfortran-8 minvalchar.f90
> ./a.out
 a
</code>```

Be aware that this method may not use the collating sequence you might need for your language:

```<code>print *,maxval([character(4) :: "a","b","c","č","d","ď","e","é","f"])
end

> ./a.out
 ď
</code>```

Especially considering that the file you now posted uses Cyrillic. I have no idea if the characters you need are correctly ordered in Unicode. You might need to use USC-4 in Fortran and even then the order may be unsuitable.

Body:
I have character array with surnames

character(SNAME_LEN, kind=CH_) :: Surnames(SNAME_AMOUNT) = ""

and I must to write minimal surname by alphabet to the file.

I can't to find function for my problem. Fortran has regular function MINVAL, but array for his must be INTEGER or REAL only.

Thanks for anything ideas :-)

UPD:
GFortran shows error

src/main.f90:73:22:

    write (*,*) MINVAL(Surnames(:))
                      1
Error: ‘array’ argument of ‘minval’ intrinsic at (1) must be INTEGER or REAL

UPD2:
The main part of program

lr1.f90

program lr1_1

    implicit none
    integer, parameter      :: CH_= Selected_Char_Kind("ISO_10646")
    character(*), parameter :: E_ = "UTF-8"

    integer, parameter :: SNAME_AMOUNT = 23, SNAME_LEN = 15, TEL_LEN = 10

    character(:), allocatable :: input_file, output_file

    character(SNAME_LEN, kind=CH_) :: Surnames(SNAME_AMOUNT) = ""
    character(TEL_LEN, kind=CH_) :: Tel(SNAME_AMOUNT) = ""

    integer :: In, Out, IO, i, j

    input_file = "input.txt"
    output_file = "output.txt"

    open (file=input_file, encoding=E_, newunit=In)
       read (In, '(3(a), 3(a))', iostat=IO) (Surnames(i), Tel(i), i = 1, SNAME_AMOUNT)
    close (In)

    write (*,*) MINVAL(Surnames(:))

end program lr1_1

input.txt

Дудиков         9111630001
Тихонов         9111630002
Степин          9111630003
Садовникова     9111630004
Воробъёва       9111630005
Дудиков         9111630006
Тихонов         9111630007
Степин          9111630008
Садовникова     9111630009
Воробъёва       9111630010
Петров          9111630011
Фёдоров         9111630012
Петров          9111630013
Воробъёва       9111630014

Body:
The missing MINVAL for the character type was tracked in bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=36313 It is a new feature of Fortran 2003, in Fortran 95 these functions were only for real and integer. Update your compiler to GCC version 8 or more recent.

> cat minvalchar.f90
print *,minval(["a"])
end
> gfortran-8 minvalchar.f90
> ./a.out
 a

Be aware that this method may not use the collating sequence you might need for your language:

print *,maxval([character(4) :: "a","b","c","č","d","ď","e","é","f"])
end

> ./a.out
 ď

Especially considering that the file you now posted uses Cyrillic. I have no idea if the characters you need are correctly ordered in Unicode. You might need to use USC-4 in Fortran and even then the order may be unsuitable.


问:
JSON to CSV Conversion in Python
There're lots of questions regarding JSON to CSV Conversion in Python , but unfortunately couldn't solve my problem.

I've this simple simple JSON Data which is in a file and looks like this after loading.

Raw data in single line [I've structured this to understand better]:

```<code>{
    "t_id":"80740185.1558980000000.120184.121164",
    "s_id":"80740185",
    "pt_slot":"null:null",
    "ch_id":1,"o_id":121164,"c_id":120184,
    "msg_type":1,
    "amd":"{
                \"msg\":\" some Bengali text\",
                \"mask\":\"1GB_OFFER\",
                \"ec\":\"1\",
                \"time-out\":\"0\",
                \"validity\":\"30052019 000000\"
           }",
    "time":1558960217731,
    "dlr":"1",
    "msisdn":"xxxxx",
    "entity":1
}
</code>```

**After loading to JSON formated data looks like below **

```<code>{
    u't_id': u'80740185.1558980000000.120184.121164',
    u'c_id': 120184,
    u'msg_type': 1,
    u'dlr': u'1',
    u'msisdn': u'xxxxxxxx',
    u'amd': u'{
                "msg":" \u0986\u099c \u09b0\u09be\u09a4 \u09e7\u09e8\u099f\u09be\u09b0 \u09ae\u09a7\u09cd\u09af\u09c7 *21291*609# \u09a1\u09be\u09df\u09be\u09b2\u09c7 \u0995\u09bf\u09a8\u09c1\u09a8 \u09e7\u099c\u09bf\u09ac\u09bf \u09ef\u099f\u09be\u0995\u09be\u09a4\u09c7 (\u09e9\u09a6\u09bf\u09a8)",
                "mask":"1GB_OFFER",
                "ec":"1",
                "time-out":"0",
                "validity":"30052019 000000"
               }',
    u'entity': 1,
    u's_id': u'80740185',
    u'ch_id': 1,
    u'time': 1558960217731,
    u'pt_slot': u'null:null',
    u'o_id': 121164
}
</code>```

I've above very simple JSON Data which I'm trying to convert to CSV data. But getting below error.

Here is my code

```<code>#!/usr/bin/python

import json
import csv

def write_sms_dat_to_csv_file():
    f = csv.writer(open('csv_data.txt','wb+'),delimiter = '|')
    with open('test.dat') as fh:
            data = json.load(fh)

    for dt in data:
            f.writerow([dt['c_id'],dt['msisdn'],dt["amd"]["mask"]])

if __name__=="__main__":
    write_sms_dat_to_csv_file()
</code>```

Error Message

```<code>Traceback (most recent call last):
File "./sms_data_read.py", line 16, in <module>
write_sms_dat_to_csv_file()
File "./sms_data_read.py", line 13, in write_sms_dat_to_csv_file
f.writerow([dt['c_id'],dt['msisdn'],dt['amd']['mask']])
TypeError: string indices must be integers
</code>```

Removing for loops with below statement gives same error:

```<code>f.writerow([data['c_id'],data['msisdn'],data['amd']["mask"]])
</code>```

Title: JSON to CSV Conversion in Python

Body:
There're lots of questions regarding JSON to CSV Conversion in Python , but unfortunately couldn't solve my problem.

I've this simple simple JSON Data which is in a file and looks like this after loading.

Raw data in single line [I've structured this to understand better]:

{
    "t_id":"80740185.1558980000000.120184.121164",
    "s_id":"80740185",
    "pt_slot":"null:null",
    "ch_id":1,"o_id":121164,"c_id":120184,
    "msg_type":1,
    "amd":"{
                \"msg\":\" some Bengali text\",
                \"mask\":\"1GB_OFFER\",
                \"ec\":\"1\",
                \"time-out\":\"0\",
                \"validity\":\"30052019 000000\"
           }",
    "time":1558960217731,
    "dlr":"1",
    "msisdn":"xxxxx",
    "entity":1
}

**After loading to JSON formated data looks like below **

{
    u't_id': u'80740185.1558980000000.120184.121164',
    u'c_id': 120184,
    u'msg_type': 1,
    u'dlr': u'1',
    u'msisdn': u'xxxxxxxx',
    u'amd': u'{
                "msg":" \u0986\u099c \u09b0\u09be\u09a4 \u09e7\u09e8\u099f\u09be\u09b0 \u09ae\u09a7\u09cd\u09af\u09c7 *21291*609# \u09a1\u09be\u09df\u09be\u09b2\u09c7 \u0995\u09bf\u09a8\u09c1\u09a8 \u09e7\u099c\u09bf\u09ac\u09bf \u09ef\u099f\u09be\u0995\u09be\u09a4\u09c7 (\u09e9\u09a6\u09bf\u09a8)",
                "mask":"1GB_OFFER",
                "ec":"1",
                "time-out":"0",
                "validity":"30052019 000000"
               }',
    u'entity': 1,
    u's_id': u'80740185',
    u'ch_id': 1,
    u'time': 1558960217731,
    u'pt_slot': u'null:null',
    u'o_id': 121164
}

I've above very simple JSON Data which I'm trying to convert to CSV data. But getting below error.

Here is my code

#!/usr/bin/python

import json
import csv

def write_sms_dat_to_csv_file():
    f = csv.writer(open('csv_data.txt','wb+'),delimiter = '|')
    with open('test.dat') as fh:
            data = json.load(fh)

    for dt in data:
            f.writerow([dt['c_id'],dt['msisdn'],dt["amd"]["mask"]])

if __name__=="__main__":
    write_sms_dat_to_csv_file()

Error Message

Traceback (most recent call last):
File "./sms_data_read.py", line 16, in <module>
write_sms_dat_to_csv_file()
File "./sms_data_read.py", line 13, in write_sms_dat_to_csv_file
f.writerow([dt['c_id'],dt['msisdn'],dt['amd']['mask']])
TypeError: string indices must be integers

Removing for loops with below statement gives same error:

f.writerow([data['c_id'],data['msisdn'],data['amd']["mask"]])

Body:
Something is a bit odd about your source JSON encoding, but if the structure is consistent with what you've provided, then you just need to parse the value in dt['amd'] as well:

$ python
Python 3.7.2 (default, Dec 27 2018, 07:35:06)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> json_string = '''
... [
...     {
...         "t_id": "80740185.1558980000000.120184.121164",
...         "s_id": "80740185",
...         "pt_slot": "null:null",
...         "ch_id": 1,
...         "o_id": 121164,
...         "c_id": 120184,
...         "msg_type": 1,
...         "amd": "{\\"msg\\": \\" some Bengali text\\", \\"mask\\": \\"1GB_OFFER\\", \\"ec\\": \\"1\\", \\"time-out\\": \\"0\\", \\"validity\\": \\"30052019 000000\\"}",
...         "time": 1558960217731,
...         "dlr": "1",
...         "msisdn": "xxxxx",
...         "entity": 1
...     }
... ]
... '''
>>> json_data = json.loads(json_string)
>>> for row in json_data:
...     row['amd'] = json.loads(row['amd'])
...     # Write row to CSV
...
>>> json_data
[{'amd': {'ec': '1',
          'mask': '1GB_OFFER',
          'msg': ' some Bengali text',
          'time-out': '0',
          'validity': '30052019 000000'},
  'c_id': 120184,
  'ch_id': 1,
  'dlr': '1',
  'entity': 1,
  'msg_type': 1,
  'msisdn': 'xxxxx',
  'o_id': 121164,
  'pt_slot': 'null:null',
  's_id': '80740185',
  't_id': '80740185.1558980000000.120184.121164',
  'time': 1558960217731}]

Edited to provide full working example.


问:
Python deprecation warning about sum function
I coded an algorithm and it worked properly till 2 weeks ago. I get this warning and I cannot understand why I get it. The warning is:

"C:/Users/Administrator/Documents/Python/sezg_1_diffne.py:147:
  DeprecationWarning: Calling np.sum(generator) is deprecated, and in
  the future will give a different result. Use
  np.sum(np.from_iter(generator)) or the python sum builtin instead.
  obje_1=detmas.objVal+sum(hopen[i]*fixedCost for i in Fset)"

A part of my code is:

```<code>obje_1=detmas.objVal+sum(hopen[i]*fixedCost for i in Fset)
</code>```

I tried something which I found in internet such as removing numpy and reinstall it. However these solutions did not work for my code. How I can solve it? Thanks in advance...

答:
I have found an alternative solution to the one by jpp. If you wish to keep the from numpy import * you can assign the built-in object to a different variable before importing numpy, as it is shown here.

In your particular case you have two choices:

Import the built-in module:

import builtins for Python 3, or import __builtin__ for Python 2. And you call either builtins.sum(hopen[i]*fixedCost for i in Fset) or __builtin__.sum(hopen[i]*fixedCost for i in Fset).

Assign the built-in sum to a different variable before importing numpy:

bltin_sum = sum

from numpy import *

bltin_sum(hopen[i]*fixedCost for i in Fset)

I have already checked that the built-in sum behaves as expected for numpy arrays as well.

Body:
I coded an algorithm and it worked properly till 2 weeks ago. I get this warning and I cannot understand why I get it. The warning is:

"C:/Users/Administrator/Documents/Python/sezg_1_diffne.py:147:
  DeprecationWarning: Calling np.sum(generator) is deprecated, and in
  the future will give a different result. Use
  np.sum(np.from_iter(generator)) or the python sum builtin instead.
  obje_1=detmas.objVal+sum(hopen[i]*fixedCost for i in Fset)"

A part of my code is:

obje_1=detmas.objVal+sum(hopen[i]*fixedCost for i in Fset)

I tried something which I found in internet such as removing numpy and reinstall it. However these solutions did not work for my code. How I can solve it? Thanks in advance...


问:
Moving up a directory
I'm creating a directory in a php script, moving into that directory and doing some stuff. This part works fine.

Now, I want to move out of this directory and delete it.
Any pointers on how to do this?

I have tried moving up 1 level, but it doesnt work

```<code>chdir("../");
chdir("..")
system("cd ..");
</code>```

none of the above have any effect on the present working directory

答:
I would advise against actually changing dir; simply hold the path of interest and operate upon it (and the files within it) directly.

That said, chdir ('../'); should work.

ContentLicense: CC BY-SA 3.0

Title: Moving up a directory

Body:
I'm creating a directory in a php script, moving into that directory and doing some stuff. This part works fine.

Now, I want to move out of this directory and delete it.
Any pointers on how to do this?

I have tried moving up 1 level, but it doesnt work

chdir("../");
chdir("..")
system("cd ..");

none of the above have any effect on the present working directory


问:
How does a Rust PathBuf prevent directory traversal attacks?
From "A Case for Oxidation: The Rust Programming Language" Sergio Benitez says,

Here is a static file server written in Rocket. It is exactly four lines and it guaranteed to not be vulnerable to directory traversal attacks.

Those four lines are:

```<code>#[get("/<path..>")]
fn files(path: PathBuf) -> Option<NamedFile> {
    NamedFile::open(Path::new("static/").join(path)).ok()
}
</code>```

The bottom of this slide says,

FromParam* implementation for PathBuf verifies path safety

I get how a type can guarantee safety by validating input (in the same sense that any object can in a constructor or how the input to a function can be wrapped with a validating function.

dangerousThing(validateSafety(input))
```

<p>Many languages provide this. I also understand how you can make this simpler by putting it into a constructor for a type or class,</p>

<pre class="lang-none prettyprint-override"><code>class Path {
  constructor(path) { this._path = validateSafety(path) }
}
</code>```

But I'm confused at what (if anything) Rust is doing differently here. Is there anything more to this?

答:
PathBuf provides no such guarantees. It cannot because there's no concept of "directory traversal attacks" in all domains where a PathBuf is used.

What the author means is that the implementation of FromSegments for PathBuf performs the traversal attack check and never calls the handler if it fails.

FromSegments allows for failure cases by returning a Result:

```<code>pub trait FromSegments<'a>: Sized {
    type Error: Debug;
    fn from_segments(segments: Segments<'a>) -> Result<Self, Self::Error>;
}
</code>```

Body:
From "A Case for Oxidation: The Rust Programming Language" Sergio Benitez says,

Here is a static file server written in Rocket. It is exactly four lines and it guaranteed to not be vulnerable to directory traversal attacks.

Those four lines are:

#[get("/<path..>")]
fn files(path: PathBuf) -> Option<NamedFile> {
    NamedFile::open(Path::new("static/").join(path)).ok()
}

The bottom of this slide says,

FromParam* implementation for PathBuf verifies path safety

I get how a type can guarantee safety by validating input (in the same sense that any object can in a constructor or how the input to a function can be wrapped with a validating function.

dangerousThing(validateSafety(input))

Many languages provide this. I also understand how you can make this simpler by putting it into a constructor for a type or class,

class Path {
  constructor(path) { this._path = validateSafety(path) }
}

But I'm confused at what (if anything) Rust is doing differently here. Is there anything more to this?

Body:
PathBuf provides no such guarantees. It cannot because there's no concept of "directory traversal attacks" in all domains where a PathBuf is used.

What the author means is that the implementation of FromSegments for PathBuf performs the traversal attack check and never calls the handler if it fails.

FromSegments allows for failure cases by returning a Result:

pub trait FromSegments<'a>: Sized {
    type Error: Debug;
    fn from_segments(segments: Segments<'a>) -> Result<Self, Self::Error>;
}


问:
ReactJS: Uncaught TypeError: this.setState is not a function
While running my app, and when trying to update state with some form values the following error message appears:

"Uncaught TypeError: this.setState is not a function"

LoginForm.onChange
src/components/forms/LoginForm.js:21
  18 | }
  19 |
  20 | onChange = e => {
> 21 |     this.setState({
     | ^  22 |         data: { ...this.state.data, [e.target.name]: e.target.value }
  23 |     });
  24 | }
```

<p>Added binding in constructor to onChange (this was not there before), but this does not resolve the problem.
this.onChange = this.onChange.bind(this);</p>

<p>I'm using: react: "^16.8.6"</p>

<p>Here is the component code:</p>

<pre class="lang-js prettyprint-override"><code>import React from "react";
import { Form, Button } from "semantic-ui-react";
import Validator from "validator";
import InlineError from "../messages/InlineError"

class LoginForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: {
                email: "",
                password: ""
            },
            loading: false,
            errors: {}
        };
        this.onChange = this.onChange.bind(this);
    }

    onChange = e => {
        this.setState({
            data: { ...this.state.data, [e.target.name]: e.target.value }
        });
    }

    onSubmit = () => {
        const errors = this.validate(this.state.data);
        this.setState = ({ errors });
    };

    validate = (data) => {
        const errors = {};
        if (!Validator.isEmail(data.email)) errors.email = "Invalid email."
        if (!data.password) errors.password = "Cannot be blank.";

        return errors;
    };

    render() {
        const { data, errors } = this.state;
        return (
            <Form onSubmit={this.onSubmit}>
                <Form.Field>
                    <label htmlFor="email">Email</label>
                    <input
                        type="email"
                        id="email"
                        name="email"
                        placeholder="me@example.com"
                        value={data.email}
                        onChange={this.onChange}
                    />

                </Form.Field>
                {errors.email && <InlineError text={errors.email} />}
                <Form.Field>
                    <label htmlFor="password">Password</label>
                    <input
                        type="password"
                        id="password"
                        name="password"
                        placeholder="Enter your password"
                        value={data.password}
                        onChange={this.onChange}
                    />
                    {errors.password && <InlineError text={errors.password} />}

                </Form.Field>

                <Button primary>Login</Button>
            </Form>
        );
    }
}

export default LoginForm;

</code>```

答:
Everything is right with the code except onChange handler just small
 modification to your onChange handler

```<code>onChange = e => {
  const target = e.target;
  const name = target.name;
  this.setState({
     ...this.state,
     data: {
        ...this.state.data,
        [name]: target.value
     }
  });
 };
</code>```

Sorry I ignored onSubmit it should be like this

```<code> onSubmit = () => {
  const errors = this.validate(this.state.data);
  this.setState({ errors });
};
</code>```

And This should work !!

Make sure Component Look Like this

```<code>import React from "react";
import { Form, Button } from "semantic-ui-react";
import Validator from "validator";
import InlineError from "../messages/InlineError";

class LoginForm extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
         data: {
            email: "",
            password: ""
         },
         loading: false,
         errors: {}
      };
   }

   onChange = e => {
      const target = e.target;
      const name = target.name;
      this.setState({
         ...this.state,
         data: {
            ...this.state.data,
            [name]: target.value
         }
      });
   };

   onSubmit = () => {
      const errors = this.validate(this.state.data);
      this.setState({ errors });
   };

   validate = data => {
      const errors = {};
      if (!Validator.isEmail(data.email)) errors.email = "Invalid email.";
      if (!data.password) errors.password = "Cannot be blank.";

      return errors;
   };

   render() {
      const { data, errors } = this.state;
      return (
         <Form onSubmit={this.onSubmit}>
            <Form.Field>
               <label htmlFor="email">Email</label>
               <input
                  type="email"
                  id="email"
                  name="email"
                  placeholder="me@example.com"
                  value={data.email}
                  onChange={this.onChange}
               />
            </Form.Field>
            {errors.email && <InlineError text={errors.email} />}
            <Form.Field>
               <label htmlFor="password">Password</label>
               <input
                  type="password"
                  id="password"
                  name="password"
                  placeholder="Enter your password"
                  value={data.password}
                  onChange={this.onChange}
               />
               {errors.password && <InlineError text={errors.password} />}
            </Form.Field>

            <Button primary>Login</Button>
         </Form>
      );
   }
}

export default LoginForm;
</code>```

Body:
While running my app, and when trying to update state with some form values the following error message appears:

"Uncaught TypeError: this.setState is not a function"

LoginForm.onChange
src/components/forms/LoginForm.js:21
  18 | }
  19 |
  20 | onChange = e => {
> 21 |     this.setState({
     | ^  22 |         data: { ...this.state.data, [e.target.name]: e.target.value }
  23 |     });
  24 | }

Added binding in constructor to onChange (this was not there before), but this does not resolve the problem.
this.onChange = this.onChange.bind(this);

I'm using: react: "^16.8.6"

Here is the component code:

import React from "react";
import { Form, Button } from "semantic-ui-react";
import Validator from "validator";
import InlineError from "../messages/InlineError"

class LoginForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: {
                email: "",
                password: ""
            },
            loading: false,
            errors: {}
        };
        this.onChange = this.onChange.bind(this);
    }

    onChange = e => {
        this.setState({
            data: { ...this.state.data, [e.target.name]: e.target.value }
        });
    }

    onSubmit = () => {
        const errors = this.validate(this.state.data);
        this.setState = ({ errors });
    };

    validate = (data) => {
        const errors = {};
        if (!Validator.isEmail(data.email)) errors.email = "Invalid email."
        if (!data.password) errors.password = "Cannot be blank.";

        return errors;
    };

    render() {
        const { data, errors } = this.state;
        return (
            <Form onSubmit={this.onSubmit}>
                <Form.Field>
                    Email
                    <input
                        type="email"
                        id="email"
                        name="email"
                        placeholder="me@example.com"
                        value={data.email}
                        onChange={this.onChange}
                    />

                </Form.Field>
                {errors.email && <InlineError text={errors.email} />}
                <Form.Field>
                    Password
                    <input
                        type="password"
                        id="password"
                        name="password"
                        placeholder="Enter your password"
                        value={data.password}
                        onChange={this.onChange}
                    />
                    {errors.password && <InlineError text={errors.password} />}

                </Form.Field>

                <Button primary>Login</Button>
            </Form>
        );
    }
}

export default LoginForm;

Body:
Everything is right with the code except onChange handler just small
 modification to your onChange handler

onChange = e => {
  const target = e.target;
  const name = target.name;
  this.setState({
     ...this.state,
     data: {
        ...this.state.data,
        [name]: target.value
     }
  });
 };

Sorry I ignored onSubmit it should be like this

 onSubmit = () => {
  const errors = this.validate(this.state.data);
  this.setState({ errors });
};

And This should work !!

Make sure Component Look Like this

import React from "react";
import { Form, Button } from "semantic-ui-react";
import Validator from "validator";
import InlineError from "../messages/InlineError";

class LoginForm extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
         data: {
            email: "",
            password: ""
         },
         loading: false,
         errors: {}
      };
   }

   onChange = e => {
      const target = e.target;
      const name = target.name;
      this.setState({
         ...this.state,
         data: {
            ...this.state.data,
            [name]: target.value
         }
      });
   };

   onSubmit = () => {
      const errors = this.validate(this.state.data);
      this.setState({ errors });
   };

   validate = data => {
      const errors = {};
      if (!Validator.isEmail(data.email)) errors.email = "Invalid email.";
      if (!data.password) errors.password = "Cannot be blank.";

      return errors;
   };

   render() {
      const { data, errors } = this.state;
      return (
         <Form onSubmit={this.onSubmit}>
            <Form.Field>
               <label htmlFor="email">Email</label>
               <input
                  type="email"
                  id="email"
                  name="email"
                  placeholder="me@example.com"
                  value={data.email}
                  onChange={this.onChange}
               />
            </Form.Field>
            {errors.email && <InlineError text={errors.email} />}
            <Form.Field>
               <label htmlFor="password">Password</label>
               <input
                  type="password"
                  id="password"
                  name="password"
                  placeholder="Enter your password"
                  value={data.password}
                  onChange={this.onChange}
               />
               {errors.password && <InlineError text={errors.password} />}
            </Form.Field>

            <Button primary>Login</Button>
         </Form>
      );
   }
}

export default LoginForm;


问:
React - native cannot read property 'navigate" of undefined
I'm building an app in react-native and I'm using StackNavigator to navigate.
Here is my problem:

I have my principal page in which I import two other component :

```<code>
export default class RoomChoice extends Component {
  constructor(props) {
    super(props)
    this.state = {
      create: this.props.navigation.state.params.create,
      join: this.props.navigation.state.params.join
    }
  }

  onCreatePress = () => {
    this.setState({ create: true })
    this.setState({ join: false })
  }

  onJoinPress = () => {
    this.setState({ join: true })
    this.setState({ create: false })
  }

  render() {
    return (
      <View style={styles.container}>
        <BtnCreateJoinRoom
          create={this.state.create}
          join={this.state.join}
          onPressCreate={() => {
            this.onCreatePress()
          }}
          onPressJoin={() => {
            this.onJoinPress()
          }}
        />
        {this.state.create ? <CreateRoom /> : <JoinRoom />}
      </View>
    )
  }
}
</code>```

Here is my CreateRoom component in which I want to use the navigation to another page :

```<code>
export default class CreateRoom extends Component {

  render() {
    return (
      <View style={styles.container}>
          <BtnComponent title='Créer un code'
                        onPressBtn={() => { this.props.navigation.navigate('CodeCreateRoom') }}/>
      </View>
    )
  }
}

</code>```

But When I click it throws error : cannont read property 'navigate' of undefined

```<code>
import {
  createStackNavigator,
  createAppContainer,
  createSwitchNavigator
} from 'react-navigation'

import Home from '../screens/Home'
import RoomChoice from '../screens/Room/RoomChoice'
import CreateRoom from '../screens/Room/CreateRoom'
import CodeCreateRoom from '../screens/Room/CodeCreateRoom'

const AppStack = createStackNavigator(
  {
    Home: {
      screen: Home,
      navigationOptions: {
        header: null
      }
    },
    RoomChoice: {
      screen: RoomChoice,
      navigationOptions: {
        headerStyle: {
          backgroundColor: BUTTON_SECONDARY_BACKGROUND_COLOR,
          borderBottomWidth: 0
        },
        headerTintColor: 'white'
      }
    },
    CreateRoom: {
      screen: CreateRoom,
      navigationOptions: {
        headerStyle: {
          backgroundColor: BUTTON_SECONDARY_BACKGROUND_COLOR,
          borderBottomWidth: 0
        },
        headerTintColor: 'white'
      }
    },
    CodeCreateRoom: {
      screen: CodeCreateRoom,
      navigationOptions: {
        headerStyle: {
          backgroundColor: BUTTON_SECONDARY_BACKGROUND_COLOR,
          borderBottomWidth: 0
        },
        headerTintColor: 'white'
      }
    }
  },
  {
    headerLayoutPreset: 'center',
    initialRouteName: 'Home'
  }
)

</code>```

I don't understand why it doesn't want to navigate, does anyone have any ideas ?

答:
You only have the navigation prop on direct children of your navigator. Your custom BtnCreateJoinRoom components don't inherit the navigation prop. You must use withNavigation, or pass the prop from one of the direct children.

https://reactnavigation.org/docs/en/connecting-navigation-prop.html

Body:
I'm building an app in react-native and I'm using StackNavigator to navigate.
Here is my problem:

I have my principal page in which I import two other component :

export default class RoomChoice extends Component {
  constructor(props) {
    super(props)
    this.state = {
      create: this.props.navigation.state.params.create,
      join: this.props.navigation.state.params.join
    }
  }

  onCreatePress = () => {
    this.setState({ create: true })
    this.setState({ join: false })
  }

  onJoinPress = () => {
    this.setState({ join: true })
    this.setState({ create: false })
  }

  render() {
    return (
      <View style={styles.container}>
        <BtnCreateJoinRoom
          create={this.state.create}
          join={this.state.join}
          onPressCreate={() => {
            this.onCreatePress()
          }}
          onPressJoin={() => {
            this.onJoinPress()
          }}
        />
        {this.state.create ? <CreateRoom /> : <JoinRoom />}
      </View>
    )
  }
}

Here is my CreateRoom component in which I want to use the navigation to another page :

export default class CreateRoom extends Component {

  render() {
    return (
      <View style={styles.container}>
          <BtnComponent title='Créer un code'
                        onPressBtn={() => { this.props.navigation.navigate('CodeCreateRoom') }}/>
      </View>
    )
  }
}

But When I click it throws error : cannont read property 'navigate' of undefined

import {
  createStackNavigator,
  createAppContainer,
  createSwitchNavigator
} from 'react-navigation'

import Home from '../screens/Home'
import RoomChoice from '../screens/Room/RoomChoice'
import CreateRoom from '../screens/Room/CreateRoom'
import CodeCreateRoom from '../screens/Room/CodeCreateRoom'

const AppStack = createStackNavigator(
  {
    Home: {
      screen: Home,
      navigationOptions: {
        header: null
      }
    },
    RoomChoice: {
      screen: RoomChoice,
      navigationOptions: {
        headerStyle: {
          backgroundColor: BUTTON_SECONDARY_BACKGROUND_COLOR,
          borderBottomWidth: 0
        },
        headerTintColor: 'white'
      }
    },
    CreateRoom: {
      screen: CreateRoom,
      navigationOptions: {
        headerStyle: {
          backgroundColor: BUTTON_SECONDARY_BACKGROUND_COLOR,
          borderBottomWidth: 0
        },
        headerTintColor: 'white'
      }
    },
    CodeCreateRoom: {
      screen: CodeCreateRoom,
      navigationOptions: {
        headerStyle: {
          backgroundColor: BUTTON_SECONDARY_BACKGROUND_COLOR,
          borderBottomWidth: 0
        },
        headerTintColor: 'white'
      }
    }
  },
  {
    headerLayoutPreset: 'center',
    initialRouteName: 'Home'
  }
)

I don't understand why it doesn't want to navigate, does anyone have any ideas ?


问:
How to nest a conditional 3 quote strings inside another 3 quote strings in python?
I am trying to a paragraph of lines using 3 quote strings where some group of lines in the paragraph are to be included on a if condition. I am using {} brackets for those conditional lines and since each of them have to be on the next line, I have to use 3 quote strings for them. So its a nested 3 quote string with a condition

For example, I have

write_line_3nd4 = True
paragraph = f'''
this is line one
x = 12 #line two
{f'''
line 3,4 #this is line 3
x=34 #this is line 4''' if write_line_3nd4 else ''}
'''
```

<p>It gives me an error as such:</p>

```File "<ipython-input-36-4bcb98c8ebe0>", line 6
line 3,4 #this is line 3
     ^
SyntaxError: invalid syntax
```

How do use conditional multi-line strings inside multi-line strings?

答:
Maybe this will help.

```<code>x = "one"
if x == "one":
    y = "two"
else:
    y = "three"
print("""
    This is some line of printed text
    This is some line of printed more text
    these {} and {} are variables designated by `str.format()`
    """.format(x, y))
print(x)
</code>```

Im not sure what you're asking either but this is my guess as to what you are looking for.

Body:
I am trying to a paragraph of lines using 3 quote strings where some group of lines in the paragraph are to be included on a if condition. I am using {} brackets for those conditional lines and since each of them have to be on the next line, I have to use 3 quote strings for them. So its a nested 3 quote string with a condition

For example, I have

write_line_3nd4 = True
paragraph = f'''
this is line one
x = 12 #line two
{f'''
line 3,4 #this is line 3
x=34 #this is line 4''' if write_line_3nd4 else ''}
'''

It gives me an error as such:

File "<ipython-input-36-4bcb98c8ebe0>", line 6
line 3,4 #this is line 3
     ^
SyntaxError: invalid syntax

How do use conditional multi-line strings inside multi-line strings?

Body:
Maybe this will help.

x = "one"
if x == "one":
    y = "two"
else:
    y = "three"
print("""
    This is some line of printed text
    This is some line of printed more text
    these {} and {} are variables designated by `str.format()`
    """.format(x, y))
print(x)

Im not sure what you're asking either but this is my guess as to what you are looking for.


问:
SELECTing top N rows without ROWNUM?
I hope you can help me with my homework :)

We need to build a query that outputs the top N best paid employees.

My version works perfectly fine.

For example the top 3:

```<code>SELECT name, salary
FROM staff
WHERE salary IN ( SELECT *
                  FROM ( SELECT salary
                         FROM staff
                         ORDER BY salary DESC )
                  WHERE ROWNUM <= 3 )
ORDER BY salary DESC
;
</code>```

Note that this will output employees that are in the top 3 and have the same salary, too.

1: Mike, 4080

  2: Steve, 2800

  2: Susan, 2800

  2: Jack, 2800

  3: Chloe, 1400

But now our teacher does not allow us to use ROWNUM.

I searched far and wide and didn't find anything useable.

My second solution thanks to Justin Caves' hint.

First i tried this:

```<code>SELECT name, salary, ( rank() OVER ( ORDER BY salary DESC ) ) as myorder
FROM staff
WHERE myorder <= 3
;
</code>```

The errormessage is: "myorder: invalid identifier"

Thanks to DCookie its now clear:

"[...] Analytics are applied AFTER
  the where clause is evaluated, which
  is why you get the error that myorder
  is an invalid identifier."

Wrapping a SELECT around solves this:

```<code>SELECT *
FROM ( SELECT name, salary, rank() OVER ( ORDER BY salary DESC ) as myorder FROM staff )
WHERE myorder <= 3
;
</code>```

My teacher strikes again and don't allow such exotic analytic functions.

3rd solution from @Justin Caves.

"If analytic functions are also
  disallowed, the other option I could
  imagine-- one that you would never,
  ever, ever actually write in practice,
  would be something like"

```<code>SELECT name, salary
  FROM staff s1
 WHERE (SELECT COUNT(*)
          FROM staff s2
         WHERE s1.salary < s2.salary) <= 3
</code>```

答:
Since this is homework, a hint rather than an answer.  You'll want to use analytic functions.  ROW_NUMBER, RANK, or DENSE_RANK can work depending on how you want to handle ties.

If analytic functions are also disallowed, the other option I could imagine-- one that you would never, ever, ever actually write in practice, would be something like

```<code>SELECT name, salary
  FROM staff s1
 WHERE (SELECT COUNT(*)
          FROM staff s2
         WHERE s1.salary < s2.salary) <= 3
</code>```

With regard to performance, I wouldn't rely on the COST number from the query plan-- that's only an estimate and it is not generally possible to compare the cost between plans for different SQL statements.  You're much better off looking at something like the number of consistent gets the query actually does and considering how the query performance will scale as the number of rows in the table increases.  The third option is going to be radically less efficient than the other two simply because it needs to scan the STAFF table twice.

I don't have your STAFF table, so I'll use the EMP table from the SCOTT schema

The analytic function solution actually does 7 consistent gets as does the ROWNUM solution

```<code>Wrote file afiedt.buf

  1  select ename, sal
  2    from( select ename,
  3                 sal,
  4                 rank() over (order by sal) rnk
  5            from emp )
  6*  where rnk <= 3
SQL> /

ENAME             SAL
---------- ----------
smith             800
SM0               950
ADAMS            1110

Execution Plan
----------------------------------------------------------
Plan hash value: 3291446077

--------------------------------------------------------------------------------
-
| Id  | Operation                | Name | Rows  | Bytes | Cost (%CPU)| Time
|
--------------------------------------------------------------------------------
-
|   0 | SELECT STATEMENT         |      |    14 |   672 |     4  (25)| 00:00:01
|*  1 |  VIEW                    |      |    14 |   672 |     4  (25)| 00:00:01
|*  2 |   WINDOW SORT PUSHED RANK|      |    14 |   140 |     4  (25)| 00:00:01
|   3 |    TABLE ACCESS FULL     | EMP  |    14 |   140 |     3   (0)| 00:00:01
--------------------------------------------------------------------------------
-

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter("RNK"<=3)
   2 - filter(RANK() OVER ( ORDER BY "SAL")<=3)

Statistics
----------------------------------------------------------
          0  recursive calls
          0  db block gets
          7  consistent gets
          0  physical reads
          0  redo size
        668  bytes sent via SQL*Net to client
        524  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          1  sorts (memory)
          0  sorts (disk)
          3  rows processed

SQL> select ename, sal
  2    from( select ename, sal
  3            from emp
  4           order by sal )
  5   where rownum <= 3;

ENAME             SAL
---------- ----------
smith             800
SM0               950
ADAMS            1110

Execution Plan
----------------------------------------------------------
Plan hash value: 1744961472

--------------------------------------------------------------------------------
| Id  | Operation               | Name | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------------
|   0 | SELECT STATEMENT        |      |     3 |   105 |     4  (25)| 00:00:01 |
|*  1 |  COUNT STOPKEY          |      |       |       |            |          |
|   2 |   VIEW                  |      |    14 |   490 |     4  (25)| 00:00:01 |
|*  3 |    SORT ORDER BY STOPKEY|      |    14 |   140 |     4  (25)| 00:00:01 |
|   4 |     TABLE ACCESS FULL   | EMP  |    14 |   140 |     3   (0)| 00:00:01 |
--------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter(ROWNUM<=3)
   3 - filter(ROWNUM<=3)

Statistics
----------------------------------------------------------
          1  recursive calls
          0  db block gets
          7  consistent gets
          0  physical reads
          0  redo size
        668  bytes sent via SQL*Net to client
        524  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          1  sorts (memory)
          0  sorts (disk)
          3  rows processed
</code>```

The COUNT(*) solution, however, actually does 99 consistent gets and has to do a full scan of the table twice so it is more than 10 times less efficient.  And it will scale much worse as the number of rows in the table increases

```<code>SQL> select ename, sal
  2    from emp e1
  3   where (select count(*) from emp e2 where e1.sal < e2.sal) <= 3;

ENAME             SAL
---------- ----------
JONES            2975
SCOTT            3000
KING             5000
FORD             3000
FOO

Execution Plan
----------------------------------------------------------
Plan hash value: 2649664444

----------------------------------------------------------------------------
| Id  | Operation           | Name | Rows  | Bytes | Cost (%CPU)| Time     |
----------------------------------------------------------------------------
|   0 | SELECT STATEMENT    |      |    14 |   140 |    24   (0)| 00:00:01 |
|*  1 |  FILTER             |      |       |       |            |          |
|   2 |   TABLE ACCESS FULL | EMP  |    14 |   140 |     3   (0)| 00:00:01 |
|   3 |   SORT AGGREGATE    |      |     1 |     4 |            |          |
|*  4 |    TABLE ACCESS FULL| EMP  |     1 |     4 |     3   (0)| 00:00:01 |
----------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter( (SELECT COUNT(*) FROM "EMP" "E2" WHERE
              "E2"."SAL">:B1)<=3)
   4 - filter("E2"."SAL">:B1)

Statistics
----------------------------------------------------------
          0  recursive calls
          0  db block gets
         99  consistent gets
          0  physical reads
          0  redo size
        691  bytes sent via SQL*Net to client
        524  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
          5  rows processed
</code>```

Title: SELECTing top N rows without ROWNUM?

Body:
I hope you can help me with my homework :)

We need to build a query that outputs the top N best paid employees.

My version works perfectly fine.

For example the top 3:

SELECT name, salary
FROM staff
WHERE salary IN ( SELECT *
                  FROM ( SELECT salary
                         FROM staff
                         ORDER BY salary DESC )
                  WHERE ROWNUM <= 3 )
ORDER BY salary DESC
;

Note that this will output employees that are in the top 3 and have the same salary, too.

1: Mike, 4080

  2: Steve, 2800

  2: Susan, 2800

  2: Jack, 2800

  3: Chloe, 1400

But now our teacher does not allow us to use ROWNUM.

I searched far and wide and didn't find anything useable.

My second solution thanks to Justin Caves' hint.

First i tried this:

SELECT name, salary, ( rank() OVER ( ORDER BY salary DESC ) ) as myorder
FROM staff
WHERE myorder <= 3
;

The errormessage is: "myorder: invalid identifier"

Thanks to DCookie its now clear:

"[...] Analytics are applied AFTER
  the where clause is evaluated, which
  is why you get the error that myorder
  is an invalid identifier."

Wrapping a SELECT around solves this:

SELECT *
FROM ( SELECT name, salary, rank() OVER ( ORDER BY salary DESC ) as myorder FROM staff )
WHERE myorder <= 3
;

My teacher strikes again and don't allow such exotic analytic functions.

3rd solution from @Justin Caves.

"If analytic functions are also
  disallowed, the other option I could
  imagine-- one that you would never,
  ever, ever actually write in practice,
  would be something like"

SELECT name, salary
  FROM staff s1
 WHERE (SELECT COUNT(*)
          FROM staff s2
         WHERE s1.salary < s2.salary) <= 3

Body:
Since this is homework, a hint rather than an answer.  You'll want to use analytic functions.  ROW_NUMBER, RANK, or DENSE_RANK can work depending on how you want to handle ties.

If analytic functions are also disallowed, the other option I could imagine-- one that you would never, ever, ever actually write in practice, would be something like

SELECT name, salary
  FROM staff s1
 WHERE (SELECT COUNT(*)
          FROM staff s2
         WHERE s1.salary < s2.salary) <= 3

With regard to performance, I wouldn't rely on the COST number from the query plan-- that's only an estimate and it is not generally possible to compare the cost between plans for different SQL statements.  You're much better off looking at something like the number of consistent gets the query actually does and considering how the query performance will scale as the number of rows in the table increases.  The third option is going to be radically less efficient than the other two simply because it needs to scan the STAFF table twice.

I don't have your STAFF table, so I'll use the EMP table from the SCOTT schema

The analytic function solution actually does 7 consistent gets as does the ROWNUM solution

Wrote file afiedt.buf

  1  select ename, sal
  2    from( select ename,
  3                 sal,
  4                 rank() over (order by sal) rnk
  5            from emp )
  6*  where rnk <= 3
SQL> /

ENAME             SAL
---------- ----------
smith             800
SM0               950
ADAMS            1110

Execution Plan
----------------------------------------------------------
Plan hash value: 3291446077

--------------------------------------------------------------------------------
-
| Id  | Operation                | Name | Rows  | Bytes | Cost (%CPU)| Time
|
--------------------------------------------------------------------------------
-
|   0 | SELECT STATEMENT         |      |    14 |   672 |     4  (25)| 00:00:01
|*  1 |  VIEW                    |      |    14 |   672 |     4  (25)| 00:00:01
|*  2 |   WINDOW SORT PUSHED RANK|      |    14 |   140 |     4  (25)| 00:00:01
|   3 |    TABLE ACCESS FULL     | EMP  |    14 |   140 |     3   (0)| 00:00:01
--------------------------------------------------------------------------------
-

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter("RNK"<=3)
   2 - filter(RANK() OVER ( ORDER BY "SAL")<=3)

Statistics
----------------------------------------------------------
          0  recursive calls
          0  db block gets
          7  consistent gets
          0  physical reads
          0  redo size
        668  bytes sent via SQL*Net to client
        524  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          1  sorts (memory)
          0  sorts (disk)
          3  rows processed

SQL> select ename, sal
  2    from( select ename, sal
  3            from emp
  4           order by sal )
  5   where rownum <= 3;

ENAME             SAL
---------- ----------
smith             800
SM0               950
ADAMS            1110

Execution Plan
----------------------------------------------------------
Plan hash value: 1744961472

--------------------------------------------------------------------------------
| Id  | Operation               | Name | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------------
|   0 | SELECT STATEMENT        |      |     3 |   105 |     4  (25)| 00:00:01 |
|*  1 |  COUNT STOPKEY          |      |       |       |            |          |
|   2 |   VIEW                  |      |    14 |   490 |     4  (25)| 00:00:01 |
|*  3 |    SORT ORDER BY STOPKEY|      |    14 |   140 |     4  (25)| 00:00:01 |
|   4 |     TABLE ACCESS FULL   | EMP  |    14 |   140 |     3   (0)| 00:00:01 |
--------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter(ROWNUM<=3)
   3 - filter(ROWNUM<=3)

Statistics
----------------------------------------------------------
          1  recursive calls
          0  db block gets
          7  consistent gets
          0  physical reads
          0  redo size
        668  bytes sent via SQL*Net to client
        524  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          1  sorts (memory)
          0  sorts (disk)
          3  rows processed

The COUNT(*) solution, however, actually does 99 consistent gets and has to do a full scan of the table twice so it is more than 10 times less efficient.  And it will scale much worse as the number of rows in the table increases

SQL> select ename, sal
  2    from emp e1
  3   where (select count(*) from emp e2 where e1.sal < e2.sal) <= 3;

ENAME             SAL
---------- ----------
JONES            2975
SCOTT            3000
KING             5000
FORD             3000
FOO

Execution Plan
----------------------------------------------------------
Plan hash value: 2649664444

----------------------------------------------------------------------------
| Id  | Operation           | Name | Rows  | Bytes | Cost (%CPU)| Time     |
----------------------------------------------------------------------------
|   0 | SELECT STATEMENT    |      |    14 |   140 |    24   (0)| 00:00:01 |
|*  1 |  FILTER             |      |       |       |            |          |
|   2 |   TABLE ACCESS FULL | EMP  |    14 |   140 |     3   (0)| 00:00:01 |
|   3 |   SORT AGGREGATE    |      |     1 |     4 |            |          |
|*  4 |    TABLE ACCESS FULL| EMP  |     1 |     4 |     3   (0)| 00:00:01 |
----------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter( (SELECT COUNT(*) FROM "EMP" "E2" WHERE
              "E2"."SAL">:B1)<=3)
   4 - filter("E2"."SAL">:B1)

Statistics
----------------------------------------------------------
          0  recursive calls
          0  db block gets
         99  consistent gets
          0  physical reads
          0  redo size
        691  bytes sent via SQL*Net to client
        524  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
          5  rows processed


问:
What is the most secure mcrpyt_encrypt algorithm?
I am trying  to come up with a secure algorithm to encrypt and decrypt specific strings in my project I am working on. I am using the mcrypt_encrypt with the MCRYPT_RIJNDAEL_256 block cipher variation.

I have tested many and found this one to seem quite secure.

I am making the encrypt and decrypt into functions so I can call upon them for multiple instances in the future of my project. So far this is what I have come up with. My question here is if there is any way to make this more secure, harder to decrypt or if there are any newer formulas/methods that are known to be better.

```<code>function encrypt($privatekey, $stringe)
 {
     $var = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $privatekey, $stringe,
 MCRYPT_MODE_CBC, $privatekey);
     return base64_encode($var);
 }
function decrypt($privatekey, $stringd)
{
    $stringd = str_replace("~", "+", $stringd);
    $var = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $privatekey,
base64_decode($stringd), MCRYPT_MODE_CBC, $privatekey);
    $var = rtrim($var, "\0\4");
    return $var;
}
</code>```

答:
I have tested many and found this one to seem quite secure.

What tests did you conduct, exactly?

Rijndael256 is a 256-bit block variant of Rijndael (for which the 128-bit block size variant is known as AES). However, when implemented in pure software (like mcrypt is implemented), it's vulnerable to cache-timing attacks.

What is the most secure mcrpyt_encrypt algorithm?

Mcrypt's implementations are not secure. That's why it was deprecated in PHP 7.1, and removed in PHP 7.2.

See this answer for safe-to-use example code backed by libsodium. For PHP 7.1 and below, you want to install the Sodium extension from PECL or install sodium_compat.

Body:
I am trying  to come up with a secure algorithm to encrypt and decrypt specific strings in my project I am working on. I am using the mcrypt_encrypt with the MCRYPT_RIJNDAEL_256 block cipher variation.

I have tested many and found this one to seem quite secure.

I am making the encrypt and decrypt into functions so I can call upon them for multiple instances in the future of my project. So far this is what I have come up with. My question here is if there is any way to make this more secure, harder to decrypt or if there are any newer formulas/methods that are known to be better.

function encrypt($privatekey, $stringe)
 {
     $var = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $privatekey, $stringe,
 MCRYPT_MODE_CBC, $privatekey);
     return base64_encode($var);
 }
function decrypt($privatekey, $stringd)
{
    $stringd = str_replace("~", "+", $stringd);
    $var = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $privatekey,
base64_decode($stringd), MCRYPT_MODE_CBC, $privatekey);
    $var = rtrim($var, "\0\4");
    return $var;
}


问:
Minecraft Forge Mod blocks not showing
I programmed 2 blocks in minecraft forge (I did everything right, I checked it on 4 tutorials).
When I try to run the game the blocks are not in the creative inventory.
The console gives me no error: http://pastebin.com/G5qnz9nT.

My code:
http://pastebin.com/cq4MvwH9

Why are my blocks not there?

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

答:
I have the same problem. Can`t see my block in tabs , and even command "/give playername @mymod:myblock 1" returns "There is no such item with name @mymod:myblock".

There is my main mod class code:

```<code>@Mod.EventBusSubscriber
@Mod(modid = NoFear.MODID, name = NoFear.NAME, version = NoFear.VERSION)
public class NoFear
{
    public static final String MODID = "nofear";
    public static final String NAME = "No fear";
    public static final String VERSION = "1.0";

    private static Logger logger;

    @EventHandler
    public void preLoad(FMLPreInitializationEvent event)
    {
        logger = event.getModLog();
        logger.info("PRELOAD");

    }

    @SubscribeEvent
    public static void registerBlocks(RegistryEvent.Register<Block> event) {
        event.getRegistry().register(new BlockTigerMuzzle());
    }

    @EventHandler
    public void preInit(FMLPreInitializationEvent event)
    {
    }

    @EventHandler
    public void init(FMLInitializationEvent event)
    {
    }
}
</code>```

and block`s class:

```<code>public class BlockTigerMuzzle extends Block {

    public BlockTigerMuzzle() {
        super(Material.IRON);
        this.setRegistryName("nofear","tigermuzzle");
        this.setCreativeTab(CreativeTabs.SEARCH);
        this.setHardness(15F);
        this.setResistance(10F);
        this.setHarvestLevel("pickaxe", 3);
        this.setLightLevel(0F);
        this.setUnlocalizedName("Tiger muzzle");

    }
}
</code>```

blockstates:

```<code>{
  "forge_marker": 1,
  "variants": {
    "normal": {
      "model": "nofear:tigermuzzle"
    },
    "inventory": {
      "model": "nofear:tigermuzzle",
      "transform": "forge:default-block"
    }
  }
}
</code>```

and finally block`s model:

```<code>{
  "ambientocclusion": false,
  "textures": {
    "muzzle": "nofear:blocks/tigermuzzle"
  },
  "elements": [
    {
      "from": [ 0, 0, 0 ],
      "to": [ 16, 16, 16 ],
      "faces": {
        "down":  { "texture": "#muzzle", "cullface": "down" },
        "up":    { "texture": "#muzzle", "cullface": "up" },
        "north": { "texture": "#muzzle", "cullface": "north" },
        "south": { "texture": "#muzzle", "cullface": "south" },
        "west":  { "texture": "#muzzle", "cullface": "west" },
        "east":  { "texture": "#muzzle", "cullface": "east" }
      }
    }
  ]
}
</code>```

Title: Minecraft Forge Mod blocks not showing

Body:
I have the same problem. Can`t see my block in tabs , and even command "/give playername @mymod:myblock 1" returns "There is no such item with name @mymod:myblock".

There is my main mod class code:

@Mod.EventBusSubscriber
@Mod(modid = NoFear.MODID, name = NoFear.NAME, version = NoFear.VERSION)
public class NoFear
{
    public static final String MODID = "nofear";
    public static final String NAME = "No fear";
    public static final String VERSION = "1.0";

    private static Logger logger;

    @EventHandler
    public void preLoad(FMLPreInitializationEvent event)
    {
        logger = event.getModLog();
        logger.info("PRELOAD");

    }

    @SubscribeEvent
    public static void registerBlocks(RegistryEvent.Register<Block> event) {
        event.getRegistry().register(new BlockTigerMuzzle());
    }

    @EventHandler
    public void preInit(FMLPreInitializationEvent event)
    {
    }

    @EventHandler
    public void init(FMLInitializationEvent event)
    {
    }
}

and block`s class:

public class BlockTigerMuzzle extends Block {

    public BlockTigerMuzzle() {
        super(Material.IRON);
        this.setRegistryName("nofear","tigermuzzle");
        this.setCreativeTab(CreativeTabs.SEARCH);
        this.setHardness(15F);
        this.setResistance(10F);
        this.setHarvestLevel("pickaxe", 3);
        this.setLightLevel(0F);
        this.setUnlocalizedName("Tiger muzzle");

    }
}

blockstates:

{
  "forge_marker": 1,
  "variants": {
    "normal": {
      "model": "nofear:tigermuzzle"
    },
    "inventory": {
      "model": "nofear:tigermuzzle",
      "transform": "forge:default-block"
    }
  }
}

and finally block`s model:

{
  "ambientocclusion": false,
  "textures": {
    "muzzle": "nofear:blocks/tigermuzzle"
  },
  "elements": [
    {
      "from": [ 0, 0, 0 ],
      "to": [ 16, 16, 16 ],
      "faces": {
        "down":  { "texture": "#muzzle", "cullface": "down" },
        "up":    { "texture": "#muzzle", "cullface": "up" },
        "north": { "texture": "#muzzle", "cullface": "north" },
        "south": { "texture": "#muzzle", "cullface": "south" },
        "west":  { "texture": "#muzzle", "cullface": "west" },
        "east":  { "texture": "#muzzle", "cullface": "east" }
      }
    }
  ]
}


问:
Get selected option ID from populated list
I have a radiobutton list that is populated from MySQL. A function to be called when the selected radiobutton changes. I would like to be get the ID of the selected item.

```<code> <ul id="radio" class="input-list">
<?php
$stmt = mysqli_prepare($link, "SELECT id, name, price FROM cases ORDER BY price");
$stmt->execute();
$stmt->bind_result($case_id, $case_name, $case_price);
while($stmt->fetch()) {
echo '<li>
<input class="selectedoptions" id="'.$case_id.'" name="config-case" value="'.$case_price.'" type="radio" onchange="updateImage(this.id);">
<label class="sub-label" for="'.$case_id.'">'.$case_name.'         [£'.$case_price.']</label>
</li>';
}
$stmt->close();
>
</ul>
</code>```

JS:

```<code><script>

    function updateImage(caseid) {

        var selectmenuID = document.getElementById(caseid);
        console.log(selectmenuID);
    }

<script>
</code>```

Attempting to get the id of the selected item is not successful. This is the console output:

```<code><input class="selectedoptions" id="32" name="config-case" value="24"
type="radio" onchange="updateImage(this.id);">
</code>```

I would like to get the 32 (the id). How can I do this? Thank you,

答:
maybe this is could help you:

```<code><script>
    function updateImage(caseid) {

        const selectmenuID = document.getElementById(caseid);
        const id  = selectmenuID.options[e.selectmenuID].value;

        // console your answer
        console.log(id);
    }
<script>
</code>```

This is the best way using javascript.

Body:
I have a radiobutton list that is populated from MySQL. A function to be called when the selected radiobutton changes. I would like to be get the ID of the selected item.

<?php
$stmt = mysqli_prepare($link, "SELECT id, name, price FROM cases ORDER BY price");
$stmt->execute();
$stmt->bind_result($case_id, $case_name, $case_price);
while($stmt->fetch()) {
echo '

<input class="selectedoptions" id="'.$case_id.'" name="config-case" value="'.$case_price.'" type="radio" onchange="updateImage(this.id);">
'.$case_name.'         [£'.$case_price.']

';
}
$stmt->close();
>

JS:

Body:
maybe this is could help you:

<script>
    function updateImage(caseid) {

        const selectmenuID = document.getElementById(caseid);
        const id  = selectmenuID.options[e.selectmenuID].value;

        // console your answer
        console.log(id);
    }
<script>

This is the best way using javascript.


问:
Why two HTTP and TCP addresses can use the same port and two IPC addresses cannot use the same named pipe?
What I think of a port is: Whenever a message arrives to a machine, it is copied to a memory area which is mapped to the port specified and the concerned application or service is notified that a message has arrived for it.

If this is true, then what happens if two messages arrive for two different services listening on the same port ? ( either http or tcp )

And why can not two named pipe addresses use the same named pipe ?

答:
Your description is one way to handle incoming messages.

In the case of two web sites listening on the same port, there is one web server listening on that port, which then looks at the http host header to find the correct web site to forward the request to.

The same is true for named pipes, the RPC listener listens on the TCP port, and then finds out that it is a named pipe message and then forwards the message to the right named pipe.


问:
Can anyone provide step by step process to implement SAML
I have a situation where I currently call web focus reports from our JAVA web applications. But is not a secured way calling and I wanted to implement SAML authentication and pass parameters through SAML. Any help in this regard will be great help</p>

答:
Is there a reason you need SAML?

OpenID Connect is a much easier option.

For SAML, you need to implement a SAML stack.

There is more information here.