问:
Vaadin Grid with CallbackDataProvider always throws java.lang.IndexOutOfBoundsException:
I am trying to optimize the loading of a big table in my application into a com.vaadin.flow.component.grid.Grid. For that - instead of passing the entire, huge List<HistoryElement> using grid.setItems(allData) (which always caused lengthy freezing of the UI) - I am now using a CallbackDataProvider, that's returning the elements between offset and offset + limit as a Stream<HistoryElement>. The implementation is very similar to the example here: How to Vaadin CallbackDataProvider make an asyncronous fetch data?, i.e. I always create a Stream from a fraction (a sublist(...)) of the entire list.

In principle this seems to works except each time when I scroll towards the end of the list, i.e. when the offset + limit reaches the maximum of available elements. At that point I always get a huge exception stack trace like below (only the offending index varies).

But: there is not a single line of my own code in that trace! How can I avoid this IndexOutOfBoundsException? WHat might I be doing wrong here that later triggers that exception?   Or could it be that the index calculation inside the Grid-widget is faulty?
Any hints would be appreciated!

This is using Vaadin v22.0.2 and Java 11.

```<code>...
2022-01-03 13:34:16,324 ERROR [http-nio-8085-exec-5] com.vaadin.flow.server.DefaultErrorHandler:
java.lang.IndexOutOfBoundsException: Index 133 out of bounds for length 133
        at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
        at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
        at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
        at java.base/java.util.Objects.checkIndex(Objects.java:372)
        at java.base/java.util.ArrayList.get(ArrayList.java:459)
        at com.vaadin.flow.data.provider.DataCommunicator.lambda$getJsonItems$5(DataCommunicator.java:1326)
        at java.base/java.util.stream.IntPipeline$1$1.accept(IntPipeline.java:180)
        at java.base/java.util.stream.Streams$RangeIntSpliterator.forEachRemaining(Streams.java:104)
        at java.base/java.util.Spliterator$OfInt.forEachRemaining(Spliterator.java:699)
        at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
        at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
        at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
        at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
        at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
        at com.vaadin.flow.data.provider.DataCommunicator.getJsonItems(DataCommunicator.java:1328)
        at com.vaadin.flow.data.provider.DataCommunicator.lambda$collectChangesToSend$4(DataCommunicator.java:1281)
        at com.vaadin.flow.data.provider.DataCommunicator.applyIfNotEmpty(DataCommunicator.java:1341)
        at com.vaadin.flow.data.provider.DataCommunicator.withMissing(DataCommunicator.java:1336)
        at com.vaadin.flow.data.provider.DataCommunicator.collectChangesToSend(DataCommunicator.java:1280)
        at com.vaadin.flow.data.provider.DataCommunicator.flush(DataCommunicator.java:1152)
        at com.vaadin.flow.data.provider.DataCommunicator.lambda$requestFlush$7258256f$1(DataCommunicator.java:1069)
        at com.vaadin.flow.internal.StateTree.lambda$runExecutionsBeforeClientResponse$2(StateTree.java:392)
        at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
        at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
        at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1655)
        at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
        at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
        at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
        at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
        at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
        at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
        at com.vaadin.flow.internal.StateTree.runExecutionsBeforeClientResponse(StateTree.java:389)
        at com.vaadin.flow.server.communication.UidlWriter.encodeChanges(UidlWriter.java:391)
        at com.vaadin.flow.server.communication.UidlWriter.createUidl(UidlWriter.java:174)
        at com.vaadin.flow.server.communication.UidlRequestHandler.createUidl(UidlRequestHandler.java:158)
        at com.vaadin.flow.server.communication.UidlRequestHandler.writeUidl(UidlRequestHandler.java:146)
        at com.vaadin.flow.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:116)
        at com.vaadin.flow.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:40)
        at com.vaadin.flow.server.VaadinService.handleRequest(VaadinService.java:1567)
        at com.vaadin.flow.server.VaadinServlet.service(VaadinServlet.java:299)
        at com.vaadin.flow.spring.SpringServlet.service(SpringServlet.java:109)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:711)
        at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459)
        at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:353)
        at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:313)
        at org.springframework.web.servlet.mvc.ServletForwardingController.handleRequestInternal(ServletForwardingController.java:141)
        at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:177)
        at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:51)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327)
        at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115)
        at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
        at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:122)
        at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:116)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
        at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126)
        at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
        at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:109)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
        at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
        at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
        at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:219)
        at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:213)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
        at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103)
        at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
        at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90)
        at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
        at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:110)
        at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
        at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
        at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211)
        at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183)
        at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
        at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
        at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.base/java.lang.Thread.run(Thread.java:829)
</code>```

答: I found the reason! The CallbackDataProvider has to implement two methods, one providing a count of all available items and the other that allows the widget to request a chunk of data. In my case - due to a wrong argument passed to the underlying filtering done by the service that provides the count as well as the data - the count did not always match the number of items actually retrievable. That mismatch obviously caused the widget to throw these IndexOutOfBounds exceptions. My bad...</p>

Body:
I am trying to optimize the loading of a big table in my application into a com.vaadin.flow.component.grid.Grid. For that - instead of passing the entire, huge List<HistoryElement> using grid.setItems(allData) (which always caused lengthy freezing of the UI) - I am now using a CallbackDataProvider, that's returning the elements between offset and offset + limit as a Stream<HistoryElement>. The implementation is very similar to the example here: How to Vaadin CallbackDataProvider make an asyncronous fetch data?, i.e. I always create a Stream from a fraction (a sublist(...)) of the entire list.

In principle this seems to works except each time when I scroll towards the end of the list, i.e. when the offset + limit reaches the maximum of available elements. At that point I always get a huge exception stack trace like below (only the offending index varies).

But: there is not a single line of my own code in that trace! How can I avoid this IndexOutOfBoundsException? WHat might I be doing wrong here that later triggers that exception?   Or could it be that the index calculation inside the Grid-widget is faulty?
Any hints would be appreciated!

This is using Vaadin v22.0.2 and Java 11.

...
2022-01-03 13:34:16,324 ERROR [http-nio-8085-exec-5] com.vaadin.flow.server.DefaultErrorHandler:
java.lang.IndexOutOfBoundsException: Index 133 out of bounds for length 133
        at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
        at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
        at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
        at java.base/java.util.Objects.checkIndex(Objects.java:372)
        at java.base/java.util.ArrayList.get(ArrayList.java:459)
        at com.vaadin.flow.data.provider.DataCommunicator.lambda$getJsonItems$5(DataCommunicator.java:1326)
        at java.base/java.util.stream.IntPipeline$1$1.accept(IntPipeline.java:180)
        at java.base/java.util.stream.Streams$RangeIntSpliterator.forEachRemaining(Streams.java:104)
        at java.base/java.util.Spliterator$OfInt.forEachRemaining(Spliterator.java:699)
        at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
        at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
        at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
        at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
        at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
        at com.vaadin.flow.data.provider.DataCommunicator.getJsonItems(DataCommunicator.java:1328)
        at com.vaadin.flow.data.provider.DataCommunicator.lambda$collectChangesToSend$4(DataCommunicator.java:1281)
        at com.vaadin.flow.data.provider.DataCommunicator.applyIfNotEmpty(DataCommunicator.java:1341)
        at com.vaadin.flow.data.provider.DataCommunicator.withMissing(DataCommunicator.java:1336)
        at com.vaadin.flow.data.provider.DataCommunicator.collectChangesToSend(DataCommunicator.java:1280)
        at com.vaadin.flow.data.provider.DataCommunicator.flush(DataCommunicator.java:1152)
        at com.vaadin.flow.data.provider.DataCommunicator.lambda$requestFlush$7258256f$1(DataCommunicator.java:1069)
        at com.vaadin.flow.internal.StateTree.lambda$runExecutionsBeforeClientResponse$2(StateTree.java:392)
        at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
        at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
        at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1655)
        at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
        at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
        at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
        at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
        at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
        at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
        at com.vaadin.flow.internal.StateTree.runExecutionsBeforeClientResponse(StateTree.java:389)
        at com.vaadin.flow.server.communication.UidlWriter.encodeChanges(UidlWriter.java:391)
        at com.vaadin.flow.server.communication.UidlWriter.createUidl(UidlWriter.java:174)
        at com.vaadin.flow.server.communication.UidlRequestHandler.createUidl(UidlRequestHandler.java:158)
        at com.vaadin.flow.server.communication.UidlRequestHandler.writeUidl(UidlRequestHandler.java:146)
        at com.vaadin.flow.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:116)
        at com.vaadin.flow.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:40)
        at com.vaadin.flow.server.VaadinService.handleRequest(VaadinService.java:1567)
        at com.vaadin.flow.server.VaadinServlet.service(VaadinServlet.java:299)
        at com.vaadin.flow.spring.SpringServlet.service(SpringServlet.java:109)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:711)
        at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459)
        at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:353)
        at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:313)
        at org.springframework.web.servlet.mvc.ServletForwardingController.handleRequestInternal(ServletForwardingController.java:141)
        at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:177)
        at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:51)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327)
        at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115)
        at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
        at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:122)
        at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:116)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
        at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126)
        at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
        at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:109)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
        at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
        at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
        at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:219)
        at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:213)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
        at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103)
        at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
        at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90)
        at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
        at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:110)
        at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
        at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
        at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211)
        at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183)
        at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
        at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
        at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.base/java.lang.Thread.run(Thread.java:829)


来源: stackexchange

问:
How Can I Do Peach Math Number Switcher Program Like This?
Here's The Program I Want To Do.
Program

[x,y,z]

X = The Largest Number Of Position X, By Start From Number Zero

Y = The Largest Number Of Position Y, By Start From Number Zero

Z = The Largest Number Of Position Z, By Start From Number Zero

C = The Sum Number Of Position (x, y, z), It Must Not Equal To C.

答:
You could use the range() function in nested loops to get your number combinations and pick the ones that meet your criteria:

```<code>X = 1
Y = 1
Z = 2
C = 3

result = []
for x in range(X+1):
    for y in range(Y+1):
        for z in range(Z+1):
            if x+y+z != C:
                result.append([x,y,z])

print(result)
[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [1, 0, 0],
 [1, 0, 1], [1, 1, 0], [1, 1, 2]]
</code>```

The number combinations could also be obtained using the product function from itertools.  This would allow you to get the result in a list comprehension:

```<code>X = 1
Y = 1
Z = 2
C = 3

from itertools import product

result = [ p for p in product(*map(range,(X+1,Y+1,Z+1))) if sum(p) != C]

print(result)
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (1, 0, 0),
 (1, 0, 1), (1, 1, 0), (1, 1, 2)]
</code>```

An additional way to do this is to unrank the combinations in a single loop:

```<code>X = 1
Y = 1
Z = 2
C = 3

result = []
for n in range((X+1)*(Y+1)*(Z+1)):
    n,z = divmod(n,Z+1)
    x,y = divmod(n,Y+1)
    if x+y+z != C:
        result.append([x,y,z])

print(result)
[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [1, 0, 0],
 [1, 0, 1], [1, 1, 0], [1, 1, 2]]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You could use the range() function in nested loops to get your number combinations and pick the ones that meet your criteria:

X = 1
Y = 1
Z = 2
C = 3

result = []
for x in range(X+1):
    for y in range(Y+1):
        for z in range(Z+1):
            if x+y+z != C:
                result.append([x,y,z])

print(result)
[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [1, 0, 0],
 [1, 0, 1], [1, 1, 0], [1, 1, 2]]

The number combinations could also be obtained using the product function from itertools.  This would allow you to get the result in a list comprehension:

X = 1
Y = 1
Z = 2
C = 3

from itertools import product

result = [ p for p in product(*map(range,(X+1,Y+1,Z+1))) if sum(p) != C]

print(result)
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (1, 0, 0),
 (1, 0, 1), (1, 1, 0), (1, 1, 2)]

An additional way to do this is to unrank the combinations in a single loop:

X = 1
Y = 1
Z = 2
C = 3

result = []
for n in range((X+1)*(Y+1)*(Z+1)):
    n,z = divmod(n,Z+1)
    x,y = divmod(n,Y+1)
    if x+y+z != C:
        result.append([x,y,z])

print(result)
[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [1, 0, 0],
 [1, 0, 1], [1, 1, 0], [1, 1, 2]]


问:
Intervention image multiple image upload in laravel
in blade

```<code><input type="file" name="image[]" id="" required class="form-control" multiple accept="image/*">
</code>```

in controller

```<code>public function addReviewPost(Request $request)
{
    $image = $request->file('image');

    $this->validate($request, [
        'image' => 'required',
        'image.*' => ' max:2048 | dimensions:max_width=2200',
    ]);

    if (request()->hasFile('image')) {
        $counter = count($image);

        for ($i = 0; $i < $counter; $i++) {

            $image = Image::make($image[$i]);
            $image->resize(null, 627, function ($constraint) {
                $constraint->aspectRatio();
            });
            $image->save(public_path('../../img/testimonial/' . time() . '.png'));
        }
    }

}
</code>```

it shows error

```<code>Symfony\Component\Debug\Exception\FatalThrowableError
Cannot use object of type Intervention\Image\Image as array
</code>```

can anyone please help me how can I upload multi file using intervention image package?

答:
html

```<code><input type="file" name="images[]" multiple accept="image/*">
</code>```

Controller

```<code>foreach ($request->images as $key=>$image) {
                $iimage = Image::make($image)
                                ->resize(350, 150)
                                ->encode('jpg');

            Storage::disk('local')->put('public/gallery_images/' . $image->hashName(), (string)$iimage, 'public');
            $request_data['image']    = 'gallery_images/'. $image->hashName();
            $request_data['owner_id'] = auth()->guard('owner')->user()->id;

            Gallery::create($request_data);

        }//end of foreach
</code>```

Body:
in blade

<input type="file" name="image[]" id="" required class="form-control" multiple accept="image/*">

in controller

public function addReviewPost(Request $request)
{
    $image = $request->file('image');

    $this->validate($request, [
        'image' => 'required',
        'image.*' => ' max:2048 | dimensions:max_width=2200',
    ]);

    if (request()->hasFile('image')) {
        $counter = count($image);

        for ($i = 0; $i < $counter; $i++) {

            $image = Image::make($image[$i]);
            $image->resize(null, 627, function ($constraint) {
                $constraint->aspectRatio();
            });
            $image->save(public_path('../../img/testimonial/' . time() . '.png'));
        }
    }

}

it shows error

Symfony\Component\Debug\Exception\FatalThrowableError
Cannot use object of type Intervention\Image\Image as array

can anyone please help me how can I upload multi file using intervention image package?

Body:
html

<input type="file" name="images[]" multiple accept="image/*">

Controller

foreach ($request->images as $key=>$image) {
                $iimage = Image::make($image)
                                ->resize(350, 150)
                                ->encode('jpg');

            Storage::disk('local')->put('public/gallery_images/' . $image->hashName(), (string)$iimage, 'public');
            $request_data['image']    = 'gallery_images/'. $image->hashName();
            $request_data['owner_id'] = auth()->guard('owner')->user()->id;

            Gallery::create($request_data);

        }//end of foreach


问:
How does one implement an Iterator for a an Object that has generic types?
So I have an object called DetailedResponse<T>. Now I want to use this for an API where I can pass some data into it. Let's say this is the implementation for DetailedResponse

#[derive(serde::Deserialize, serde::Serialize)]
pub struct DetailedResponse<T> {
    pub data: Option<T>,
    pub success: bool,
    pub message: String,
}

impl<T> DetailedResponse<T> {
    pub fn new() -> DetailedResponse<T> {
        DetailedResponse {
            data: None,
            success: false,
            message: "".to_string(),
        }
    }
}
```
<p>And now in the API I want to use actix::Json to map some data lests say: <code>DetailedResponse<Vec<i16>></code> and I want to implement the response in code like this:</p>
<pre class="lang-rust prettyprint-override"><code>let response = DetailedResponse<Vec<i16>>::new();
// Do something
response.map(Json)
</code>```

I know I need to implement an Iterator trait for detailed response but I haven't seen good examples for what I want to accomplish. What I am imagining is that I will need to do something like this:

pub struct DetailedResponseIter<T> {
    // stuck here
}

impl<'a, T> DetailedResponseIter<T> {
    type Item = DetailedResponse<T>

    // Also Stuck here.
}
```

Thank you for your help and I will edit any more needed information.

答:
So taking a hint from jmb, I did some more digging and the answer is pretty simple. And the error I was getting was not as clear as I was thinking. Here is the Actual Code block I am working with:

#[actix_web::get("/party")]
async fn parties(db: Data<PartyRepo>)
    -> Result<
        Json<DetailedResponse<Vec<PartyEntity>>>,
        InternalError<StdErr>
    >
{
    let mut response: DetailedResponse<Vec<PartyEntity>> = DetailedResponse::new();

    let data = db.all().await;
    match data {
        Ok(value) => {
            response.data = Some(value);
            response.success = true;
            response.message = format!("APi Request Successful on {}/{}",
                std::env::var("SERVER_URL").unwrap(),
                std::env::var("PARTY_CONTROLLER_PORT").unwrap()
            );
        }
        Err(e) => {
            response.success = false;
            response.message = e.to_string();
        }
    }
    Ok(Json(response))
}
```

You can really just map the data within the Json and aslong as DetailedResponse has #[derive(serde::Deserialize)] Tag it should do the work. As always RFM. Also thank you to Solomon Ucko for helping me stumble on to this lol.

Body:
So I have an object called DetailedResponse<T>. Now I want to use this for an API where I can pass some data into it. Let's say this is the implementation for DetailedResponse

#[derive(serde::Deserialize, serde::Serialize)]
pub struct DetailedResponse<T> {
    pub data: Option<T>,
    pub success: bool,
    pub message: String,
}

impl<T> DetailedResponse<T> {
    pub fn new() -> DetailedResponse<T> {
        DetailedResponse {
            data: None,
            success: false,
            message: "".to_string(),
        }
    }
}

And now in the API I want to use actix::Json to map some data lests say: DetailedResponse<Vec<i16>> and I want to implement the response in code like this:

let response = DetailedResponse<Vec<i16>>::new();
// Do something
response.map(Json)

I know I need to implement an Iterator trait for detailed response but I haven't seen good examples for what I want to accomplish. What I am imagining is that I will need to do something like this:

pub struct DetailedResponseIter<T> {
    // stuck here
}

impl<'a, T> DetailedResponseIter<T> {
    type Item = DetailedResponse<T>

    // Also Stuck here.
}

Thank you for your help and I will edit any more needed information.

Body:
So taking a hint from jmb, I did some more digging and the answer is pretty simple. And the error I was getting was not as clear as I was thinking. Here is the Actual Code block I am working with:

#[actix_web::get("/party")]
async fn parties(db: Data<PartyRepo>)
    -> Result<
        Json<DetailedResponse<Vec<PartyEntity>>>,
        InternalError<StdErr>
    >
{
    let mut response: DetailedResponse<Vec<PartyEntity>> = DetailedResponse::new();

    let data = db.all().await;
    match data {
        Ok(value) => {
            response.data = Some(value);
            response.success = true;
            response.message = format!("APi Request Successful on {}/{}",
                std::env::var("SERVER_URL").unwrap(),
                std::env::var("PARTY_CONTROLLER_PORT").unwrap()
            );
        }
        Err(e) => {
            response.success = false;
            response.message = e.to_string();
        }
    }
    Ok(Json(response))
}

You can really just map the data within the Json and aslong as DetailedResponse has #[derive(serde::Deserialize)] Tag it should do the work. As always RFM. Also thank you to Solomon Ucko for helping me stumble on to this lol.


问:
How can I get the SNS topic ARN using the topic name to publish a SNS message in Python via Boto3?
Python

method to run query

```<code>def function(run_query)
   //topic = arn return from topic name
   topic.publish(message)
   pass
</code>```

I am using the boto3 resource method. There are lot of examples of using boto3.client and limited example of sns method implementation using boto3 resource methods.

答:
There seems to be no easy, expected get_topic_arn(topic_name) method to get an AWS topic ARN using the topic name, via the Boto3 SNS client or resource.

However, a clever workaround would be to use the create_topic method:

This action is idempotent, so if the requester already owns a topic with the specified name, that topic's ARN is returned without creating a new topic.

Call create_topic with an existing topic name, which will retrieve the SNS.Topic sub-resource, and then call the publish method on the topic sub-resource.

import boto3

sns = boto3.resource('sns')

topic = sns.create_topic(Name='MyTopicName')
topic_arn = topic.arn

response = topic.publish(Message='MyMessage')
...
```

Body:
Python

method to run query

def function(run_query)
   //topic = arn return from topic name
   topic.publish(message)
   pass

I am using the boto3 resource method. There are lot of examples of using boto3.client and limited example of sns method implementation using boto3 resource methods.


问:
This expression has a type of 'void' so its value can't be used flutter dart
 i hope this image help

as well this one

when i try to use provider to call async function from another file I get the error.
i dont know that it's a problem in the methode where i call it or in the file that i created the function. at the end i will say thank you because stack overflow says  add more details.

the code from pictures

```<code>void _saveForm() async {
var isValid = _form.currentState?.validate() as bool;
if (!isValid) {
  return;
}
_form.currentState?.save();
print(_editedProduct);
if (_editedProduct.id == '') {
  print('done');
  // ignore: await_only_futures
  await Provider.of<Products>(context, listen: false)
      .addProduct(_editedProduct); // this is where i get the error.
} else {
  Provider.of<Products>(context, listen: false)
      .updateProduct(_editedProduct.id, _editedProduct);
}
Navigator.of(context).pop();
</code>```

}

```<code>Future<void> addProduct(Product product) async {
var httpsUri = Uri(
  scheme: 'scheme',
  host: 'host',
  path: 'path',
);
final uri = Uri.parse(
    'host');

try {
  var res = await http.post(uri,
      body: json.encode({
        'title': product.title,
        'description': product.description,
        'price': product.price,
        'isFav': product.isFavorite,
        'imageUrl': product.imageUrl
      }));

  final newProduct = Product(
    title: product.title,
    description: product.description,
    price: product.price,
    imageUrl: product.imageUrl,
    id: DateTime.now().toString(),
  );
  _items.add(newProduct);
  notifyListeners();
} catch (e) {
  print(e);
}

// _items.insert(0, newProduct); // at the start of the list
</code>```

}

答: Future<void> addProduct(Product product) async {...} means the function doesn't return anything but Provider needs a value so it throws an error.

Body:
 i hope this image help

as well this one

when i try to use provider to call async function from another file I get the error.
i dont know that it's a problem in the methode where i call it or in the file that i created the function. at the end i will say thank you because stack overflow says  add more details.

the code from pictures

void _saveForm() async {
var isValid = _form.currentState?.validate() as bool;
if (!isValid) {
  return;
}
_form.currentState?.save();
print(_editedProduct);
if (_editedProduct.id == '') {
  print('done');
  // ignore: await_only_futures
  await Provider.of<Products>(context, listen: false)
      .addProduct(_editedProduct); // this is where i get the error.
} else {
  Provider.of<Products>(context, listen: false)
      .updateProduct(_editedProduct.id, _editedProduct);
}
Navigator.of(context).pop();

}

Future<void> addProduct(Product product) async {
var httpsUri = Uri(
  scheme: 'scheme',
  host: 'host',
  path: 'path',
);
final uri = Uri.parse(
    'host');

try {
  var res = await http.post(uri,
      body: json.encode({
        'title': product.title,
        'description': product.description,
        'price': product.price,
        'isFav': product.isFavorite,
        'imageUrl': product.imageUrl
      }));

  final newProduct = Product(
    title: product.title,
    description: product.description,
    price: product.price,
    imageUrl: product.imageUrl,
    id: DateTime.now().toString(),
  );
  _items.add(newProduct);
  notifyListeners();
} catch (e) {
  print(e);
}

// _items.insert(0, newProduct); // at the start of the list

}


问:
How to conditionally set a Style variable in JSX (React)?
I am trying to conditonally set the border color of an image. Depending on the image name, I would like to set a different border color.

Here is my code:

```<code><div className="row">
    {asideData.imageGallery2.map( (img, i) => {
        return(
              <div className="col-md-6 col-lg-4">
                   // if img.name includes "Quartz" then make border color red
                   // if img.name includes "Flake" then make border color blue
                  <img src={img.img} alt="" key={img.name} style={{border:"5px solid #555"}}/>
               </div>)
               })}

</div>
</code>```

答:
try

style={{border:"5px solid", borderColor: img.name.includes('Quartz') ? 'red' : (img.name.includes('Flake') ? 'blue' : null)}}/>
```

Check if that works

Body:
I am trying to conditonally set the border color of an image. Depending on the image name, I would like to set a different border color.

Here is my code:

    {asideData.imageGallery2.map( (img, i) => {
        return(

                   // if img.name includes "Quartz" then make border color red
                   // if img.name includes "Flake" then make border color blue

)
               })}

Body:
try

style={{border:"5px solid", borderColor: img.name.includes('Quartz') ? 'red' : (img.name.includes('Flake') ? 'blue' : null)}}/>

Check if that works


问:
How to reveal line level profiling in JS sources?
I've read this article about analyzing runtime performance. The image below is copied from this article. If you check this image, there are yellow highlighted execution time hints for JS files next to each line in the file.

I find this line level profiling feature pretty useful and I would like to try it in my own projects, too.

However, when I open a JS source file in the sources tab, I cannot see it. Note that, I already took a performance profiling snapshot. But still I cannot see this execution time hints.

How can I reveal this feature?

Thanks.

答:
I wasn't seeing the line by line timings from the profiler either, and it was driving me crazy for days.

My code was written in typescript and converted to JScript with source maps using esbuild.

When I turned source maps off in esbuild, the line timings reappeared from the profiler!

The Jscript is close enough to the Typescript so the line timings are still useful.

I could have sworn I'd seen it work with source maps in the past but now I'm not so sure. It would be great if the line timings did work with source maps but it kind of makes sense that they don't.

Has anyone else seen profiler line timings work on code with sourcemaps turn on?


问:
psycopg2 TypeError: not all arguments converted during string formatting
I'm trying execute a simple query, but getting this error no matter how I pass the parameters.

Here is the query (I'm using Trac db object to connect to a DB):

```<code>cursor.execute("""SELECT name FROM "%s".customer WHERE firm_id='%s'""" % (schema, each['id']))
</code>```

schema and each['id'] both are simple strings

```<code>print("""SELECT name FROM "%s".customer WHERE firm_id='%s'""" % (schema, each['id']))
</code>```

Result:
SELECT name FROM "Planing".customer WHERE firm_id='135'

There is on error is a remove quote after firm_id=, but that way parameter is treated a an integer and ::text leads to the very same error.

答: Every time I have this kind of error, I am passing the wrong amount of values. Try check it</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying execute a simple query, but getting this error no matter how I pass the parameters.

Here is the query (I'm using Trac db object to connect to a DB):

cursor.execute("""SELECT name FROM "%s".customer WHERE firm_id='%s'""" % (schema, each['id']))

schema and each['id'] both are simple strings

print("""SELECT name FROM "%s".customer WHERE firm_id='%s'""" % (schema, each['id']))

Result:
SELECT name FROM "Planing".customer WHERE firm_id='135'

There is on error is a remove quote after firm_id=, but that way parameter is treated a an integer and ::text leads to the very same error.


问:
Write list of numbers to CSV file in Python
I have a list of 4-digit numbers (1234, 1234, 1234) in Python that I would like to write to a CSV file.

I am using the csv library, this is the code I have:

```<code>with open('converted2.csv','w') as new_file:
 write=csv.writer(new_file)
 write.writerows(results)
</code>```

However, when I import the values into a file,
they are spread across rows

How could I prevent this from happening and have the four-digit numbers all under one column only?

Thank you!

答:
use the lambda method provided inside writerows to print rows</p>
```<code>import csv

results = [1234, 1234, 1234]
with open('converted2.csv','w') as new_file:
 write=csv.writer(new_file)
 write.writerows(map(lambda x: [x], results))

$ cat converted2.csv
1234
1234
1234
</code>```

Body:
I have a list of 4-digit numbers (1234, 1234, 1234) in Python that I would like to write to a CSV file.

I am using the csv library, this is the code I have:

with open('converted2.csv','w') as new_file:
 write=csv.writer(new_file)
 write.writerows(results)

However, when I import the values into a file,
they are spread across rows

How could I prevent this from happening and have the four-digit numbers all under one column only?

Thank you!

Body:
use the lambda method provided inside writerows to print rows

import csv

results = [1234, 1234, 1234]
with open('converted2.csv','w') as new_file:
 write=csv.writer(new_file)
 write.writerows(map(lambda x: [x], results))

$ cat converted2.csv
1234
1234
1234


问:
OCaml function definition
Can somebody tell me the difference between these two definitions ?

```<code>let f x y = x + y;;
</code>```

which yields val f : int -> int -> int = <fun>

and  this definition

```<code>let f = fun x y -> x + y;;
</code>```

which also yields val f : int -> int -> int = <fun> ?

答:
There is no difference.

```<code>let f x y = x + y
</code>```

is syntactic sugar for

```<code>let f = fun x y -> x + y
</code>```

which is syntactic sugar for

```<code>let f = function x -> function y -> x + y
</code>```

It's all the same and you can do for example

```<code>let incr = f 1
</code>```

with any of them.

Title: OCaml function definition

Body:
Can somebody tell me the difference between these two definitions ?

let f x y = x + y;;

which yields val f : int -> int -> int = <fun>

and  this definition

let f = fun x y -> x + y;;

which also yields val f : int -> int -> int = <fun> ?

Body:
There is no difference.

let f x y = x + y

is syntactic sugar for

let f = fun x y -> x + y

which is syntactic sugar for

let f = function x -> function y -> x + y

It's all the same and you can do for example

let incr = f 1

with any of them.


问:
How to create boundary in React?
I have a form and a list. I want to put them inside a parent component (a boundary) and I want to change their form and behavior based on the detection of the presence of the boundary.

Here's my idea:

```<code>const ParentChildrenPage = () => {
    return <ParentChildren>
         <ParentForm />
         <ChildrenList />
    </ParentChildren>
}
</code>```

Here are some notes:

ParentForm when rendred by itself, has a Cancel button that returns the user to the previous page. But when it's rendered inside the ParentChildren it should not show that Cancel button, and on Save it should not navigate user to the previous page, but should stay in that page.

ChildrenList has a Add button on top of it. When shown by itself it navigates user to a child creation form. But when it detects that it's rendered inside ParentChildren its Add button should show a dialog form.

Basically, I'm trying to create the notion of boundary and let children components detect that they are rendered inside that boundary and adjust their structure and behavior accordingly.

How can I do this?

答:
Let's consider a Boundary.js component

```<code>import React from 'react'

const BoundaryComponent = ({children}) => {
  const childrenWithBoundary = React.Children.map(children, child => {
    if (React.isValidElement(child)) {
      return React.cloneElement(child, { hasBoundary: true });
    }
    return child;
  });

  return childrenWithBoundary
}

export default BoundaryComponent
</code>```

What we do, we iterate through all the children, clone the element and also append a new prop to them.

So, let's create three components, two of them having the possibility to render based on the boundary, and one independent.

```<code>export const Component1 = ({hasBoundary=false}) => {
  if (hasBoundary) {
    return <div>Component 1 With Boundary</div>
  }
  return <div>Component 1</div>
}

export const Component2 = ({hasBoundary=false}) => {
  if (hasBoundary) {
    return <div>Component 2 With Boundary</div>
  }
  return <div>Component 2</div>
}

export const Component3 = () => {
  return <div>Component 3</div>
}
</code>```

Such that in our App.js, we will have:

```<code>import BoundaryComponent from './Boundary'
import {Component1, Component2, Component3} from './Components'

export default function App() {
  return (
    <div>
      <Component1/>
      <Component2/>
      <Component3/>

      <BoundaryComponent>
        <Component1/>
        <Component2/>
        <Component3/>
      </BoundaryComponent>
    </div>
  );
}
</code>```

The output:

Note:
In this scenario, the BoundaryComponent should have the affected components as direct children.

Title: How to create boundary in React?

Body:
I have a form and a list. I want to put them inside a parent component (a boundary) and I want to change their form and behavior based on the detection of the presence of the boundary.

Here's my idea:

const ParentChildrenPage = () => {
    return <ParentChildren>
         <ParentForm />
         <ChildrenList />
    </ParentChildren>
}

Here are some notes:

ParentForm when rendred by itself, has a Cancel button that returns the user to the previous page. But when it's rendered inside the ParentChildren it should not show that Cancel button, and on Save it should not navigate user to the previous page, but should stay in that page.

ChildrenList has a Add button on top of it. When shown by itself it navigates user to a child creation form. But when it detects that it's rendered inside ParentChildren its Add button should show a dialog form.

Basically, I'm trying to create the notion of boundary and let children components detect that they are rendered inside that boundary and adjust their structure and behavior accordingly.

How can I do this?

Body:
Let's consider a Boundary.js component

import React from 'react'

const BoundaryComponent = ({children}) => {
  const childrenWithBoundary = React.Children.map(children, child => {
    if (React.isValidElement(child)) {
      return React.cloneElement(child, { hasBoundary: true });
    }
    return child;
  });

  return childrenWithBoundary
}

export default BoundaryComponent

What we do, we iterate through all the children, clone the element and also append a new prop to them.

So, let's create three components, two of them having the possibility to render based on the boundary, and one independent.

export const Component1 = ({hasBoundary=false}) => {
  if (hasBoundary) {
    return <div>Component 1 With Boundary</div>
  }
  return <div>Component 1</div>
}

export const Component2 = ({hasBoundary=false}) => {
  if (hasBoundary) {
    return <div>Component 2 With Boundary</div>
  }
  return <div>Component 2</div>
}

export const Component3 = () => {
  return <div>Component 3</div>
}

Such that in our App.js, we will have:

import BoundaryComponent from './Boundary'
import {Component1, Component2, Component3} from './Components'

export default function App() {
  return (
    <div>
      <Component1/>
      <Component2/>
      <Component3/>

      <BoundaryComponent>
        <Component1/>
        <Component2/>
        <Component3/>
      </BoundaryComponent>
    </div>
  );
}

The output:

Note:
In this scenario, the BoundaryComponent should have the affected components as direct children.


问:
Pass Parcelable argument with compose navigation
I want to pass a parcelable object (BluetoothDevice) to a composable using compose navigation.

Passing primitive types is easy:

composable(
  "profile/{userId}",
  arguments = listOf(navArgument("userId") { type = NavType.StringType })
) {...}
```
<pre class="lang-kotlin prettyprint-override"><code>navController.navigate("profile/user1234")
</code>```

But I can't pass a parcelable object in the route unless I can serialize it to a string.

composable(
  "deviceDetails/{device}",
  arguments = listOf(navArgument("device") { type = NavType.ParcelableType(BluetoothDevice::class.java) })
) {...}
```
<pre class="lang-kotlin prettyprint-override"><code>val device: BluetoothDevice = ...
navController.navigate("deviceDetails/$device")
</code>```

The code above obviously doesn't work because it just implicitly calls toString().

Is there a way to either serialize a Parcelable to a String so I can pass it in the route or pass the navigation argument as an object with a function other than navigate(route: String)?

答:
A very simple and basic way to do is as below

1.First create the parcelable object that you want to pass e.g

```<code>@Parcelize
data class User(
    val name: String,
    val phoneNumber:String
) : Parcelable
</code>```

2.Then in the current composable that you are in e.g main screen

```<code> val userDetails = UserDetails(
                            name = "emma",
                             phoneNumber = "1234"
                            )
                        )
navController.currentBackStackEntry?.arguments?.apply {
                            putParcelable("userDetails",userDetails)
                        }
                        navController.navigate(Destination.DetailsScreen.route)
</code>```

3.Then in the details composable, make sure you pass to it a navcontroller as an parameter e.g.

```<code>@Composable
fun Details (navController:NavController){
val data = remember {
        mutableStateOf(navController.previousBackStackEntry?.arguments?.getParcelable<UserDetails>("userDetails")!!)
    }
}
</code>```

N.B:  If the parcelable is not passed into state, you will receive an error when navigating back

Body:
I want to pass a parcelable object (BluetoothDevice) to a composable using compose navigation.

Passing primitive types is easy:

composable(
  "profile/{userId}",
  arguments = listOf(navArgument("userId") { type = NavType.StringType })
) {...}

navController.navigate("profile/user1234")

But I can't pass a parcelable object in the route unless I can serialize it to a string.

composable(
  "deviceDetails/{device}",
  arguments = listOf(navArgument("device") { type = NavType.ParcelableType(BluetoothDevice::class.java) })
) {...}

val device: BluetoothDevice = ...
navController.navigate("deviceDetails/$device")

The code above obviously doesn't work because it just implicitly calls toString().

Is there a way to either serialize a Parcelable to a String so I can pass it in the route or pass the navigation argument as an object with a function other than navigate(route: String)?

Body:
A very simple and basic way to do is as below

1.First create the parcelable object that you want to pass e.g

@Parcelize
data class User(
    val name: String,
    val phoneNumber:String
) : Parcelable

2.Then in the current composable that you are in e.g main screen

 val userDetails = UserDetails(
                            name = "emma",
                             phoneNumber = "1234"
                            )
                        )
navController.currentBackStackEntry?.arguments?.apply {
                            putParcelable("userDetails",userDetails)
                        }
                        navController.navigate(Destination.DetailsScreen.route)

3.Then in the details composable, make sure you pass to it a navcontroller as an parameter e.g.

@Composable
fun Details (navController:NavController){
val data = remember {
        mutableStateOf(navController.previousBackStackEntry?.arguments?.getParcelable<UserDetails>("userDetails")!!)
    }
}

N.B:  If the parcelable is not passed into state, you will receive an error when navigating back


问:
Flutter: How to fetch a particular record from firebase
This is the screenshot of my database.

I want to fetch the record for a particular username. (For eg: where user=nam@gmail.com) Can anyone suggest to me how to fetch this in flutter?

It would be a great help, Thank you.

答:
For android solution follow this:</p>
```<code> FirebaseFirestore.getInstance()
                .collection("users").whereArrayContains("user","nam@gmail.com").get();
</code>```

Body:
For android solution follow this:

 FirebaseFirestore.getInstance()
                .collection("users").whereArrayContains("user","nam@gmail.com").get();


问:
How to make the navbar items active with Bootstrap 5
I am building my first site with Jekyll and Bootrstap 5. I followed the instruction on the Bootstrap 5 intro page to set up my template and navbar. However, I am not able to make the items in the navbar active as I click on them.

Below you can see my html code:

```<code><!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!-- CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <link rel="stylesheet" href="/css/mystyle.css">

    <!-- Title -->
    <title>My title</title>
  </head>

  <body>
    <!-- Navbar -->
    <nav class="navbar fixed-top navbar-expand-lg navbar-light">
      <div class="container-fluid">
        <a class="navbar-brand" href="/index"><img src="logo/logo.svg" alt="" width="" height="60">
        </a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
          <ul class="navbar-nav ms-auto">
            <li class="nav-item">
              <a class="nav-link active" aria-current="page" href="/home">Home</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="/pricing">Pricing</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="/about">About</a>
            </li>
          </ul>
        </div>
      </div>
    </nav>

    <!-- Js -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <script src="/js/myscript.js"></script>
  </body>
</html>
</code>```

Below is my css code (which is in the "mystyle.css" file):

```<code>.active {
  background-color: green;
}
</code>```

And below is my js code (which is in the "myscript.js" file)

```<code>$(".navbar .nav-link").on("click", function(){
   $(".navbar").find(".active").removeClass("active");
   $(this).addClass("active");
});
</code>```

What am I doing wrong?
Thanks!

答: You need to link the jquery for it to work.</p>

Body:
I am building my first site with Jekyll and Bootrstap 5. I followed the instruction on the Bootstrap 5 intro page to set up my template and navbar. However, I am not able to make the items in the navbar active as I click on them.

Below you can see my html code:

<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <link rel="stylesheet" href="/css/mystyle.css">

    <title>My title</title>

        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

        </button>

              Home

              Pricing

              About

Below is my css code (which is in the "mystyle.css" file):

.active {
  background-color: green;
}

And below is my js code (which is in the "myscript.js" file)

$(".navbar .nav-link").on("click", function(){
   $(".navbar").find(".active").removeClass("active");
   $(this).addClass("active");
});

What am I doing wrong?
Thanks!


问:
How to Import a Single Lodash Function?
Using webpack, I'm trying to import isEqual since lodash seems to be importing everything. I've tried doing the following with no success:

```<code>import { isEqual } from 'lodash'

import isEqual from 'lodash/lang'

import isEqual from 'lodash/lang/isEqual'

import { isEqual } from 'lodash/lang'

import { isEqual } from 'lodash/lang'
</code>```

答:
If you're using a REPL on the browser (chrome dev tools or Deno for example), and you really just need to quickly test something without using any IDE, babel or tool, you can import a single or more lodash functions from almost any website unless they're CORS restricted, in the following way:

(arr => Promise.all(arr.map(_ =>
  import ('https://cdn.skypack.dev/lodash.' + _))).then(_ => _[0].default(arr, _.map(d => d.default))))(
  ["zip", "unzip", "groupby", "mapvalues"])
  .then(_ => Object.fromEntries(_)).then(_ => {
  //you can use _ with zip, unzip, groupby, and mapvalues
  console.log(Object.keys(_))
})```

Title: How to Import a Single Lodash Function?

Body:
Using webpack, I'm trying to import isEqual since lodash seems to be importing everything. I've tried doing the following with no success:

import { isEqual } from 'lodash'

import isEqual from 'lodash/lang'

import isEqual from 'lodash/lang/isEqual'

import { isEqual } from 'lodash/lang'

import { isEqual } from 'lodash/lang'


问:
Converting nested loops into forEach();
Im trying to learn forEach() method but i cant find more advanced examples. So i thought about refactoring my Codewars code to learn from it. I dont know know to properly use forEach method in nested loops. Hope You can help me learn from this example :)

6 kyu - Replace With Alphabet Position
https://www.codewars.com/kata/546f922b54af40e1e90001da/train/javascript

```<code>function alphabetPosition(text) {
    let textToArray = text.replace(/[^a-zA-Z]/gi,'').toUpperCase().split(''); //Eliminate anything thats not a letter
    const alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
    let pointsHolder = [];                            //empty array for score
    for (let i = 0; i < textToArray.length; i++){
        for  (let j = 0; j < alphabet.length; j++) {
            if (textToArray[i] == alphabet[j] ) {     //We check the index of given string letter in alphabet
                pointsHolder.push(j+1)                //give it a score based on place in alphabet(+1 for 0 as 1st index)
            }
        }
    }
    return pointsHolder.join(' ');                    //return scored array as a string with spaces
}
</code>```

答:
An alternative to the charCode solution proposed in Terry's answer but which also avoids nested loops is be to create a Map of the characters you want to score against and then access it per character from the passed string.

Keep in mind that strings are iterable without needing to convert to an array.

function alphabetPosition(text) {
  text = text.toUpperCase().replace(/[^A-Z]/gi, '');

  const alphabet = new Map(
    ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
      .map((v, i) => [v, i + 1])
  );

  const pointsHolder = [];
  for (const char of text) {
    pointsHolder.push(alphabet.get(char))
  }

  return pointsHolder.join(' ');
}

console.log(alphabetPosition("ABCSTU"))```
</div>
</div>
</p>
<p>This also allows you to use a Map which doesn't necessarily have consecutive charCodes</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function alphabetPosition(text) {
  text = text.toUpperCase().replace(/[^]/gi, '');

  const alphabet = new Map(
    ["", "", ""]
      .map((v, i) => [v, i + 1])
  );

  const pointsHolder = [];
  for (const char of text) {
    pointsHolder.push(alphabet.get(char))
  }

  return pointsHolder.join(' ');
}

console.log(alphabetPosition("ABCSTU"))</code>```

Title: Converting nested loops into forEach();

Body:
Im trying to learn forEach() method but i cant find more advanced examples. So i thought about refactoring my Codewars code to learn from it. I dont know know to properly use forEach method in nested loops. Hope You can help me learn from this example :)

6 kyu - Replace With Alphabet Position
https://www.codewars.com/kata/546f922b54af40e1e90001da/train/javascript

function alphabetPosition(text) {
    let textToArray = text.replace(/[^a-zA-Z]/gi,'').toUpperCase().split(''); //Eliminate anything thats not a letter
    const alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
    let pointsHolder = [];                            //empty array for score
    for (let i = 0; i < textToArray.length; i++){
        for  (let j = 0; j < alphabet.length; j++) {
            if (textToArray[i] == alphabet[j] ) {     //We check the index of given string letter in alphabet
                pointsHolder.push(j+1)                //give it a score based on place in alphabet(+1 for 0 as 1st index)
            }
        }
    }
    return pointsHolder.join(' ');                    //return scored array as a string with spaces
}

Body:
An alternative to the charCode solution proposed in Terry's answer but which also avoids nested loops is be to create a Map of the characters you want to score against and then access it per character from the passed string.

Keep in mind that strings are iterable without needing to convert to an array.

function alphabetPosition(text) {
  text = text.toUpperCase().replace(/[^A-Z]/gi, '');

  const alphabet = new Map(
    ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
      .map((v, i) => [v, i + 1])
  );

  const pointsHolder = [];
  for (const char of text) {
    pointsHolder.push(alphabet.get(char))
  }

  return pointsHolder.join(' ');
}

console.log(alphabetPosition("ABCSTU"))

This also allows you to use a Map which doesn't necessarily have consecutive charCodes

function alphabetPosition(text) {
  text = text.toUpperCase().replace(/[^]/gi, '');

  const alphabet = new Map(
    ["", "", ""]
      .map((v, i) => [v, i + 1])
  );

  const pointsHolder = [];
  for (const char of text) {
    pointsHolder.push(alphabet.get(char))
  }

  return pointsHolder.join(' ');
}

console.log(alphabetPosition("ABCSTU"))


问:
focus on textarea inside v-for issue
I have comments and replies .

when i click the reply button on the comment i want it to focus on the collapsed textarea .

there is many textareas since its a comment section ..

```<code>  <div class="bg-white border shadow-soft p-4 mb-4" v-for="comment in comments" :key="comment.id"
</code>```

The reply button :

```<code>   <b-button class="text-action font-weight-light font-small" v-b-toggle="'collapse-'+comment.id" @click="focusTextArea('replay'+comment.id)">
                    <i class="fas fa-reply mr-2"></i> رد</b-button>

</code>```

textarea :

```<code>   <b-collapse :id="'collapse-'+comment.id">
     <textarea class="form-control " v-model="reply"  placeholder="Reply to John Doe" rows="6"  :ref="'replay'+comment.id"></textarea>
    <div class="d-flex justify-content-between mt-3"><small class="font-weight-light"><span >1000</span> characters remaining</small>
<button class="btn btn-primary btn-sm animate-up-2" type="button" @click="replyTo(comment)">send</button>
   </div>
    </b-collapse>
</code>```

I have tried this :

```<code>   focusTextArea(textarea) {
                this.$nextTick(() => {
                    this.$refs[textarea][0].focus();
                });
            },
</code>```

and on click on the button above ^.

when i click the button nothing happens but when i click the button back the textarea gets collapsed and the focus appears while its collapsing :\

Any idea whats wrong here?

答:
i have created a codepen for this.

Your approach is right so far, but keep in mind that the collapse element has an animation which you should wait for before triggering the focus().

https://codepen.io/elsib/pen/GROEVRe

Title: focus on textarea inside v-for issue

Body:
I have comments and replies .

when i click the reply button on the comment i want it to focus on the collapsed textarea .

there is many textareas since its a comment section ..

  <div class="bg-white border shadow-soft p-4 mb-4" v-for="comment in comments" :key="comment.id"

The reply button :

                     رد

textarea :

     <textarea class="form-control " v-model="reply"  placeholder="Reply to John Doe" rows="6"  :ref="'replay'+comment.id"></textarea>

1000 characters remaining
<button class="btn btn-primary btn-sm animate-up-2" type="button" @click="replyTo(comment)">send</button>

I have tried this :

   focusTextArea(textarea) {
                this.$nextTick(() => {
                    this.$refs[textarea][0].focus();
                });
            },

and on click on the button above ^.

when i click the button nothing happens but when i click the button back the textarea gets collapsed and the focus appears while its collapsing :\

Any idea whats wrong here?


问:
Class constructor l cannot be invoked without 'new'
Here is the full error:

Class constructor l cannot be invoked without 'new' TypeError: Class
constructor l cannot be invoked without 'new'
at renderWithHooks (http://localhost:6006/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_lib_runtime_RefreshUtils_js-node_mod-c02f3e.iframe.bundle.js:85190:18)
at mountIndeterminateComponent (http://localhost:6006/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_lib_runtime_RefreshUtils_js-node_mod-c02f3e.iframe.bundle.js:88016:13)
at beginWork (http://localhost:6006/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_lib_runtime_RefreshUtils_js-node_mod-c02f3e.iframe.bundle.js:89254:16)
at HTMLUnknownElement.callCallback (http://localhost:6006/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_lib_runtime_RefreshUtils_js-node_mod-c02f3e.iframe.bundle.js:74150:14)
at Object.invokeGuardedCallbackDev (http://localhost:6006/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_lib_runtime_RefreshUtils_js-node_mod-c02f3e.iframe.bundle.js:74199:16)
at invokeGuardedCallback (http://localhost:6006/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_lib_runtime_RefreshUtils_js-node_mod-c02f3e.iframe.bundle.js:74261:31)
at beginWork$1 (http://localhost:6006/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_lib_runtime_RefreshUtils_js-node_mod-c02f3e.iframe.bundle.js:94164:7)
at performUnitOfWork (http://localhost:6006/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_lib_runtime_RefreshUtils_js-node_mod-c02f3e.iframe.bundle.js:92976:12)
at workLoopSync (http://localhost:6006/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_lib_runtime_RefreshUtils_js-node_mod-c02f3e.iframe.bundle.js:92907:5)
at renderRootSync (http://localhost:6006/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_lib_runtime_RefreshUtils_js-node_mod-c02f3e.iframe.bundle.js:92870:7)

Here is my component file:

```<code>import React from "react";
import PropTypes from "prop-types";
import { ClrLoadingState, CdsButton } from "@cds/core/button";

const ButtonProgress = ({ isButtonDisabled, buttonLabel, onClick, ...props }) => {
  const loadingState = true;
  const onClickHandler = () => {
    alert("Button clicked");
  };
  const isDisabled = loadingState === ClrLoadingState.loading || isButtonDisabled;
  return (
    <CdsButton
      loading-state={loadingState}
      disabled={isDisabled}
      value={buttonLabel}
      name={buttonLabel}
      onClick={onClickHandler}
      {...props}
    />
  );
};

ButtonProgress.propTypes = {
  isButtonDisabled: PropTypes.bool,
  buttonLabel: PropTypes.string.isRequired,
  onClick: PropTypes.func.isRequired,
};

ButtonProgress.defaultProps = {
  isButtonDisabled: false,
};

export default ButtonProgress;
</code>```

I am not using any class based components still it gives me the error. Please help.

答:
You're not importing your design system properly @cds/core needs to be @cds/react. You have a host of other issues as well but here's a working example:

```<code>import React from "react";
import { ClrLoadingState, CdsButton } from "@cds/react/button";

const ButtonProgress = ({ ...props }) => {
const onClickHandler = () => {alert("Button clicked");};

  return (
   <CdsButton
     loading-state={ClrLoadingState}
     onClick={onClickHandler}
     {...props}
   >
     Label
   </CdsButton>
  );
};

ButtonProgress.defaultProps = {
 isButtonDisabled: false
};

export default ButtonProgress;
</code>```

Sandbox link: https://codesandbox.io/s/zen-liskov-58qfe?file=/src/ButtonProgress.js:0-451

You should read their docs to become more familiar: https://clarity.design/storybook/core/?path=/story/components-button--page

Body:
Here is the full error:

Class constructor l cannot be invoked without 'new' TypeError: Class
constructor l cannot be invoked without 'new'
at renderWithHooks (http://localhost:6006/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_lib_runtime_RefreshUtils_js-node_mod-c02f3e.iframe.bundle.js:85190:18)
at mountIndeterminateComponent (http://localhost:6006/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_lib_runtime_RefreshUtils_js-node_mod-c02f3e.iframe.bundle.js:88016:13)
at beginWork (http://localhost:6006/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_lib_runtime_RefreshUtils_js-node_mod-c02f3e.iframe.bundle.js:89254:16)
at HTMLUnknownElement.callCallback (http://localhost:6006/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_lib_runtime_RefreshUtils_js-node_mod-c02f3e.iframe.bundle.js:74150:14)
at Object.invokeGuardedCallbackDev (http://localhost:6006/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_lib_runtime_RefreshUtils_js-node_mod-c02f3e.iframe.bundle.js:74199:16)
at invokeGuardedCallback (http://localhost:6006/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_lib_runtime_RefreshUtils_js-node_mod-c02f3e.iframe.bundle.js:74261:31)
at beginWork$1 (http://localhost:6006/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_lib_runtime_RefreshUtils_js-node_mod-c02f3e.iframe.bundle.js:94164:7)
at performUnitOfWork (http://localhost:6006/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_lib_runtime_RefreshUtils_js-node_mod-c02f3e.iframe.bundle.js:92976:12)
at workLoopSync (http://localhost:6006/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_lib_runtime_RefreshUtils_js-node_mod-c02f3e.iframe.bundle.js:92907:5)
at renderRootSync (http://localhost:6006/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_lib_runtime_RefreshUtils_js-node_mod-c02f3e.iframe.bundle.js:92870:7)

Here is my component file:

import React from "react";
import PropTypes from "prop-types";
import { ClrLoadingState, CdsButton } from "@cds/core/button";

const ButtonProgress = ({ isButtonDisabled, buttonLabel, onClick, ...props }) => {
  const loadingState = true;
  const onClickHandler = () => {
    alert("Button clicked");
  };
  const isDisabled = loadingState === ClrLoadingState.loading || isButtonDisabled;
  return (
    <CdsButton
      loading-state={loadingState}
      disabled={isDisabled}
      value={buttonLabel}
      name={buttonLabel}
      onClick={onClickHandler}
      {...props}
    />
  );
};

ButtonProgress.propTypes = {
  isButtonDisabled: PropTypes.bool,
  buttonLabel: PropTypes.string.isRequired,
  onClick: PropTypes.func.isRequired,
};

ButtonProgress.defaultProps = {
  isButtonDisabled: false,
};

export default ButtonProgress;

I am not using any class based components still it gives me the error. Please help.

Body:
You're not importing your design system properly @cds/core needs to be @cds/react. You have a host of other issues as well but here's a working example:

import React from "react";
import { ClrLoadingState, CdsButton } from "@cds/react/button";

const ButtonProgress = ({ ...props }) => {
const onClickHandler = () => {alert("Button clicked");};

  return (
   <CdsButton
     loading-state={ClrLoadingState}
     onClick={onClickHandler}
     {...props}
   >
     Label
   </CdsButton>
  );
};

ButtonProgress.defaultProps = {
 isButtonDisabled: false
};

export default ButtonProgress;

Sandbox link: https://codesandbox.io/s/zen-liskov-58qfe?file=/src/ButtonProgress.js:0-451

You should read their docs to become more familiar: https://clarity.design/storybook/core/?path=/story/components-button--page


问:
How to update image source on hover?
I'm trying to use Next.js Image component to render images on my app page. I'm having issues understanding how to select and update the main Image src so that I can replace it with all the responsive sizes Next.js creates for Image elements.

I have a list of navigation links in my app menu and I want to assign data attributes to each one so that when these links are hovered over they update the main Image element and display a different main image for each link hovered over.

I'm new to React and the way it works, so I'm not sure what my issues are but I have made a start with some basic concepts. I have started to console log the data I have to see what I get but now I've hit a brick wall.

Here is what I have so far:

```<code>import React, { useState, useEffect, useRef } from 'react';
import Image from 'next/image';

function Header() {

  const MenuHeroImg = useRef();

  function handleMouseEnter(e) {
    console.log(e.target.getAttribute('data-project-image-url'));
    console.log(MenuHeroImg.current);
  }

  return (
    <>
     <ul>
        <li
         onMouseEnter={handleMouseEnter}
         data-project-image-url="/public/images/projects/image_2.png"
         className={`${navigationStyles['c-navigation-menu-link']}`}>
         <Link href="/project-link-here">Link</Link>
        </li>
        <li
         onMouseEnter={handleMouseEnter}
         data-project-image-url="/public/images/projects/image_3.png"
         className={`${navigationStyles['c-navigation-menu-link']}`}>
         <Link href="/project-link-here_2">Link</Link>
        </li>
     <ul>
     <picture ref={MenuHeroImg}>
       <Image
        src="/public/images/projects/image_1.png"
        alt="Image"
        width={660}
        height={835}
        layout="responsive"
       />
     </picture>
    </>
  );
}

export default Header;
</code>```

Console Log:

答:
the src should be like this:/images/projects/image_1.png;
because nextjs look for the image in the root folder that is the public folder</p>

Title: How to update image source on hover?

Body:
I'm trying to use Next.js Image component to render images on my app page. I'm having issues understanding how to select and update the main Image src so that I can replace it with all the responsive sizes Next.js creates for Image elements.

I have a list of navigation links in my app menu and I want to assign data attributes to each one so that when these links are hovered over they update the main Image element and display a different main image for each link hovered over.

I'm new to React and the way it works, so I'm not sure what my issues are but I have made a start with some basic concepts. I have started to console log the data I have to see what I get but now I've hit a brick wall.

Here is what I have so far:

import React, { useState, useEffect, useRef } from 'react';
import Image from 'next/image';

function Header() {

  const MenuHeroImg = useRef();

  function handleMouseEnter(e) {
    console.log(e.target.getAttribute('data-project-image-url'));
    console.log(MenuHeroImg.current);
  }

  return (
    <>

        <li
         onMouseEnter={handleMouseEnter}
         data-project-image-url="/public/images/projects/image_2.png"
         className={`${navigationStyles['c-navigation-menu-link']}`}>
         <Link href="/project-link-here">Link</Link>

        <li
         onMouseEnter={handleMouseEnter}
         data-project-image-url="/public/images/projects/image_3.png"
         className={`${navigationStyles['c-navigation-menu-link']}`}>
         <Link href="/project-link-here_2">Link</Link>

     <picture ref={MenuHeroImg}>
       <Image
        src="/public/images/projects/image_1.png"
        alt="Image"
        width={660}
        height={835}
        layout="responsive"
       />
     </picture>
    </>
  );
}

export default Header;

Console Log:


问:
AssertJ Swing enterText() writing wrong symbols
I'm using Swing to create a GUI for my application that has a JSpinner named "spinner". Inside the tests, created using AssertJ Swing I have something like this:

```<code>import org.assertj.swing.fixture.FrameFixture;
import org.assertj.swing.edt.GuiActionRunner;

FrameFixture window;
MyView view;
GuiActionRunner.execute(() -> {
    view = new MyView();
    return view;
});
window = new FrameFixture(view);
window.spinner("spinner").enterText("-1");
</code>```

This code runs without any problems on Ubuntu. However while testing the same code on MacOS with an Italian keyboard, I've noticed that instead of entering "-1" the text written is "'1". This happens also for other symbols like "\\" that turns into an "ù".

If I manually enter "-1" inside the spinner on mac it is written ok. So I guess the problem is associated to enterText() itself and mac.
Does anyone has an idea of why this is happening? Thanks.

Update:

In order to isolate the problem I've also tried doing:

```<code>String minus = java.awt.event.KeyEvent.getKeyText(45);
System.out.println(minus);
</code>```

From this cheat sheet, I know that 45 key corresponds to - and indeed this code works correctly.

But then I've tried:

```<code>window.spinner("spinner").click();
window.robot().pressAndReleaseKeys(45);
</code>```

Or similarly by creating a new robot:

```<code>robot = new Robot();
robot.setAutoDelay(500);
window.spinner("spinner").click();
robot.keyPress(KeyEvent.VK_MINUS);
</code>```

This two fragment of code again instead of writing - write '. From this old discussion I suspect that there is a bug in the key mapping for the Italian keyboard in a way similar to the bugs mentioned in the discussion for the French and German keyboard.

答:
Here, I've discovered that the tests can be executed using the following VM argument for assertj:

```<code>-Dassertj.swing.keyboard.locale=language
</code>```

Indeed by specifying a different language the keyboard mapping changes, overriding the default one.
Of course choosing "it" as language hasn't solved the problem. I did some tests changing different keyboard locale. The one that works the best for my italian MacBook is surprisingly the Finnish keyboard layout.

I've tested a few symbols with:

window.spinner("spinner").enterText("-123456789;.,_èé@)(/&%$£|\"!<>ìàòùabcdefghilmnopqrstuvzwxyjk");
```
<p>The resulting text is:</p>
```-123456789;.,?èé2)(/&%43"!lìàòùabcdefghilmnopqrstuvzwxyjk
```

Some character are still not correctly mapped, but is way better than before. For the tests that I have in my GUI this is enough. Still I would appreciate a more entirely correct solution.

In the assertj documentation I've found the KeyStrokeMappingProvider class that can be used for mapping. Besides the default one there are currently available keystroke mapping providers for German, English, Finnish, French and French + macOS. My guess is that there should be also a mapping provider for the Italian + macOS layout.

Body:
I'm using Swing to create a GUI for my application that has a JSpinner named "spinner". Inside the tests, created using AssertJ Swing I have something like this:

import org.assertj.swing.fixture.FrameFixture;
import org.assertj.swing.edt.GuiActionRunner;

FrameFixture window;
MyView view;
GuiActionRunner.execute(() -> {
    view = new MyView();
    return view;
});
window = new FrameFixture(view);
window.spinner("spinner").enterText("-1");

This code runs without any problems on Ubuntu. However while testing the same code on MacOS with an Italian keyboard, I've noticed that instead of entering "-1" the text written is "'1". This happens also for other symbols like "\\" that turns into an "ù".

If I manually enter "-1" inside the spinner on mac it is written ok. So I guess the problem is associated to enterText() itself and mac.
Does anyone has an idea of why this is happening? Thanks.

Update:

In order to isolate the problem I've also tried doing:

String minus = java.awt.event.KeyEvent.getKeyText(45);
System.out.println(minus);

From this cheat sheet, I know that 45 key corresponds to - and indeed this code works correctly.

But then I've tried:

window.spinner("spinner").click();
window.robot().pressAndReleaseKeys(45);

Or similarly by creating a new robot:

robot = new Robot();
robot.setAutoDelay(500);
window.spinner("spinner").click();
robot.keyPress(KeyEvent.VK_MINUS);

This two fragment of code again instead of writing - write '. From this old discussion I suspect that there is a bug in the key mapping for the Italian keyboard in a way similar to the bugs mentioned in the discussion for the French and German keyboard.

Body:
Here, I've discovered that the tests can be executed using the following VM argument for assertj:

-Dassertj.swing.keyboard.locale=language

Indeed by specifying a different language the keyboard mapping changes, overriding the default one.
Of course choosing "it" as language hasn't solved the problem. I did some tests changing different keyboard locale. The one that works the best for my italian MacBook is surprisingly the Finnish keyboard layout.

I've tested a few symbols with:

window.spinner("spinner").enterText("-123456789;.,_èé@)(/&%$£|\"!<>ìàòùabcdefghilmnopqrstuvzwxyjk");

The resulting text is:

-123456789;.,?èé2)(/&%43"!lìàòùabcdefghilmnopqrstuvzwxyjk

Some character are still not correctly mapped, but is way better than before. For the tests that I have in my GUI this is enough. Still I would appreciate a more entirely correct solution.

In the assertj documentation I've found the KeyStrokeMappingProvider class that can be used for mapping. Besides the default one there are currently available keystroke mapping providers for German, English, Finnish, French and French + macOS. My guess is that there should be also a mapping provider for the Italian + macOS layout.


问:
[Vis.js]How to use storePositions()
I want to know how to use the function storePositions of the dataView library Vis.js. And I want to know if there is a forum for this library(I don't found it)
Thanks for you help !

There is no documention about it, no one ask for this.
I have already try something for storing positions but I'm beginner in development. Here is my try

    let positions = network.getPositions();
    let nodesO = this.objectToArray(positions);
    let store = network.storePositions(nodesO);
    console.log(nodesO);
    console.log(store);
  }
```

I need to store the positions of my nodes when they are moved.

答:
Although @tomáš-vyčítal, a member of visjs, answered it and it makes sense, but an example would be helpful, because 'stablization' part on document makes it losing focused.

```<code>> data.nodes.get(1)
{id: 1, label: 'Node 1'}
> network.storePositions()
undefined
> data.nodes.get(1)
{id: 1, label: 'Node 1', x: 52, y: 81}
</code>```

This would be useful to save/restore positions of all nodes from/to a database

```<code>> JSON.stringify(data.nodes.get())
'[{"id":1,"label":"Node 1"},{"id":2,"label":"Node 2"},{"id":3,"label":"Node 3"},{"id":4,"label":"Node 4"},{"id":5,"label":"Node 5"}]'
> network.storePositions()
undefined
> JSON.stringify(data.nodes.get())
'[{"id":1,"label":"Node 1","x":-61,"y":-80},{"id":2,"label":"Node 2","x":15,"y":11},{"id":3,"label":"Node 3","x":-160,"y":-152},{"id":4,"label":"Node 4","x":-35,"y":126},{"id":5,"label":"Node 5","x":142,"y":-3}]'
</code>```

You may try this in console from this url.
https://visjs.github.io/vis-network/examples/network/basicUsage.html

Title: [Vis.js]How to use storePositions()

Body:
I want to know how to use the function storePositions of the dataView library Vis.js. And I want to know if there is a forum for this library(I don't found it)
Thanks for you help !

There is no documention about it, no one ask for this.
I have already try something for storing positions but I'm beginner in development. Here is my try

    let positions = network.getPositions();
    let nodesO = this.objectToArray(positions);
    let store = network.storePositions(nodesO);
    console.log(nodesO);
    console.log(store);
  }

I need to store the positions of my nodes when they are moved.

Body:
Although @tomáš-vyčítal, a member of visjs, answered it and it makes sense, but an example would be helpful, because 'stablization' part on document makes it losing focused.

> data.nodes.get(1)
{id: 1, label: 'Node 1'}
> network.storePositions()
undefined
> data.nodes.get(1)
{id: 1, label: 'Node 1', x: 52, y: 81}

This would be useful to save/restore positions of all nodes from/to a database

> JSON.stringify(data.nodes.get())
'[{"id":1,"label":"Node 1"},{"id":2,"label":"Node 2"},{"id":3,"label":"Node 3"},{"id":4,"label":"Node 4"},{"id":5,"label":"Node 5"}]'
> network.storePositions()
undefined
> JSON.stringify(data.nodes.get())
'[{"id":1,"label":"Node 1","x":-61,"y":-80},{"id":2,"label":"Node 2","x":15,"y":11},{"id":3,"label":"Node 3","x":-160,"y":-152},{"id":4,"label":"Node 4","x":-35,"y":126},{"id":5,"label":"Node 5","x":142,"y":-3}]'

You may try this in console from this url.
https://visjs.github.io/vis-network/examples/network/basicUsage.html