问:
Cannot create resource in keycloak - Getting unknown exception
In keycloak admin when I try to create a resource, I get a '500' unknown exception error.  Looking at the logs, it appears a search call is made on the new resource name that returns the '500' error because media type is not present?  I have not done any customizations or set any properties on my instance.

Keycloak version is 10.0 and i've used Oracle jdk 8 and open jdk 11
The full error trace is:

```<code>08:41:02,795 ERROR [org.keycloak.headers.DefaultSecurityHeadersProvider] (default task-15) MediaType not set on path /auth/admin/realms/MyRealm/clients/6d7c8a64-e725-41f3-a488-9e150eed57cf/authz/resource-server/resource/search, with response status 200
08:41:02,807 ERROR [org.keycloak.services.error.KeycloakErrorHandler] (default task-15) Uncaught server error: javax.ws.rs.InternalServerErrorException: HTTP 500 Internal Server Error
        at org.keycloak.keycloak-services@10.0.0//org.keycloak.headers.DefaultSecurityHeadersProvider.addHeaders(DefaultSecurityHeadersProvider.java:71)
        at org.keycloak.keycloak-services@10.0.0//org.keycloak.services.filters.KeycloakSecurityHeadersFilter.filter(KeycloakSecurityHeadersFilter.java:36)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.core.interception.ContainerResponseContextImpl.filter(ContainerResponseContextImpl.java:356)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.core.ServerResponseWriter.executeFilters(ServerResponseWriter.java:219)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.core.ServerResponseWriter.writeNomapResponse(ServerResponseWriter.java:95)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.core.ServerResponseWriter.writeNomapResponse(ServerResponseWriter.java:69)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.core.SynchronousDispatcher.writeResponse(SynchronousDispatcher.java:530)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:461)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:229)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:135)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.core.interception.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:356)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:138)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:215)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:227)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51)
        at javax.servlet.api@2.0.0.Final//javax.servlet.http.HttpServlet.service(HttpServlet.java:590)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
        at org.keycloak.keycloak-services@10.0.0//org.keycloak.services.filters.KeycloakSessionServletFilter.doFilter(KeycloakSessionServletFilter.java:91)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
        at org.wildfly.extension.undertow@19.0.0.Final//org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
        at io.undertow.core@2.0.30.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:132)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
        at io.undertow.core@2.0.30.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at io.undertow.core@2.0.30.Final//io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
        at io.undertow.core@2.0.30.Final//io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
        at io.undertow.core@2.0.30.Final//io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
        at io.undertow.core@2.0.30.Final//io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
        at io.undertow.core@2.0.30.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at org.wildfly.extension.undertow@19.0.0.Final//org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
        at io.undertow.core@2.0.30.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at org.wildfly.extension.undertow@19.0.0.Final//org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
        at io.undertow.core@2.0.30.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:269)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:78)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:133)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:130)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
        at org.wildfly.extension.undertow@19.0.0.Final//org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
        at org.wildfly.extension.undertow@19.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
        at org.wildfly.extension.undertow@19.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
        at org.wildfly.extension.undertow@19.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
        at org.wildfly.extension.undertow@19.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:249)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:78)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:99)
        at io.undertow.core@2.0.30.Final//io.undertow.server.Connectors.executeRootHandler(Connectors.java:376)
        at io.undertow.core@2.0.30.Final//io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
        at org.jboss.threads@2.3.3.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
        at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
        at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
        at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
        at java.base/java.lang.Thread.run(Thread.java:834)
</code>```

答: This is the bug KEYCLOAK-14098 affecting 10.0.0 release fixed in 10.0.1 </p>

Body:
In keycloak admin when I try to create a resource, I get a '500' unknown exception error.  Looking at the logs, it appears a search call is made on the new resource name that returns the '500' error because media type is not present?  I have not done any customizations or set any properties on my instance.

Keycloak version is 10.0 and i've used Oracle jdk 8 and open jdk 11
The full error trace is:

08:41:02,795 ERROR [org.keycloak.headers.DefaultSecurityHeadersProvider] (default task-15) MediaType not set on path /auth/admin/realms/MyRealm/clients/6d7c8a64-e725-41f3-a488-9e150eed57cf/authz/resource-server/resource/search, with response status 200
08:41:02,807 ERROR [org.keycloak.services.error.KeycloakErrorHandler] (default task-15) Uncaught server error: javax.ws.rs.InternalServerErrorException: HTTP 500 Internal Server Error
        at org.keycloak.keycloak-services@10.0.0//org.keycloak.headers.DefaultSecurityHeadersProvider.addHeaders(DefaultSecurityHeadersProvider.java:71)
        at org.keycloak.keycloak-services@10.0.0//org.keycloak.services.filters.KeycloakSecurityHeadersFilter.filter(KeycloakSecurityHeadersFilter.java:36)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.core.interception.ContainerResponseContextImpl.filter(ContainerResponseContextImpl.java:356)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.core.ServerResponseWriter.executeFilters(ServerResponseWriter.java:219)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.core.ServerResponseWriter.writeNomapResponse(ServerResponseWriter.java:95)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.core.ServerResponseWriter.writeNomapResponse(ServerResponseWriter.java:69)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.core.SynchronousDispatcher.writeResponse(SynchronousDispatcher.java:530)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:461)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:229)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:135)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.core.interception.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:356)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:138)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:215)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:227)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56)
        at org.jboss.resteasy.resteasy-jaxrs@3.11.0.Final//org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51)
        at javax.servlet.api@2.0.0.Final//javax.servlet.http.HttpServlet.service(HttpServlet.java:590)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
        at org.keycloak.keycloak-services@10.0.0//org.keycloak.services.filters.KeycloakSessionServletFilter.doFilter(KeycloakSessionServletFilter.java:91)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
        at org.wildfly.extension.undertow@19.0.0.Final//org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
        at io.undertow.core@2.0.30.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:132)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
        at io.undertow.core@2.0.30.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at io.undertow.core@2.0.30.Final//io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
        at io.undertow.core@2.0.30.Final//io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
        at io.undertow.core@2.0.30.Final//io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
        at io.undertow.core@2.0.30.Final//io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
        at io.undertow.core@2.0.30.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at org.wildfly.extension.undertow@19.0.0.Final//org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
        at io.undertow.core@2.0.30.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at org.wildfly.extension.undertow@19.0.0.Final//org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
        at io.undertow.core@2.0.30.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:269)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:78)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:133)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:130)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
        at org.wildfly.extension.undertow@19.0.0.Final//org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
        at org.wildfly.extension.undertow@19.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
        at org.wildfly.extension.undertow@19.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
        at org.wildfly.extension.undertow@19.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
        at org.wildfly.extension.undertow@19.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:249)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:78)
        at io.undertow.servlet@2.0.30.Final//io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:99)
        at io.undertow.core@2.0.30.Final//io.undertow.server.Connectors.executeRootHandler(Connectors.java:376)
        at io.undertow.core@2.0.30.Final//io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
        at org.jboss.threads@2.3.3.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
        at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
        at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
        at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
        at java.base/java.lang.Thread.run(Thread.java:834)


来源: stackexchange

问:
Responsive images in inline SVG
I have tried to find an example or answer to this but haven't been able to do so.

The way we optimize images so that unnecessary large images doesn't have to be loaded when they don't need to, can be done like in the example below:

```<code><img src="http://localhost:8888/example.jpg" alt="sample 1" srcset="http://localhost:8888/example-1024x1024.jpg 1000w, http://localhost:8888/example-300x300.jpg 300w, http://localhost:8888/example-150x150.jpg 150w, http://localhost:8888/example-768x768.jpg 768w" sizes="(max-width: 1000px) 100vw, 1000px">
</code>```

So my question is if this could also be done the same way or in some other way with images used in inline SVG for optimization.

Image used in SVG like in this example:

```<code><svg role="img" width="100%" height="100%">
  <title>Ocean wave</title>
  <desc>Ocean wave in crystal clear blue water.</desc>
  <defs>
    <filter id="blur">
      ...
    </filter>
  </defs>
  <image href="img/image.jpg" width="100%" height="100%" preserveAspectRatio="xMidYMid slice"></image>
</svg>
</code>```

答:
Using the <foreignObject> instead of <image> seems to do the trick as this enables you to use any kind of HTML element inside the SVG.

```<code><svg role="img" width="100%" height="100%">
  <title>Ocean wave</title>
  <desc>Ocean wave in crystal clear blue water.</desc>
  <defs>
    <filter id="blur">
      ...
    </filter>
  </defs>
  <foreignObject width="100%" height="100%">
    <img src="img/image.jpg" alt="sample 1" srcset="http://localhost:8888/example-1024x1024.jpg 1000w, http://localhost:8888/example-300x300.jpg 300w, http://localhost:8888/example-150x150.jpg 150w, http://localhost:8888/example-768x768.jpg 768w" sizes="(max-width: 1000px) 100vw, 1000px">
  </foreignObject>
</svg>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Responsive images in inline SVG

Body:
I have tried to find an example or answer to this but haven't been able to do so.

The way we optimize images so that unnecessary large images doesn't have to be loaded when they don't need to, can be done like in the example below:

So my question is if this could also be done the same way or in some other way with images used in inline SVG for optimization.

Image used in SVG like in this example:

<svg role="img" width="100%" height="100%">
  <title>Ocean wave</title>
  <desc>Ocean wave in crystal clear blue water.</desc>
  <defs>
    <filter id="blur">
      ...
    </filter>
  </defs>
  <image href="img/image.jpg" width="100%" height="100%" preserveAspectRatio="xMidYMid slice"></image>
</svg>

Body:
Using the <foreignObject> instead of <image> seems to do the trick as this enables you to use any kind of HTML element inside the SVG.

<svg role="img" width="100%" height="100%">
  <title>Ocean wave</title>
  <desc>Ocean wave in crystal clear blue water.</desc>
  <defs>
    <filter id="blur">
      ...
    </filter>
  </defs>
  <foreignObject width="100%" height="100%">
    <img src="img/image.jpg" alt="sample 1" srcset="http://localhost:8888/example-1024x1024.jpg 1000w, http://localhost:8888/example-300x300.jpg 300w, http://localhost:8888/example-150x150.jpg 150w, http://localhost:8888/example-768x768.jpg 768w" sizes="(max-width: 1000px) 100vw, 1000px">
  </foreignObject>
</svg>


问:
Use SpeechSynthesizer in Dutch
I want to use tts in c# and my code works fine for English, but now I want to use it in Dutch.

```<code>private void btnSpeak_Click(object sender, EventArgs e)
{
     SpeechSynthesizer synthesizer = new SpeechSynthesizer();

     foreach (var v in synthesizer.GetInstalledVoices(CultureInfo.CurrentCulture))
     {
         VoiceInfo info = v.VoiceInfo;
         OutputVoiceInfo(info);
     }

     synthesizer.SelectVoiceByHints(VoiceGender.Male, VoiceAge.Adult, 0, CultureInfo.CurrentCulture);
     synthesizer.Volume = 100;  // 0...100
     synthesizer.Rate = 1;     // -10...10

     // Synchronous
     if(textBox1.Text != null)
         synthesizer.SpeakAsync(textBox1.Text);
}

private static void OutputVoiceInfo(VoiceInfo info)
{
     Console.WriteLine("Name: {0}, culture: {1}, gender: {2}, age: {3}.\n", info.Name, info.Culture, info.Gender, info.Age);
     Console.WriteLine("Description: {0}\n", info.Description);
}
</code>```

Is there anything I should install so it is capable of speaking Dutch?

答:
I had similar issues. Running the following PowerShell resolved it:

```<code>$sourcePath = 'HKLM:\software\Microsoft\Speech_OneCore\Voices\Tokens' #Where the OneCore voices live
$destinationPath = 'HKLM:\SOFTWARE\Microsoft\Speech\Voices\Tokens' #For 64-bit apps
$destinationPath2 = 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\SPEECH\Voices\Tokens' #For 32-bit apps
cd $destinationPath
$listVoices = Get-ChildItem $sourcePath
foreach($voice in $listVoices)
{
$source = $voice.PSPath #Get the path of this voices key
copy -Path $source -Destination $destinationPath -Recurse
copy -Path $source -Destination $destinationPath2 -Recurse
}
</code>```

Source: https://gist.github.com/hiepxanh/8b6ad80f6d620cd3eaaaa5c1d2c660b2

Running your example uses the Dutch TTS engine Microsoft Frank.

ContentLicense: CC BY-SA 3.0

Title: Use SpeechSynthesizer in Dutch

Body:
I want to use tts in c# and my code works fine for English, but now I want to use it in Dutch.

private void btnSpeak_Click(object sender, EventArgs e)
{
     SpeechSynthesizer synthesizer = new SpeechSynthesizer();

     foreach (var v in synthesizer.GetInstalledVoices(CultureInfo.CurrentCulture))
     {
         VoiceInfo info = v.VoiceInfo;
         OutputVoiceInfo(info);
     }

     synthesizer.SelectVoiceByHints(VoiceGender.Male, VoiceAge.Adult, 0, CultureInfo.CurrentCulture);
     synthesizer.Volume = 100;  // 0...100
     synthesizer.Rate = 1;     // -10...10

     // Synchronous
     if(textBox1.Text != null)
         synthesizer.SpeakAsync(textBox1.Text);
}

private static void OutputVoiceInfo(VoiceInfo info)
{
     Console.WriteLine("Name: {0}, culture: {1}, gender: {2}, age: {3}.\n", info.Name, info.Culture, info.Gender, info.Age);
     Console.WriteLine("Description: {0}\n", info.Description);
}

Is there anything I should install so it is capable of speaking Dutch?

Body:
I had similar issues. Running the following PowerShell resolved it:

$sourcePath = 'HKLM:\software\Microsoft\Speech_OneCore\Voices\Tokens' #Where the OneCore voices live
$destinationPath = 'HKLM:\SOFTWARE\Microsoft\Speech\Voices\Tokens' #For 64-bit apps
$destinationPath2 = 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\SPEECH\Voices\Tokens' #For 32-bit apps
cd $destinationPath
$listVoices = Get-ChildItem $sourcePath
foreach($voice in $listVoices)
{
$source = $voice.PSPath #Get the path of this voices key
copy -Path $source -Destination $destinationPath -Recurse
copy -Path $source -Destination $destinationPath2 -Recurse
}

Source: https://gist.github.com/hiepxanh/8b6ad80f6d620cd3eaaaa5c1d2c660b2

Running your example uses the Dutch TTS engine Microsoft Frank.


问:
How to loop a menu if wrong selection occurred
I am trying to loop a menu when the user insert wrong choice:

```<code>public static void main(String[] args) {

    Scanner YourChoice = new Scanner(System.in);

    System.out.println("+-------------------------+");
    System.out.println("|        Welcome          |");
    System.out.println("|    To this program      |");
    System.out.println("+-------------------------+");
    System.out.println();

    System.out.println("Please Choose your preference: ");
    System.out.println();
    System.out.println("Press 1 - Test1");
    System.out.println("Press 2 - Test2");
    System.out.println("Press 3 - Test3");
    System.out.println("Press 0 - Exit");

    System.out.println();
    System.out.print("Your Choice is: ");
    int CHOICE = YourChoice.nextInt();

    if (CHOICE == 1) {
        System.out.println("You want Test1");
    }
    else if (CHOICE == 2) {
        System.out.println("You want Test2");
    }
    else if (CHOICE == 3) {
        System.out.println("You want Test3");
    }
    else if (CHOICE == 0) {
        System.out.println("You want Exit");
    }
    else {
        System.out.println("Wrong Input, please try again");

    }
</code>```

What I want is, if a user inserted wrong number, then the menu should start again, until the user enters a correct value (0 to 3).
I am not sure where and how to put the while loop,
Could you please clarify it?

答:
public static void main(String[] args)
    {

```<code>int CHOICE;
Scanner YourChoice = new Scanner(System.in);

System.out.println("+-------------------------+");
System.out.println("|        Welcome          |");
System.out.println("|    To this program      |");
System.out.println("+-------------------------+");
System.out.println();
while(true)
{
   System.out.println("Please Choose your preference: ");
   System.out.println();
   System.out.println("Press 1 - Test1");
   System.out.println("Press 2 - Test2");
   System.out.println("Press 3 - Test3");
   System.out.println("Press 0 - Exit");

   System.out.println();
   System.out.print("Your Choice is: ");
   CHOICE = YourChoice.nextInt();

   if (CHOICE == 1)
   {
      System.out.println("You want Test1");
   }
   else if (CHOICE == 2)
   {
      System.out.println("You want Test2");
   }
   else if (CHOICE == 3)
   {
      System.out.println("You want Test3");
   }
   else if (CHOICE == 0)
   {
      System.out.println("You want Exit");
      System.exit(0);
   }
   else
   {
       System.out.println("Wrong Input, please try again");

   }
</code>```

}
 }

Body:
I am trying to loop a menu when the user insert wrong choice:

public static void main(String[] args) {

    Scanner YourChoice = new Scanner(System.in);

    System.out.println("+-------------------------+");
    System.out.println("|        Welcome          |");
    System.out.println("|    To this program      |");
    System.out.println("+-------------------------+");
    System.out.println();

    System.out.println("Please Choose your preference: ");
    System.out.println();
    System.out.println("Press 1 - Test1");
    System.out.println("Press 2 - Test2");
    System.out.println("Press 3 - Test3");
    System.out.println("Press 0 - Exit");

    System.out.println();
    System.out.print("Your Choice is: ");
    int CHOICE = YourChoice.nextInt();

    if (CHOICE == 1) {
        System.out.println("You want Test1");
    }
    else if (CHOICE == 2) {
        System.out.println("You want Test2");
    }
    else if (CHOICE == 3) {
        System.out.println("You want Test3");
    }
    else if (CHOICE == 0) {
        System.out.println("You want Exit");
    }
    else {
        System.out.println("Wrong Input, please try again");

    }

What I want is, if a user inserted wrong number, then the menu should start again, until the user enters a correct value (0 to 3).
I am not sure where and how to put the while loop,
Could you please clarify it?

Body:
public static void main(String[] args)
    {

int CHOICE;
Scanner YourChoice = new Scanner(System.in);

System.out.println("+-------------------------+");
System.out.println("|        Welcome          |");
System.out.println("|    To this program      |");
System.out.println("+-------------------------+");
System.out.println();
while(true)
{
   System.out.println("Please Choose your preference: ");
   System.out.println();
   System.out.println("Press 1 - Test1");
   System.out.println("Press 2 - Test2");
   System.out.println("Press 3 - Test3");
   System.out.println("Press 0 - Exit");

   System.out.println();
   System.out.print("Your Choice is: ");
   CHOICE = YourChoice.nextInt();

   if (CHOICE == 1)
   {
      System.out.println("You want Test1");
   }
   else if (CHOICE == 2)
   {
      System.out.println("You want Test2");
   }
   else if (CHOICE == 3)
   {
      System.out.println("You want Test3");
   }
   else if (CHOICE == 0)
   {
      System.out.println("You want Exit");
      System.exit(0);
   }
   else
   {
       System.out.println("Wrong Input, please try again");

   }

}
 }


问:
How to fix "Error: listen EADDRINUSE: address already in use :::5000" Unhandled 'error' event
i create a nodejs server (a loginapp) but when i try to node app a error (she was not here before) came out :

```<code>events.js:167
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE: address already in use :::5000
    at Server.setupListenHandle [as _listen2] (net.js:1290:14)
    at listenInCluster (net.js:1338:12)
    at Server.listen (net.js:1425:7)
    at Function.listen (C:\Users\Corentin\Documents\loginapp\node_modules\express\lib\application.js:618:24)
    at Object.<anonymous> (C:\Users\Corentin\Documents\loginapp\app.js:81:5)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
Emitted 'error' event at:
    at emitErrorNT (net.js:1317:8)
    at process._tickCallback (internal/process/next_tick.js:63:19)
    at Function.Module.runMain (internal/modules/cjs/loader.js:745:11)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
</code>```

I think there is a link with mongo but i didnt see the error,

This is my app.js code (NOT FULL) ask me if you need more of my code

```<code>var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var bodyParser = require('body-parser');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local'),Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/loginapp', { useNewUrlParser: true });
var db = mongoose.connection;

var routes = require('./routes/index');
var users = require('./routes/users');

// APP INIT
var app = express();

// VIEW ENGINE
app.set('views', path.join(__dirname,'views'));
app.engine('handlebars', exphbs({ defaultLayout:'layout' }));
app.set('view engine','handlebars');

app.use('/', routes);
app.use('/users', users);

// SET PORT
app.set('port', (5000));

app.listen(app.get('port'), () => {
    console.log('Server lancé sur le port ' + app.get('port'));
});
</code>```

This is my users.js file

```<code>var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');

var User = require('../models/user');

// REGISTER
router.get('/register', (req, res) => {
    res.render('register');
});

// LOGIN
router.get('/login', (req, res) => {
    res.render('login');
});

// REGISTER
router.post('/register', (req, res) => {
    var name = req.body.name;
    var username = req.body.username;
    var email = req.body.email;
    var password = req.body.password;
    var password2 = req.body.password2;

    // VALIDATION
    req.checkBody('name','Name is required').notEmpty();
    req.checkBody('username','Username is required').notEmpty();
    req.checkBody('email','Email is required').notEmpty();
    req.checkBody('email','Email is not valid').isEmail();
    req.checkBody('password','Password is required').notEmpty();
    req.checkBody('password2','Passwords do not match').equals(req.body.password);

    var errors = req.validationErrors();

    if(errors) {
        res.render('register', {
            errors:errors
        });
    } else {
        var newUser = new User({
            name: name,
            username: username,
            email: email,
            password: password
        });

        User.createUser(newUser, function(err, user) {
            if(err) throw err;
            console.log(user);
        });

        req.flash('success_msg', 'You are now registered and u can log');

        res.redirect('/users/login');
    }
});

module.exports = router;
</code>```

And the user.js file

```<code>var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');

// USER SCHEMA
var UserSchema = mongoose.Schema({
    username: {
        type: String,
        index: true
    },
    name: {
        type: String
    },
    email: {
        type: String
    },
    password: {
        type: String
    }
});

var User = module.exports = mongoose.model('User', UserSchema);

module.exports.createUser = function(newUser, callback) {
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(newUser.password, salt, function(err, hash) {
            newUser.password = hash;
            newUser.save(callback);
        });
    });
}
</code>```

Thank a lot to the person who can help me !

答:
restart your laptop/server, it will release all the busy ports, then try again...u can also use

```<code>ps aux | grep node
</code>```

and then  kill the process using:

```<code>kill -9 PID
</code>```

but most of the times it wont work for nodemon, and didnt work for me.

Body:
i create a nodejs server (a loginapp) but when i try to node app a error (she was not here before) came out :

events.js:167
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE: address already in use :::5000
    at Server.setupListenHandle [as _listen2] (net.js:1290:14)
    at listenInCluster (net.js:1338:12)
    at Server.listen (net.js:1425:7)
    at Function.listen (C:\Users\Corentin\Documents\loginapp\node_modules\express\lib\application.js:618:24)
    at Object.<anonymous> (C:\Users\Corentin\Documents\loginapp\app.js:81:5)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
Emitted 'error' event at:
    at emitErrorNT (net.js:1317:8)
    at process._tickCallback (internal/process/next_tick.js:63:19)
    at Function.Module.runMain (internal/modules/cjs/loader.js:745:11)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)

I think there is a link with mongo but i didnt see the error,

This is my app.js code (NOT FULL) ask me if you need more of my code

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var bodyParser = require('body-parser');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local'),Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/loginapp', { useNewUrlParser: true });
var db = mongoose.connection;

var routes = require('./routes/index');
var users = require('./routes/users');

// APP INIT
var app = express();

// VIEW ENGINE
app.set('views', path.join(__dirname,'views'));
app.engine('handlebars', exphbs({ defaultLayout:'layout' }));
app.set('view engine','handlebars');

app.use('/', routes);
app.use('/users', users);

// SET PORT
app.set('port', (5000));

app.listen(app.get('port'), () => {
    console.log('Server lancé sur le port ' + app.get('port'));
});

This is my users.js file

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');

var User = require('../models/user');

// REGISTER
router.get('/register', (req, res) => {
    res.render('register');
});

// LOGIN
router.get('/login', (req, res) => {
    res.render('login');
});

// REGISTER
router.post('/register', (req, res) => {
    var name = req.body.name;
    var username = req.body.username;
    var email = req.body.email;
    var password = req.body.password;
    var password2 = req.body.password2;

    // VALIDATION
    req.checkBody('name','Name is required').notEmpty();
    req.checkBody('username','Username is required').notEmpty();
    req.checkBody('email','Email is required').notEmpty();
    req.checkBody('email','Email is not valid').isEmail();
    req.checkBody('password','Password is required').notEmpty();
    req.checkBody('password2','Passwords do not match').equals(req.body.password);

    var errors = req.validationErrors();

    if(errors) {
        res.render('register', {
            errors:errors
        });
    } else {
        var newUser = new User({
            name: name,
            username: username,
            email: email,
            password: password
        });

        User.createUser(newUser, function(err, user) {
            if(err) throw err;
            console.log(user);
        });

        req.flash('success_msg', 'You are now registered and u can log');

        res.redirect('/users/login');
    }
});

module.exports = router;

And the user.js file

var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');

// USER SCHEMA
var UserSchema = mongoose.Schema({
    username: {
        type: String,
        index: true
    },
    name: {
        type: String
    },
    email: {
        type: String
    },
    password: {
        type: String
    }
});

var User = module.exports = mongoose.model('User', UserSchema);

module.exports.createUser = function(newUser, callback) {
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(newUser.password, salt, function(err, hash) {
            newUser.password = hash;
            newUser.save(callback);
        });
    });
}

Thank a lot to the person who can help me !

Body:
restart your laptop/server, it will release all the busy ports, then try again...u can also use

ps aux | grep node

and then  kill the process using:

kill -9 PID

but most of the times it wont work for nodemon, and didnt work for me.


问:
Invoking manual sync of Azure App Services via webhook is failing with 401 error
I'm trying to invoke the Azure App Service sync function via a HTTP call rather than Azure PowerShell to for a git pull and update.

From what I understand this should be achievable by calling

```<code>https://[sitename]:[sitepasswd]@[sitename].scm.azurewebsites.net/deploy
</code>```

with a json payload of

```<code>{
    "format": "basic",
    "url": "https://github.com/[gituser]/[repo]"
}
</code>```

This call is however failing with a LibGit2Sharp.LibGit2SharpException: Request failed with status code: 401 exception. Specifying a github username and password in the request does not resolve the issue.

Syncing via portal and PowerShell works fine, so I assume I'm missing a parameter somewhere. Any ideas?

答:
The scm site uses single sign on, so if you're already logged on to the Azure portal, you will be able to go directly to it without typing additional credentials. Sync via portal and powershell which us your user credential to login.

If you prefer not to use Single Sign On and instead use basic auth, you can go to http://mysite.scm.azurewebsites.net/basicauth. The scm service will prompt you for credentials. Here, you can use either the user publishing credentials (same as you use for git), or the site level credentials. See Deployment-credentials for details.

Body:
I'm trying to invoke the Azure App Service sync function via a HTTP call rather than Azure PowerShell to for a git pull and update.

From what I understand this should be achievable by calling

https://[sitename]:[sitepasswd]@[sitename].scm.azurewebsites.net/deploy

with a json payload of

{
    "format": "basic",
    "url": "https://github.com/[gituser]/[repo]"
}

This call is however failing with a LibGit2Sharp.LibGit2SharpException: Request failed with status code: 401 exception. Specifying a github username and password in the request does not resolve the issue.

Syncing via portal and PowerShell works fine, so I assume I'm missing a parameter somewhere. Any ideas?


问:
TypeError: %d format: a number is required, not str - DB field is string, variable passed is number in string format
I have a query which filters based on a string field, containing phone numbers with leading zero. My query uses %s as a placeholder with the variable passed to the query at execution time as so:

```<code>rows = (('01234567891',), ('01234567892',), ('01234567893',))

dbQuery2 = """
SELECT DATE_FORMAT(DATE(ch.start), '%d/%m/%Y') As CallDate,
             ch.did AS InboundNo,
             COUNT(*) AS DayTotal
      FROM call_history ch LEFT JOIN
           ast_queue_log aql
           ON aql.event = 'ENTERQUEUE' AND aql.callid = ch.callid
      WHERE ch.did = %s AND
            ch.start BETWEEN DATE_FORMAT(NOW(), '%Y-%m-01') AND NOW()
      GROUP BY ch.did, DATE(ch.start)
      ORDER BY ch.did, DATE(ch.start)
     ;
"""

for row in rows:
    cur2.execute(dbQuery2, row)
    subrows = cur.fetchall()
</code>```

The DB field that causes an issue is:

```<code>`did` varchar(32) NOT NULL DEFAULT '',`
</code>```

The error is:

```<code>TypeError: %d format: a number is required, not str
</code>```

答:
The issue here are the DATE_FORMAT strings in the SQL query. The %d, %m and %Y are interpreted as variable placeholders and the MySQLdb engine tries to substitute the variable in there rather than in the WHERE clause.

Fixed by using the following format in the query:

```<code>dbQuery2 = """
SELECT DATE_FORMAT(DATE(ch.start), '%%d/%%m/%%Y') As CallDate,
         ch.did AS InboundNo,
         COUNT(*) AS DayTotal
  FROM call_history ch LEFT JOIN
       ast_queue_log aql
  ON aql.event = 'ENTERQUEUE' AND aql.callid = ch.callid
  WHERE ch.did = %s AND
            ch.start BETWEEN DATE_FORMAT(NOW(), '%%Y-%%m-01') AND NOW()
  GROUP BY ch.did, DATE(ch.start)
  ORDER BY ch.did, DATE(ch.start)
 ;
</code>```

"""

Body:
I have a query which filters based on a string field, containing phone numbers with leading zero. My query uses %s as a placeholder with the variable passed to the query at execution time as so:

rows = (('01234567891',), ('01234567892',), ('01234567893',))

dbQuery2 = """
SELECT DATE_FORMAT(DATE(ch.start), '%d/%m/%Y') As CallDate,
             ch.did AS InboundNo,
             COUNT(*) AS DayTotal
      FROM call_history ch LEFT JOIN
           ast_queue_log aql
           ON aql.event = 'ENTERQUEUE' AND aql.callid = ch.callid
      WHERE ch.did = %s AND
            ch.start BETWEEN DATE_FORMAT(NOW(), '%Y-%m-01') AND NOW()
      GROUP BY ch.did, DATE(ch.start)
      ORDER BY ch.did, DATE(ch.start)
     ;
"""

for row in rows:
    cur2.execute(dbQuery2, row)
    subrows = cur.fetchall()

The DB field that causes an issue is:

`did` varchar(32) NOT NULL DEFAULT '',`

The error is:

TypeError: %d format: a number is required, not str

Body:
The issue here are the DATE_FORMAT strings in the SQL query. The %d, %m and %Y are interpreted as variable placeholders and the MySQLdb engine tries to substitute the variable in there rather than in the WHERE clause.

Fixed by using the following format in the query:

dbQuery2 = """
SELECT DATE_FORMAT(DATE(ch.start), '%%d/%%m/%%Y') As CallDate,
         ch.did AS InboundNo,
         COUNT(*) AS DayTotal
  FROM call_history ch LEFT JOIN
       ast_queue_log aql
  ON aql.event = 'ENTERQUEUE' AND aql.callid = ch.callid
  WHERE ch.did = %s AND
            ch.start BETWEEN DATE_FORMAT(NOW(), '%%Y-%%m-01') AND NOW()
  GROUP BY ch.did, DATE(ch.start)
  ORDER BY ch.did, DATE(ch.start)
 ;

"""


问:
from where rpm query search and from where yum list search
I did rpm -qa and didn't found the package but when when I did yum list I found the package. why so and which command is useful in finding the installed packages in Linux?</p>

答:
I personally don't use yum or rpm to handle package management on my machine (running Debian 10 currently with XFCE) but I use the command apt list --installed to check my installed packages.  Then you can grep for whatever specific stuff you are looking for.

You could also check out this article. It's well written and has a lot of good info.

https://itsfoss.com/list-installed-packages-ubuntu/


问:
Is it possible to suppress Matplotlib/Seaborn output in Jupyter notebook?
All - reaching out for some guidance, if any available, to help solve this somewhat frustrating issue.

I am defining a function that creates a correlation matrix using Seaborn's annotated heatmap.  The function works fine, however, the Seaborn output is being produced automatically upon running the function without having to call it.

I wish to suppress this output and only produce it later on in the notebook when calling the correlation matrix, as you would do with a dataframe, other graph, etc.

Any solutions?  So far, I have tried adding semi-colons, put.ioff(), different assignments to the graph/axis objects.  To be honest, I am not sure if this is a Seaborn issue or one related to Matplotlib.  Maybe the function could be written in an alternative way to mitigate this limitation?

Code below.  Any help on this would be greatly appreciated, many thanks.

```<code># cormat is a correlation matrix

import matplotlib.pyplot as plt

def correl_heatmap(cormat):
    _f01, ax = plt.subplots(figsize=(cormat.shape[0], cormat.shape[0]));
    sns.heatmap(cormat,
                vmin=-1, vmax=1, center=0, square=True,
                annot=True, cmap='coolwarm_r', cbar_kws={'shrink': 0.8}, ax=ax);
    ax.set_xticklabels(ax.get_xticklabels(),
                       rotation=90,
                       horizontalalignment='center');
    ax.set_yticklabels(ax.get_yticklabels(),
                       rotation=90,
                       verticalalignment='center');
    return _f01

_f01 = correl_heatmap(cormat)
_f01
</code>```

答:
To suppress this output assign the return object a name:

```<code>_ = plt.plot(A)
</code>```

or

```<code>plot(A);
</code>```

Body:
All - reaching out for some guidance, if any available, to help solve this somewhat frustrating issue.

I am defining a function that creates a correlation matrix using Seaborn's annotated heatmap.  The function works fine, however, the Seaborn output is being produced automatically upon running the function without having to call it.

I wish to suppress this output and only produce it later on in the notebook when calling the correlation matrix, as you would do with a dataframe, other graph, etc.

Any solutions?  So far, I have tried adding semi-colons, put.ioff(), different assignments to the graph/axis objects.  To be honest, I am not sure if this is a Seaborn issue or one related to Matplotlib.  Maybe the function could be written in an alternative way to mitigate this limitation?

Code below.  Any help on this would be greatly appreciated, many thanks.

# cormat is a correlation matrix

import matplotlib.pyplot as plt

def correl_heatmap(cormat):
    _f01, ax = plt.subplots(figsize=(cormat.shape[0], cormat.shape[0]));
    sns.heatmap(cormat,
                vmin=-1, vmax=1, center=0, square=True,
                annot=True, cmap='coolwarm_r', cbar_kws={'shrink': 0.8}, ax=ax);
    ax.set_xticklabels(ax.get_xticklabels(),
                       rotation=90,
                       horizontalalignment='center');
    ax.set_yticklabels(ax.get_yticklabels(),
                       rotation=90,
                       verticalalignment='center');
    return _f01

_f01 = correl_heatmap(cormat)
_f01

Body:
To suppress this output assign the return object a name:

_ = plt.plot(A)

or

plot(A);


问:
Cloud Firestore/ Flutter - Map sorted by Database
When I simply upload a Map with the index values from A1 to A10, the List ist sorted like that:

A1, A10, A2, A3....

When I upload that List, it is sorted correctly (A1.A2..A10) but in Firebase it is resorted like I explained.

```<code>void updateList(newList) async {
  try {
    await Firestore.instance
        .collection("centers")
        .document(localUser.centerId)
        .updateData({
      "list": newList,
    });
  } catch (error) {}
}
</code>```

So how can I stop this auto-sort behaviour, I dont want to re-sort the list after getting it from Firebase.flutter

答:
What data type are you uploading exactly? A Map or an Array?

If you upload an Array the elements will maintain the position assigned to them.

If you upload a Map the elements will be sorted based on both the key and the value.

Based on the behavior you are describing, it looks like you are uploading a Map but expecting to download an Array. Regardless, if you are working with a Map you shouldn't care about the order since you will be accessing the values by key, is there any particular reason you would like to have a sorted dictionary?

To sum up, this is an expected behavior on Maps, you can read more about this in the documentation.

Body:
When I simply upload a Map with the index values from A1 to A10, the List ist sorted like that:

A1, A10, A2, A3....

When I upload that List, it is sorted correctly (A1.A2..A10) but in Firebase it is resorted like I explained.

void updateList(newList) async {
  try {
    await Firestore.instance
        .collection("centers")
        .document(localUser.centerId)
        .updateData({
      "list": newList,
    });
  } catch (error) {}
}

So how can I stop this auto-sort behaviour, I dont want to re-sort the list after getting it from Firebase.flutter


问:
org.elasticsearch.common.xcontent.DeprecationHandler Exception while using Elasticsearch REST High level client
I am getting the following exception while trying to use Elasticsearch high rest client.

I'm using Spring Boot 2.0.4 and Elasticsearch 6.4 versions.. The use case is simply to create an index with some data and then retrieving the same..

```<code>2018-08-24 14:25:44.185 ERROR 18768 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: org/elasticsearch/common/xcontent/DeprecationHandler] with root cause

java.lang.ClassNotFoundException: org.elasticsearch.common.xcontent.DeprecationHandler
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_144]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_144]
    at java.lang.ClassLoader.defineClass1(Native Method) ~[na:1.8.0_144]
    at java.lang.ClassLoader.defineClass(ClassLoader.java:763) ~[na:1.8.0_144]
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[na:1.8.0_144]
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:467) ~[na:1.8.0_144]
    at java.net.URLClassLoader.access$100(URLClassLoader.java:73) ~[na:1.8.0_144]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:368) ~[na:1.8.0_144]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:362) ~[na:1.8.0_144]
    at java.security.AccessController.doPrivileged(Native Method) ~[na:1.8.0_144]
    at java.net.URLClassLoader.findClass(URLClassLoader.java:361) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_144]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_144]
    at org.elasticsearch.client.RestHighLevelClient.<clinit>(RestHighLevelClient.java:1429) ~[elasticsearch-rest-high-level-client-6.4.0.jar:5.6.10]
    at com.softwareag.laasapi.rest.service.ElasticService.getClient(ElasticService.java:27) ~[classes/:na]
    at com.softwareag.laasapi.rest.service.ElasticService.getDocuments(ElasticService.java:57) ~[classes/:na]
    at com.softwareag.laasapi.rest.controller.LogsController.getDocuments(LogsController.java:52) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_144]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_144]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]
</code>```

I have just followed the elasticsearch documentation for dependencies and set up correctly.

My Gradle dependency is

```<code>dependencies {
   compile 'org.elasticsearch.client:elasticsearch-rest-high-level-client:6.4.0'
}
</code>```

For the sake of simplicity, given an short version of the code..

```<code>@RestController
public class ElasticController {

@RequestMapping("/posts")
public void getData() {

    RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", "9200","http")));

    GetRequest request = new GetRequest("posts", "doc", "1");
    GetResponse response = client.get(request, RequestOptions.DEFAULT);

    System.out.println(response.getSource().toString());

}
}
</code>```

Could anyone help on this?

答:
I struggled with this problem. Basically the root cause of this exception is version mismatch for Elastic-Search Lib, elasticsearch-rest-high-level-client and ElasticSearch Server .
I am using ElasticSearch Server 7.4 and Apache Flink 1.10. I have added following dependency in POM for Flink-Elastic-Search Sink:

```<code> <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-connector-elasticsearch7_2.11</artifactId>
            <version>1.10.0</version>
        </dependency>
    <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.4.0</version>

        </dependency>

        <!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.4.0</version>
        </dependency>
</code>```

This is working perfectly for me.

Note: Elastic-Search Server version and dependency version of elasticsearch-rest-high-level-client version, and Elastic-Search , SINK connector should be exactly same to avoid this issue.

Body:
I am getting the following exception while trying to use Elasticsearch high rest client.

I'm using Spring Boot 2.0.4 and Elasticsearch 6.4 versions.. The use case is simply to create an index with some data and then retrieving the same..

2018-08-24 14:25:44.185 ERROR 18768 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: org/elasticsearch/common/xcontent/DeprecationHandler] with root cause

java.lang.ClassNotFoundException: org.elasticsearch.common.xcontent.DeprecationHandler
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_144]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_144]
    at java.lang.ClassLoader.defineClass1(Native Method) ~[na:1.8.0_144]
    at java.lang.ClassLoader.defineClass(ClassLoader.java:763) ~[na:1.8.0_144]
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[na:1.8.0_144]
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:467) ~[na:1.8.0_144]
    at java.net.URLClassLoader.access$100(URLClassLoader.java:73) ~[na:1.8.0_144]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:368) ~[na:1.8.0_144]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:362) ~[na:1.8.0_144]
    at java.security.AccessController.doPrivileged(Native Method) ~[na:1.8.0_144]
    at java.net.URLClassLoader.findClass(URLClassLoader.java:361) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_144]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_144]
    at org.elasticsearch.client.RestHighLevelClient.<clinit>(RestHighLevelClient.java:1429) ~[elasticsearch-rest-high-level-client-6.4.0.jar:5.6.10]
    at com.softwareag.laasapi.rest.service.ElasticService.getClient(ElasticService.java:27) ~[classes/:na]
    at com.softwareag.laasapi.rest.service.ElasticService.getDocuments(ElasticService.java:57) ~[classes/:na]
    at com.softwareag.laasapi.rest.controller.LogsController.getDocuments(LogsController.java:52) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_144]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_144]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]

I have just followed the elasticsearch documentation for dependencies and set up correctly.

My Gradle dependency is

dependencies {
   compile 'org.elasticsearch.client:elasticsearch-rest-high-level-client:6.4.0'
}

For the sake of simplicity, given an short version of the code..

@RestController
public class ElasticController {

@RequestMapping("/posts")
public void getData() {

    RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", "9200","http")));

    GetRequest request = new GetRequest("posts", "doc", "1");
    GetResponse response = client.get(request, RequestOptions.DEFAULT);

    System.out.println(response.getSource().toString());

}
}

Could anyone help on this?

Body:
I struggled with this problem. Basically the root cause of this exception is version mismatch for Elastic-Search Lib, elasticsearch-rest-high-level-client and ElasticSearch Server .
I am using ElasticSearch Server 7.4 and Apache Flink 1.10. I have added following dependency in POM for Flink-Elastic-Search Sink:

 <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-connector-elasticsearch7_2.11</artifactId>
            <version>1.10.0</version>
        </dependency>
    <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.4.0</version>

        </dependency>

        <!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.4.0</version>
        </dependency>

This is working perfectly for me.

Note: Elastic-Search Server version and dependency version of elasticsearch-rest-high-level-client version, and Elastic-Search , SINK connector should be exactly same to avoid this issue.


问:
How do I use a pipe in the exec parameter for a find command?
I'm trying to construct a find command to process a bunch of files in a directory using two different executables.  Unfortunately, -exec on find doesn't allow to use pipe or even \| because the shell interprets that character first.

Here is specifically what I'm trying to do (which doesn't work because pipe ends the find command):

```<code>find /path/to/jpgs -type f -exec jhead -v {} | grep 123 \; -print
</code>```

答:
With -exec you can only run a single executable with some arguments, not arbitrary shell commands. To circumvent this, you can use sh -c '<shell command>'.

Do note that the use of -exec is quite inefficient. For each file that is found, the command has to be executed again. It would be more efficient if you can avoid this. (For example, by moving the grep outside the -exec or piping the results of find to xargs as suggested by Palmin.)

OwnerDisplayName: hoyhoy

Body:
I'm trying to construct a find command to process a bunch of files in a directory using two different executables.  Unfortunately, -exec on find doesn't allow to use pipe or even \| because the shell interprets that character first.

Here is specifically what I'm trying to do (which doesn't work because pipe ends the find command):

find /path/to/jpgs -type f -exec jhead -v {} | grep 123 \; -print

LastEditorDisplayName: Mo

OwnerDisplayName: mweerden

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: mweerden


问:
Settings Editor for #develop?
Using Visual C# Express, if I double-click on the Properties/Settings.settings file, I automagically got a special settings editor.  Doing the same under #develop just results in a standard editor, and it looks like Settings.Designer.cs doesn't get updated, so that has to be updated by hand as well.  Is there a plug-in for #develop that I'm missing?  </p>

答: SharpDevelop likely doesn't have a specific editor/designer implementation for ".settings" files. Looking at their wiki it looks like they are asking for help with a Settings Designer for #develop...</p>

OwnerDisplayName: Paul Morrison

Title: Settings Editor for #develop?

LastEditorDisplayName: Ian Robinson

OwnerDisplayName: Phil Price


问:
How to load Json array into separate table rows?
I'm having trouble with displaying my json data correctly. I want to get each products and place them into it's own row.

The problem now is that it places all the data of for example the value "name" into one table row instead of multiple rows.

This is my json data

```<code>{
 id: "FVFkkD7s8xNdDgh3zAyd",
 name: "AlperKaffe",
 products: [
 {
   id: "0cfBnXTijpJRu14DVfbI",
   name: "Første Kaffe",
   price: "1",
   size: "small",
   quantity: "20 ml"
},
{
   id: "JQadhkpn0AJd0NRnnWUF",
   name: "Anden Kaffe",
   price: "2",
   size: "Medium",
   quantity: "25 ml"
},
{
   id: "UwHHdH8bFxbVHkDryeGC",
   name: "kaffeeen",
   price: "300",
   size: "Small",
   quantity: "23 ml"
},
{
   id: "WiX5h0wFMNkCux9cINYq",
   name: "kaffe modal",
   price: "230",
   size: "Medium",
   quantity: "39 ml"
},
</code>```

this is my Js file which gets the json data. As you can see i'm only working with the "name" value for now

```<code>  // Jquery getting our json order data from API
  $.get("http://localhost:8888/products", (data) => {

    let rows = data.map(item => {

      let $clone = $('#frontpage_new_ordertable tfoot tr').clone();

      let productsName = item.products.map(prod => `${prod.name}`);
      $clone.find('.name').html(productsName);

      return $clone;
    });

    // appends to our frontpage html
    $("#frontpage_new_ordertable tbody").append(rows);

    });
</code>```

this is my html file

```<code><body>
   <table id="frontpage_new_ordertable">
    <tbody>
      <tr>
        <th>Name</th>
        <th>Price</th>
        <th>Size</th>
        <th>Quantity</th>
        <th></th>
      </tr>
    </tbody>
    <tfoot>
      <tr>
        <td class="name"></td>
        <td class="price"></td>
        <td class="size"></td>
        <td class="quantity"></td>
        <td class="buttons"></td>
      </tr>
    </tfoot>
  </table>

  <script src="./itemPage.js"></script>

</body>
</code>```

答:
you must replace
let rows = data.map(item => {
to
let rows = data.products.map(item => {

and

```<code>      let productsName = item.products.map(prod => `${prod.name}`);
</code>```

to

```<code>      let productsName = item.name;
</code>```

https://jsfiddle.net/ab7t1vmf/3/

Body:
I'm having trouble with displaying my json data correctly. I want to get each products and place them into it's own row.

The problem now is that it places all the data of for example the value "name" into one table row instead of multiple rows.

This is my json data

{
 id: "FVFkkD7s8xNdDgh3zAyd",
 name: "AlperKaffe",
 products: [
 {
   id: "0cfBnXTijpJRu14DVfbI",
   name: "Første Kaffe",
   price: "1",
   size: "small",
   quantity: "20 ml"
},
{
   id: "JQadhkpn0AJd0NRnnWUF",
   name: "Anden Kaffe",
   price: "2",
   size: "Medium",
   quantity: "25 ml"
},
{
   id: "UwHHdH8bFxbVHkDryeGC",
   name: "kaffeeen",
   price: "300",
   size: "Small",
   quantity: "23 ml"
},
{
   id: "WiX5h0wFMNkCux9cINYq",
   name: "kaffe modal",
   price: "230",
   size: "Medium",
   quantity: "39 ml"
},

this is my Js file which gets the json data. As you can see i'm only working with the "name" value for now

  // Jquery getting our json order data from API
  $.get("http://localhost:8888/products", (data) => {

    let rows = data.map(item => {

      let $clone = $('#frontpage_new_ordertable tfoot tr').clone();

      let productsName = item.products.map(prod => `${prod.name}`);
      $clone.find('.name').html(productsName);

      return $clone;
    });

    // appends to our frontpage html
    $("#frontpage_new_ordertable tbody").append(rows);

    });

this is my html file

        Name
        Price
        Size
        Quantity

Body:
you must replace
let rows = data.map(item => {
to
let rows = data.products.map(item => {

and

      let productsName = item.products.map(prod => `${prod.name}`);

to

      let productsName = item.name;

https://jsfiddle.net/ab7t1vmf/3/


问:
Django - list of objects not visible in DetailView
I have list of posts on my homepage, which are links to post DetailView.
Links works correctly, but when i go to DetailView, list is no more visible - i have to go back to home page to choose other post. Element which is showing posts list is located on base.html, correctly passes objects list to home.html, and in post_detail.html list is empty.

Homepage looks like this

Post DetailView looks like this - posts list is no more visible

Inspect view on homepage

Inepect view on DetailView - ul element is empty

base.html

```<code><body>
<div>
    <ul>
        <li>
            <a href="{% url 'blog-home' %}"> home</a>
        </li>

        <li>
            <a> items</a>
            <ul>
                {% for post in posts %}
                <li>
                    <a href="{% url 'post-detail' post.id %}"> {{ post.title }}</a>
                </li>
                {% endfor %}
            </ul>
        </li>
    </ul>

</div>
<di>
{% block content %}
{% endblock content %}
</div>
</body>
</code>```

home.html

```<code>{% extends "blog/base.html" %}

{% block content %}
{% for post in posts %}
    <div>
        <a href="#">{{post.title}}</a>
        <p>{{post.content}}</p>
        <p>{{post.date_posted}}</p>
    </div>
{% endfor %}
{% endblock content %}
</code>```

post_detail.html

```<code>{% extends "blog/base.html" %}

{% block content %}
    <div>
        <a href="#">{{object.title}}</a>
        <p>{{object.content}}</p>
    </div>
{% endblock content %}
</code>```

urls.py

```<code>from django.urls import path
from .views import PostListView, PostDetailView
from . import views

urlpatterns = [
    path('', PostListView.as_view(), name='blog-home'),
    path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
]
</code>```

views.py

```<code>from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Post

class PostListView(ListView):
    model = Post
    template_name = 'blog/home.html'
    context_object_name = 'posts'

class PostDetailView(DetailView):
    model = Post
</code>```

models.py

```<code>from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()

    def __str__(self):
        return self.title
</code>```

答:
You have to override the context of your DetailView which display only the data of current instance.</p>

```<code>class PostDetailView(DetailView):
    model = Post

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['other_posts'] = Post.objects.all()
        return context
</code>```

Body:
I have list of posts on my homepage, which are links to post DetailView.
Links works correctly, but when i go to DetailView, list is no more visible - i have to go back to home page to choose other post. Element which is showing posts list is located on base.html, correctly passes objects list to home.html, and in post_detail.html list is empty.

Homepage looks like this

Post DetailView looks like this - posts list is no more visible

Inspect view on homepage

Inepect view on DetailView - ul element is empty

base.html

             home

             items

                {% for post in posts %}

                     {{ post.title }}

                {% endfor %}

<di>
{% block content %}
{% endblock content %}

home.html

{% extends "blog/base.html" %}

{% block content %}
{% for post in posts %}

        {{post.title}}

{{post.content}}

{{post.date_posted}}

{% endfor %}
{% endblock content %}

post_detail.html

{% extends "blog/base.html" %}

{% block content %}

        {{object.title}}

{{object.content}}

{% endblock content %}

urls.py

from django.urls import path
from .views import PostListView, PostDetailView
from . import views

urlpatterns = [
    path('', PostListView.as_view(), name='blog-home'),
    path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
]

views.py

from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Post

class PostListView(ListView):
    model = Post
    template_name = 'blog/home.html'
    context_object_name = 'posts'

class PostDetailView(DetailView):
    model = Post

models.py

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()

    def __str__(self):
        return self.title

Body:
You have to override the context of your DetailView which display only the data of current instance.

class PostDetailView(DetailView):
    model = Post

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['other_posts'] = Post.objects.all()
        return context


问:
How can I have this Flutter Bloc to send updates?
I have this Flutter bloc that takes a Firebase stream of restaurants and depending on the position relative to the user will filter only the closest ones depending on the restaurant location. It works fine but I have to refresh with a RefreshIndicator if I want to see any changes in restaurant documents. What am I missing? Thanks in advance.</p>

```<code>class NearestRestaurant {
  final String id;
  final Restaurant restaurant;
  final double distance;

  NearestRestaurant({this.id, this.restaurant, this.distance});
}

class NearRestaurantBloc {
  final Future<List<Restaurant>> source;
  final Position userCoordinates;
  final _stream = StreamController<List<Restaurant>>();

  NearRestaurantBloc({
    this.source,
    this.userCoordinates,
  }) {
    List<Restaurant> resList = List<Restaurant>();
    source.then((rest) {
      rest.forEach((res) async {
        await Geolocator().distanceBetween(
          userCoordinates.latitude,
          userCoordinates.longitude,
          res.coordinates.latitude,
          res.coordinates.longitude,
        ).then((distance) {
          if (res.active && distance < res.deliveryRadius) {
            resList.add(res);
          }
        });
        _stream.add(resList);
      });
    });
  }

  Stream<List<Restaurant>> get stream => _stream.stream;

  void dispose() {
    _stream.close();
  }
}

class RestaurantQuery extends StatefulWidget {

  @override
  _RestaurantQueryState createState() => _RestaurantQueryState();
}

class _RestaurantQueryState extends State<RestaurantQuery> {
  NearRestaurantBloc bloc;

  @override
  Widget build(BuildContext context) {
    final database = Provider.of<Database>(context, listen: true);
    final session = Provider.of<Session>(context);
    final userCoordinates = session.position;
    bloc = NearRestaurantBloc(
        source: database.patronRestaurants(),
        userCoordinates: userCoordinates,
    );
    return StreamBuilder<List<Restaurant>>(
      stream: bloc.stream,
      builder: (context, snapshot) {
        bool stillLoading = true;
        var restaurantList = List<Restaurant>();
        if (snapshot.connectionState == ConnectionState.active) {
          if (snapshot.hasData && snapshot.data.length > 0) {
            restaurantList = snapshot.data;
          }
          stillLoading = false;
        }
        return Scaffold(
          appBar: AppBar(
            title: Text(
              'Restaurants near you',
              style: TextStyle(color: Theme.of(context).appBarTheme.color),
            ),
            elevation: 2.0,
          ),
          backgroundColor: Theme.of(context).scaffoldBackgroundColor,
          body: RefreshIndicator(
            onRefresh: () async {
              setState(() {

              });
            },
            child: RestaurantList(
              nearbyRestaurantsList: restaurantList,
              stillLoading: stillLoading,
            ),
          ),
        );
      },
    );
  }

  @override
  void dispose() {
    bloc.dispose();
    super.dispose();
  }

}
</code>```

答:
My mistake. I was listening to a future instead of a stream. Here's the updated bloc code:</p>

```<code>class NearestRestaurant {
  final String id;
  final Restaurant restaurant;
  final double distance;

  NearestRestaurant({this.id, this.restaurant, this.distance});
}

class NearRestaurantBloc {
  final Stream<List<Restaurant>> source;
  final Position userCoordinates;
  final _stream = StreamController<List<Restaurant>>();

  NearRestaurantBloc({
    this.source,
    this.userCoordinates,
  }) {
    List<Restaurant> resList = List<Restaurant>();
    source.forEach((rest) {
      resList.clear();
      rest.forEach((res) async {
        await Geolocator().distanceBetween(
          userCoordinates.latitude,
          userCoordinates.longitude,
          res.coordinates.latitude,
          res.coordinates.longitude,
        ).then((distance) {
          if (res.active && distance < res.deliveryRadius) {
            resList.add(res);
          }
        });
        _stream.add(resList);
      });
    });
  }

  Stream<List<Restaurant>> get stream => _stream.stream;

}
</code>```

Body:
I have this Flutter bloc that takes a Firebase stream of restaurants and depending on the position relative to the user will filter only the closest ones depending on the restaurant location. It works fine but I have to refresh with a RefreshIndicator if I want to see any changes in restaurant documents. What am I missing? Thanks in advance.

class NearestRestaurant {
  final String id;
  final Restaurant restaurant;
  final double distance;

  NearestRestaurant({this.id, this.restaurant, this.distance});
}

class NearRestaurantBloc {
  final Future<List<Restaurant>> source;
  final Position userCoordinates;
  final _stream = StreamController<List<Restaurant>>();

  NearRestaurantBloc({
    this.source,
    this.userCoordinates,
  }) {
    List<Restaurant> resList = List<Restaurant>();
    source.then((rest) {
      rest.forEach((res) async {
        await Geolocator().distanceBetween(
          userCoordinates.latitude,
          userCoordinates.longitude,
          res.coordinates.latitude,
          res.coordinates.longitude,
        ).then((distance) {
          if (res.active && distance < res.deliveryRadius) {
            resList.add(res);
          }
        });
        _stream.add(resList);
      });
    });
  }

  Stream<List<Restaurant>> get stream => _stream.stream;

  void dispose() {
    _stream.close();
  }
}

class RestaurantQuery extends StatefulWidget {

  @override
  _RestaurantQueryState createState() => _RestaurantQueryState();
}

class _RestaurantQueryState extends State<RestaurantQuery> {
  NearRestaurantBloc bloc;

  @override
  Widget build(BuildContext context) {
    final database = Provider.of<Database>(context, listen: true);
    final session = Provider.of<Session>(context);
    final userCoordinates = session.position;
    bloc = NearRestaurantBloc(
        source: database.patronRestaurants(),
        userCoordinates: userCoordinates,
    );
    return StreamBuilder<List<Restaurant>>(
      stream: bloc.stream,
      builder: (context, snapshot) {
        bool stillLoading = true;
        var restaurantList = List<Restaurant>();
        if (snapshot.connectionState == ConnectionState.active) {
          if (snapshot.hasData && snapshot.data.length > 0) {
            restaurantList = snapshot.data;
          }
          stillLoading = false;
        }
        return Scaffold(
          appBar: AppBar(
            title: Text(
              'Restaurants near you',
              style: TextStyle(color: Theme.of(context).appBarTheme.color),
            ),
            elevation: 2.0,
          ),
          backgroundColor: Theme.of(context).scaffoldBackgroundColor,
          body: RefreshIndicator(
            onRefresh: () async {
              setState(() {

              });
            },
            child: RestaurantList(
              nearbyRestaurantsList: restaurantList,
              stillLoading: stillLoading,
            ),
          ),
        );
      },
    );
  }

  @override
  void dispose() {
    bloc.dispose();
    super.dispose();
  }

}

Body:
My mistake. I was listening to a future instead of a stream. Here's the updated bloc code:

class NearestRestaurant {
  final String id;
  final Restaurant restaurant;
  final double distance;

  NearestRestaurant({this.id, this.restaurant, this.distance});
}

class NearRestaurantBloc {
  final Stream<List<Restaurant>> source;
  final Position userCoordinates;
  final _stream = StreamController<List<Restaurant>>();

  NearRestaurantBloc({
    this.source,
    this.userCoordinates,
  }) {
    List<Restaurant> resList = List<Restaurant>();
    source.forEach((rest) {
      resList.clear();
      rest.forEach((res) async {
        await Geolocator().distanceBetween(
          userCoordinates.latitude,
          userCoordinates.longitude,
          res.coordinates.latitude,
          res.coordinates.longitude,
        ).then((distance) {
          if (res.active && distance < res.deliveryRadius) {
            resList.add(res);
          }
        });
        _stream.add(resList);
      });
    });
  }

  Stream<List<Restaurant>> get stream => _stream.stream;

}


问:
How does Perl handle password prompts?
I'd like to pass a password through Perl. In my Perl script, it invokes SSH but gets stuck when the terminal is promoted for a password.

I've looked into using NET::SSH::Perl and other libraries but as of now they are not viable options. I just need to SSH into the machine, retrieve a file and leave.

答: Besides Net::SSH:Perl, there's Net::SSH2 and Net::OpenSSH. What have you tried, and what problems have you had with them?</p>

Title: How does Perl handle password prompts?


答:
The issue in your JS snippet seems to be let rows = data.map(item => { ...

From what you describe, the JSON data is comprised of 3 keys:

id

name

products

You cannot execute a map function directly on a Javascript Object, this function requires an array.

Looking a bit more at your code, I understand you need to display each product on its own row. Thus, you would need to use the map function on data.products which contains an array (of products).

let rows = data.products.map(item => {
    // ...
    $clone.find('.name').html(item.name);
    // ...
// ...
});
```

Reference: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/map

Title: How to load Json array into separate table rows?

Body:
The issue in your JS snippet seems to be let rows = data.map(item => { ...

From what you describe, the JSON data is comprised of 3 keys:

id

name

products

You cannot execute a map function directly on a Javascript Object, this function requires an array.

Looking a bit more at your code, I understand you need to display each product on its own row. Thus, you would need to use the map function on data.products which contains an array (of products).

let rows = data.products.map(item => {
    // ...
    $clone.find('.name').html(item.name);
    // ...
// ...
});

Reference: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/map