问:
Timeout Exception in Zuul based routing
I have got the below setup in which my Eureka server is running and few services created and registered with Eureka are running. All the service to service calls are happing using rest template which has been load balanced and every thing is working fine.

Now, I have introduced the Zuul based routing to the application with below code/properties -

```<code>@SpringBootApplication
@EnableZuulProxy
public class ApiGatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(ApiGatewayApplication.class, args);
    }

    @Bean
     public CorsFilter corsFilter() {
         final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource= new UrlBasedCorsConfigurationSource();
         final CorsConfiguration corsConfig = new CorsConfiguration();
         corsConfig.setAllowCredentials(true);
         corsConfig.addAllowedOrigin("*");
         corsConfig.addAllowedHeader("*");
         corsConfig.addAllowedMethod("OPTIONS");
         corsConfig.addAllowedMethod("HEAD");
         corsConfig.addAllowedMethod("GET");
         corsConfig.addAllowedMethod("PUT");
         corsConfig.addAllowedMethod("POST");
         corsConfig.addAllowedMethod("DELETE");
         corsConfig.addAllowedMethod("PATCH");
         urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfig);
         return new CorsFilter(urlBasedCorsConfigurationSource);
     }
}
</code>```

With this my routing is working absolutely fine, however now there is a service which takes close to 12 seconds in its execution and my business requirements prohibit to break into smaller calls.

This results in Timeout exception in Zuul.

Below is my .yml file -

```<code>ribbon:
  ConnectTimeout: 60000
  ReadTimeout: 600000
zuul:
  host:
    socket-timeout-millis: 60000
hystrix:
    command:
        default:
            execution:
                timeout:
                    enabled: false
</code>```

Somehow the ZuulException is still coming and i am completely failing to understand what else i can do in this.

The service i am calling from Zuul API gateway has in its main class -

```<code>@EnableCircuitBreaker
</code>```

and in the service -

```<code>@HystrixCommand(fallbackMethod = "addUserFallback")
public String addUser(....
</code>```

Also the fall back method

```<code>public String addUserFallback(...
</code>```

Error stack -

```<code>com.netflix.zuul.exception.ZuulException: Forwarding error
    at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.handleException(RibbonRoutingFilter.java:164) ~[spring-cloud-netflix-core-1.2.0.RELEASE.jar:1.2.0.RELEASE]
    at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.forward(RibbonRoutingFilter.java:139) ~[spring-cloud-netflix-core-1.2.0.RELEASE.jar:1.2.0.RELEASE]
    at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.run(RibbonRoutingFilter.java:84) ~[spring-cloud-netflix-core-1.2.0.RELEASE.jar:1.2.0.RELEASE]
    at com.netflix.zuul.ZuulFilter.runFilter(ZuulFilter.java:112) ~[zuul-core-1.2.2.jar:1.2.2]
    at com.netflix.zuul.FilterProcessor.processZuulFilter(FilterProcessor.java:197) ~[zuul-core-1.2.2.jar:1.2.2]
    at com.netflix.zuul.FilterProcessor.runFilters(FilterProcessor.java:161) ~[zuul-core-1.2.2.jar:1.2.2]
    at com.netflix.zuul.FilterProcessor.route(FilterProcessor.java:120) ~[zuul-core-1.2.2.jar:1.2.2]
    at com.netflix.zuul.ZuulRunner.route(ZuulRunner.java:96) ~[zuul-core-1.2.2.jar:1.2.2]
    at com.netflix.zuul.http.ZuulServlet.route(ZuulServlet.java:116) ~[zuul-core-1.2.2.jar:1.2.2]
    at com.netflix.zuul.http.ZuulServlet.service(ZuulServlet.java:81) ~[zuul-core-1.2.2.jar:1.2.2]
    at org.springframework.web.servlet.mvc.ServletWrappingController.handleRequestInternal(ServletWrappingController.java:157) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.cloud.netflix.zuul.web.ZuulController.handleRequestInternal(ZuulController.java:43) [spring-cloud-netflix-core-1.2.0.RELEASE.jar:1.2.0.RELEASE]
    at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:174) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:50) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:105) [spring-boot-actuator-1.4.1.RELEASE.jar:1.4.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:89) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:107) [spring-boot-actuator-1.4.1.RELEASE.jar:1.4.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_91]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_91]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_91]
Caused by: com.netflix.hystrix.exception.HystrixRuntimeException: irusermanager timed-out and no fallback available.
    at com.netflix.hystrix.AbstractCommand$22.call(AbstractCommand.java:805) ~[hystrix-core-1.5.5.jar:1.5.5]
    at com.netflix.hystrix.AbstractCommand$22.call(AbstractCommand.java:790) ~[hystrix-core-1.5.5.jar:1.5.5]
    at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError(OperatorOnErrorResumeNextViaFunction.java:140) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach$DoOnEachSubscriber.onError(OnSubscribeDoOnEach.java:87) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach$DoOnEachSubscriber.onError(OnSubscribeDoOnEach.java:87) ~[rxjava-1.1.10.jar:1.1.10]
    at com.netflix.hystrix.AbstractCommand$DeprecatedOnFallbackHookApplication$1.onError(AbstractCommand.java:1470) ~[hystrix-core-1.5.5.jar:1.5.5]
    at com.netflix.hystrix.AbstractCommand$FallbackHookApplication$1.onError(AbstractCommand.java:1395) ~[hystrix-core-1.5.5.jar:1.5.5]
    at rx.internal.operators.OnSubscribeDoOnEach$DoOnEachSubscriber.onError(OnSubscribeDoOnEach.java:87) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.observers.Subscribers$5.onError(Subscribers.java:230) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeThrow.call(OnSubscribeThrow.java:44) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeThrow.call(OnSubscribeThrow.java:28) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.unsafeSubscribe(Observable.java:10211) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:51) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.unsafeSubscribe(Observable.java:10211) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:41) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.unsafeSubscribe(Observable.java:10211) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:41) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.unsafeSubscribe(Observable.java:10211) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:41) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.unsafeSubscribe(Observable.java:10211) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:41) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.unsafeSubscribe(Observable.java:10211) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError(OperatorOnErrorResumeNextViaFunction.java:142) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach$DoOnEachSubscriber.onError(OnSubscribeDoOnEach.java:87) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach$DoOnEachSubscriber.onError(OnSubscribeDoOnEach.java:87) ~[rxjava-1.1.10.jar:1.1.10]
    at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$1.run(AbstractCommand.java:1121) ~[hystrix-core-1.5.5.jar:1.5.5]
    at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:41) ~[hystrix-core-1.5.5.jar:1.5.5]
    at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:37) ~[hystrix-core-1.5.5.jar:1.5.5]
    at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable.run(HystrixContextRunnable.java:57) ~[hystrix-core-1.5.5.jar:1.5.5]
    at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$2.tick(AbstractCommand.java:1138) ~[hystrix-core-1.5.5.jar:1.5.5]
    at com.netflix.hystrix.util.HystrixTimer$1.run(HystrixTimer.java:99) ~[hystrix-core-1.5.5.jar:1.5.5]
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) ~[na:1.8.0_91]
    at java.util.concurrent.FutureTask.runAndReset(Unknown Source) ~[na:1.8.0_91]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(Unknown Source) ~[na:1.8.0_91]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) ~[na:1.8.0_91]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_91]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_91]
    ... 1 common frames omitted
Caused by: java.util.concurrent.TimeoutException: null
    at com.netflix.hystrix.AbstractCommand.handleTimeoutViaFallback(AbstractCommand.java:980) ~[hystrix-core-1.5.5.jar:1.5.5]
    at com.netflix.hystrix.AbstractCommand.access$500(AbstractCommand.java:59) ~[hystrix-core-1.5.5.jar:1.5.5]
    at com.netflix.hystrix.AbstractCommand$12.call(AbstractCommand.java:595) ~[hystrix-core-1.5.5.jar:1.5.5]
    at com.netflix.hystrix.AbstractCommand$12.call(AbstractCommand.java:587) ~[hystrix-core-1.5.5.jar:1.5.5]
    at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError(OperatorOnErrorResumeNextViaFunction.java:140) ~[rxjava-1.1.10.jar:1.1.10]
    ... 15 common frames omitted
</code>```

Any suggestions will be really helpful.

Thanks

答:
Some of the properties and dependencies name/Id has been changed.
Please try the below properties.

```<code>ribbon:
  ConnectTimeout: 60000 //60 sec
  ReadTimeout: 60000 //60 sec
</code>```

I hope this will help you to resolve an issue with the Zuul API Gateway Timeout error.

Title: Timeout Exception in Zuul based routing

Body:
I have got the below setup in which my Eureka server is running and few services created and registered with Eureka are running. All the service to service calls are happing using rest template which has been load balanced and every thing is working fine.

Now, I have introduced the Zuul based routing to the application with below code/properties -

@SpringBootApplication
@EnableZuulProxy
public class ApiGatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(ApiGatewayApplication.class, args);
    }

    @Bean
     public CorsFilter corsFilter() {
         final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource= new UrlBasedCorsConfigurationSource();
         final CorsConfiguration corsConfig = new CorsConfiguration();
         corsConfig.setAllowCredentials(true);
         corsConfig.addAllowedOrigin("*");
         corsConfig.addAllowedHeader("*");
         corsConfig.addAllowedMethod("OPTIONS");
         corsConfig.addAllowedMethod("HEAD");
         corsConfig.addAllowedMethod("GET");
         corsConfig.addAllowedMethod("PUT");
         corsConfig.addAllowedMethod("POST");
         corsConfig.addAllowedMethod("DELETE");
         corsConfig.addAllowedMethod("PATCH");
         urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfig);
         return new CorsFilter(urlBasedCorsConfigurationSource);
     }
}

With this my routing is working absolutely fine, however now there is a service which takes close to 12 seconds in its execution and my business requirements prohibit to break into smaller calls.

This results in Timeout exception in Zuul.

Below is my .yml file -

ribbon:
  ConnectTimeout: 60000
  ReadTimeout: 600000
zuul:
  host:
    socket-timeout-millis: 60000
hystrix:
    command:
        default:
            execution:
                timeout:
                    enabled: false

Somehow the ZuulException is still coming and i am completely failing to understand what else i can do in this.

The service i am calling from Zuul API gateway has in its main class -

@EnableCircuitBreaker

and in the service -

@HystrixCommand(fallbackMethod = "addUserFallback")
public String addUser(....

Also the fall back method

public String addUserFallback(...

Error stack -

com.netflix.zuul.exception.ZuulException: Forwarding error
    at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.handleException(RibbonRoutingFilter.java:164) ~[spring-cloud-netflix-core-1.2.0.RELEASE.jar:1.2.0.RELEASE]
    at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.forward(RibbonRoutingFilter.java:139) ~[spring-cloud-netflix-core-1.2.0.RELEASE.jar:1.2.0.RELEASE]
    at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.run(RibbonRoutingFilter.java:84) ~[spring-cloud-netflix-core-1.2.0.RELEASE.jar:1.2.0.RELEASE]
    at com.netflix.zuul.ZuulFilter.runFilter(ZuulFilter.java:112) ~[zuul-core-1.2.2.jar:1.2.2]
    at com.netflix.zuul.FilterProcessor.processZuulFilter(FilterProcessor.java:197) ~[zuul-core-1.2.2.jar:1.2.2]
    at com.netflix.zuul.FilterProcessor.runFilters(FilterProcessor.java:161) ~[zuul-core-1.2.2.jar:1.2.2]
    at com.netflix.zuul.FilterProcessor.route(FilterProcessor.java:120) ~[zuul-core-1.2.2.jar:1.2.2]
    at com.netflix.zuul.ZuulRunner.route(ZuulRunner.java:96) ~[zuul-core-1.2.2.jar:1.2.2]
    at com.netflix.zuul.http.ZuulServlet.route(ZuulServlet.java:116) ~[zuul-core-1.2.2.jar:1.2.2]
    at com.netflix.zuul.http.ZuulServlet.service(ZuulServlet.java:81) ~[zuul-core-1.2.2.jar:1.2.2]
    at org.springframework.web.servlet.mvc.ServletWrappingController.handleRequestInternal(ServletWrappingController.java:157) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.cloud.netflix.zuul.web.ZuulController.handleRequestInternal(ZuulController.java:43) [spring-cloud-netflix-core-1.2.0.RELEASE.jar:1.2.0.RELEASE]
    at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:174) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:50) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:105) [spring-boot-actuator-1.4.1.RELEASE.jar:1.4.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:89) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:107) [spring-boot-actuator-1.4.1.RELEASE.jar:1.4.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_91]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_91]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.5.jar:8.5.5]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_91]
Caused by: com.netflix.hystrix.exception.HystrixRuntimeException: irusermanager timed-out and no fallback available.
    at com.netflix.hystrix.AbstractCommand$22.call(AbstractCommand.java:805) ~[hystrix-core-1.5.5.jar:1.5.5]
    at com.netflix.hystrix.AbstractCommand$22.call(AbstractCommand.java:790) ~[hystrix-core-1.5.5.jar:1.5.5]
    at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError(OperatorOnErrorResumeNextViaFunction.java:140) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach$DoOnEachSubscriber.onError(OnSubscribeDoOnEach.java:87) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach$DoOnEachSubscriber.onError(OnSubscribeDoOnEach.java:87) ~[rxjava-1.1.10.jar:1.1.10]
    at com.netflix.hystrix.AbstractCommand$DeprecatedOnFallbackHookApplication$1.onError(AbstractCommand.java:1470) ~[hystrix-core-1.5.5.jar:1.5.5]
    at com.netflix.hystrix.AbstractCommand$FallbackHookApplication$1.onError(AbstractCommand.java:1395) ~[hystrix-core-1.5.5.jar:1.5.5]
    at rx.internal.operators.OnSubscribeDoOnEach$DoOnEachSubscriber.onError(OnSubscribeDoOnEach.java:87) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.observers.Subscribers$5.onError(Subscribers.java:230) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeThrow.call(OnSubscribeThrow.java:44) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeThrow.call(OnSubscribeThrow.java:28) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.unsafeSubscribe(Observable.java:10211) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:51) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.unsafeSubscribe(Observable.java:10211) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:41) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.unsafeSubscribe(Observable.java:10211) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:41) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.unsafeSubscribe(Observable.java:10211) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:41) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.unsafeSubscribe(Observable.java:10211) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:41) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.unsafeSubscribe(Observable.java:10211) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError(OperatorOnErrorResumeNextViaFunction.java:142) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach$DoOnEachSubscriber.onError(OnSubscribeDoOnEach.java:87) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach$DoOnEachSubscriber.onError(OnSubscribeDoOnEach.java:87) ~[rxjava-1.1.10.jar:1.1.10]
    at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$1.run(AbstractCommand.java:1121) ~[hystrix-core-1.5.5.jar:1.5.5]
    at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:41) ~[hystrix-core-1.5.5.jar:1.5.5]
    at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:37) ~[hystrix-core-1.5.5.jar:1.5.5]
    at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable.run(HystrixContextRunnable.java:57) ~[hystrix-core-1.5.5.jar:1.5.5]
    at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$2.tick(AbstractCommand.java:1138) ~[hystrix-core-1.5.5.jar:1.5.5]
    at com.netflix.hystrix.util.HystrixTimer$1.run(HystrixTimer.java:99) ~[hystrix-core-1.5.5.jar:1.5.5]
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) ~[na:1.8.0_91]
    at java.util.concurrent.FutureTask.runAndReset(Unknown Source) ~[na:1.8.0_91]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(Unknown Source) ~[na:1.8.0_91]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) ~[na:1.8.0_91]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_91]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_91]
    ... 1 common frames omitted
Caused by: java.util.concurrent.TimeoutException: null
    at com.netflix.hystrix.AbstractCommand.handleTimeoutViaFallback(AbstractCommand.java:980) ~[hystrix-core-1.5.5.jar:1.5.5]
    at com.netflix.hystrix.AbstractCommand.access$500(AbstractCommand.java:59) ~[hystrix-core-1.5.5.jar:1.5.5]
    at com.netflix.hystrix.AbstractCommand$12.call(AbstractCommand.java:595) ~[hystrix-core-1.5.5.jar:1.5.5]
    at com.netflix.hystrix.AbstractCommand$12.call(AbstractCommand.java:587) ~[hystrix-core-1.5.5.jar:1.5.5]
    at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError(OperatorOnErrorResumeNextViaFunction.java:140) ~[rxjava-1.1.10.jar:1.1.10]
    ... 15 common frames omitted

Any suggestions will be really helpful.

Thanks

Body:
Some of the properties and dependencies name/Id has been changed.
Please try the below properties.

ribbon:
  ConnectTimeout: 60000 //60 sec
  ReadTimeout: 60000 //60 sec

I hope this will help you to resolve an issue with the Zuul API Gateway Timeout error.


来源: stackexchange

问:
How do I display the return statement with this occurring error?
Just learned what a return statement is and trying to practice with it, but for some reasons it is saying my innerHTML is null?

var x = my_Function(20, 3);

function my_Function(a, b) {
    return a * b;
}
document.getElementById("return").innerHTML = x;
  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="return" onload="my_Function()"></p></code>```

答:
Your code works. https://jsfiddle.net/zx8L5esd/</p>

```<code>function my_Function(a, b) {
    return a * b;
}
document.getElementById("return").innerHTML = my_Function(20, 3);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Your code works. https://jsfiddle.net/zx8L5esd/

function my_Function(a, b) {
    return a * b;
}
document.getElementById("return").innerHTML = my_Function(20, 3);


问:
I am not able to set interval in my react app
this is my showdate.js  - >

```<code>import React, { Component } from "react";

class Showdate extends Component {
    componentWillMount() {
        setInterval(1000);
    }

    render() {
        return (
            <div>
                <h1>Welcome to GeeksforGeeks!</h1>
                <h2>{new Date().toLocaleTimeString()}</h2>
            </div>
        );
    }
}

export default Showdate;
</code>```

and rendering through index.js as ->

```<code>import React from "react";
import ReactDOM from "react-dom";
import Showdate from "./showDate";
const rootElement4 = document.getElementById("root4");
console.log(<Showdate />);
ReactDOM.render(<Showdate />, rootElement4);
</code>```

time is getting displayed but it is not refresshing by one sec as it should acc to setinterval(1000)

答:
You must do something like this:

```<code>constructor(props){
super(props);
  this.state = {
       myTime: new Date() //Initialize your state
    }
}
componentDidMount() { //Use componentDidMount instead of componentWillMount

    this.myInterval = setInterval(()=>this.tick(), 1000); //Provide a callback to setInterval
}
tick(){

  this.setState({myTime: new Date()})
}

 componentWillUnmount() {
    clearInterval(this.myInterval); //You must clear interval when the component is unmounted; otherwise it could lead to memory leakage
  }
</code>```

Then Use myTime in your JSX

{this.state.myTime.toLocaleTimeString()}

Body:
this is my showdate.js  - >

import React, { Component } from "react";

class Showdate extends Component {
    componentWillMount() {
        setInterval(1000);
    }

    render() {
        return (

Welcome to GeeksforGeeks!

{new Date().toLocaleTimeString()}

        );
    }
}

export default Showdate;

and rendering through index.js as ->

import React from "react";
import ReactDOM from "react-dom";
import Showdate from "./showDate";
const rootElement4 = document.getElementById("root4");
console.log(<Showdate />);
ReactDOM.render(<Showdate />, rootElement4);

time is getting displayed but it is not refresshing by one sec as it should acc to setinterval(1000)

Body:
You must do something like this:

constructor(props){
super(props);
  this.state = {
       myTime: new Date() //Initialize your state
    }
}
componentDidMount() { //Use componentDidMount instead of componentWillMount

    this.myInterval = setInterval(()=>this.tick(), 1000); //Provide a callback to setInterval
}
tick(){

  this.setState({myTime: new Date()})
}

 componentWillUnmount() {
    clearInterval(this.myInterval); //You must clear interval when the component is unmounted; otherwise it could lead to memory leakage
  }

Then Use myTime in your JSX
  <h2>{this.state.myTime.toLocaleTimeString()}</h2>


问:
How to find credentials of Sandbox HDP-3.0.1 Atlas installed in Docker
https://www.cloudera.com/tutorials/sandbox-deployment-and-install-guide/3.html

I am following above reference and get HDP installed in linux docker. Most of the services are running. Able to log into Ambari, Ranger as admin and raj_ops respectively but could not log into Atlas. The strange thing is that following below to add policy in Ranger results in 401 error.
https://docs.cloudera.com/HDPDocuments/HDP3/HDP-3.0.1/configuring-atlas/content/configuring_atlas_authorization.html

The authorization policy is set to Ranger.

The archive scripts used to install above HDP image.
https://archive.cloudera.com/hwx-sandbox/hdp/hdp-3.0.1/HDP_3.0.1_docker-deploy-scripts_18120587fc7fb.zip

Is there any docs that could help me finding creds to access Atlas?
or
Fix Ranger issue?

Let me know if anymore information could help in understanding the problem. Thank you!

答:
Actually i found answer of this question somewhere but forgot the link.
Creds for Atlas in Sandbox HDP-3.0.1 is below:

```<code>admin/admin123
</code>```

Below are for Data Steward

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

Body:
Actually i found answer of this question somewhere but forgot the link.
Creds for Atlas in Sandbox HDP-3.0.1 is below:

admin/admin123

Below are for Data Steward

holger_gov/holger_gov


问:
Redirecting IE6 users to a specific page using .htaccess
I'm tired of fixing my wordpress site so that IE6 users could view it properly. It's nothing more than wasting my time. I have 2-3 IE6 visitors daily after all.

I believe there is a way to detect if visitor is using IE6 and redirect them to a specific page via .htaccess. But I can't figure out the bullet-proof method.

Could anyone help me with this?

Thanks.

答: After doing some research for the last couple of days, I've come across the solutions presented here which, based on my experience, is the bullet-proof solution.</p>

ContentLicense: CC BY-SA 3.0


答:
you can this :

```<code>this.timerChronoId = setInterval(() => {
                this.setState({
                    time: (this.state.time + 1)
                });
            }, 1000);
</code>```

you can use this.timerChronoId after to pause the timer by calling :

```<code>clearInterval(this.timerChronoId);
</code>```

Title: I am not able to set interval in my react app

Body:
you can this :

this.timerChronoId = setInterval(() => {
                this.setState({
                    time: (this.state.time + 1)
                });
            }, 1000);

you can use this.timerChronoId after to pause the timer by calling :

clearInterval(this.timerChronoId);


问:
Passing data from a class which is Lifecycle observer to the Activity
I have a class BatteryInfo which is a life-cycle observer and in this class, there is a BroadCastReceiver which is responsible for getting all battery information. This class is working perfectly with the lifecycle of Activity from where I have called it. This means it is registering the broadcast on activity created and unRegister on closing activity. But I am confused about how to access this broadcast live information in Activity.

```<code>class BatteryInfo(
        private val _context: Context,
        private val _lifecycle: Lifecycle,
    ): LifecycleObserver {

        private var _enabled = false

        init {
            _lifecycle.addObserver(this)
        }

        private val broadcastBatteryInfoListener = object : BroadcastReceiver() {

            override fun onReceive(context: Context?, intent: Intent?) {

                intent?.let {

                    val level = it.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
                    val temperature = it.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1)
                    val voltage = it.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1)
                    val technology = it.getIntExtra(BatteryManager.EXTRA_TECHNOLOGY, -1)
                    val plugged = it.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
                    val health = it.getIntExtra(BatteryManager.EXTRA_HEALTH, -1)

                  //  Log.d("TAG", String.format("%.1f", voltage / 1000f) + " V")
                }
            }
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun start() {
          //  if (_enabled) {
                _context.registerReceiver(broadcastBatteryInfoListener,
                    IntentFilter(Intent.ACTION_BATTERY_CHANGED)
                )
          // }
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun stop() {
            _context.unregisterReceiver(broadcastBatteryInfoListener)
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        fun destroy() {
            _lifecycle.removeObserver(this)
        }

        // connect if not connected
        fun enable() {
            _enabled = true

            if (_lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
                start()
            }
        }
    }
</code>```

I am Calling this class from MainActivity onCreate method like this

```<code>BatteryInfo(this, lifecycle)
</code>```

答:
I have done this with the help of MutableLiveData & LiveData but I am not sure it is a perfect solution or a hacky solution. I want to do a perfect solution that follows MVVM, clean-architecture, and SOLID principle without the creation of multiple objects because it is very costly.

```<code> class BatteryInfo(
            private val _context: Context,
            private val _lifecycle: Lifecycle
        ) : LifecycleObserver {

            val map = HashMap<String, Int>()
            private var _enabled = false
            private val _batteryInfoMap = MutableLiveData<HashMap<String, Int>>()

            val batteryInfo: LiveData<HashMap<String, Int>>
                get() = _batteryInfoMap

            init {
                _lifecycle.addObserver(this)
            }

            private val broadcastBatteryInfoListener = object : BroadcastReceiver() {

                override fun onReceive(context: Context?, intent: Intent?) {

                    intent?.let {

                        val level = it.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
                        val temperature = it.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1)
                        val voltage = it.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1)
                        val technology = it.getIntExtra(BatteryManager.EXTRA_TECHNOLOGY, -1)
                        val plugged = it.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
                        val health = it.getIntExtra(BatteryManager.EXTRA_HEALTH, -1)

                        map["level"] = level
                        map["temperature"] = temperature

                        _batteryInfoMap.value = map
                    }
                }
            }

            @OnLifecycleEvent(Lifecycle.Event.ON_START)
            fun start() {
                if (_enabled) {
                    _context.registerReceiver(
                        broadcastBatteryInfoListener,
                        IntentFilter(Intent.ACTION_BATTERY_CHANGED)
                    )
                }
            }

            @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
            fun stop() {
                _context.unregisterReceiver(broadcastBatteryInfoListener)
            }

            @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
            fun destroy() {
                _lifecycle.removeObserver(this)
            }

            fun enable() {
                _enabled = true

                if (_lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
                    start()
                }
            }
        }
</code>```

And inside MainActivity onCreate()

```<code>override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val into = BatteryInfo(this, lifecycle)
        into.enable()

        into.batteryInfo.observe(this, Observer {
            Log.d("TAG", "${it.values}")

        })
    }
</code>```

Body:
I have a class BatteryInfo which is a life-cycle observer and in this class, there is a BroadCastReceiver which is responsible for getting all battery information. This class is working perfectly with the lifecycle of Activity from where I have called it. This means it is registering the broadcast on activity created and unRegister on closing activity. But I am confused about how to access this broadcast live information in Activity.

class BatteryInfo(
        private val _context: Context,
        private val _lifecycle: Lifecycle,
    ): LifecycleObserver {

        private var _enabled = false

        init {
            _lifecycle.addObserver(this)
        }

        private val broadcastBatteryInfoListener = object : BroadcastReceiver() {

            override fun onReceive(context: Context?, intent: Intent?) {

                intent?.let {

                    val level = it.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
                    val temperature = it.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1)
                    val voltage = it.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1)
                    val technology = it.getIntExtra(BatteryManager.EXTRA_TECHNOLOGY, -1)
                    val plugged = it.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
                    val health = it.getIntExtra(BatteryManager.EXTRA_HEALTH, -1)

                  //  Log.d("TAG", String.format("%.1f", voltage / 1000f) + " V")
                }
            }
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun start() {
          //  if (_enabled) {
                _context.registerReceiver(broadcastBatteryInfoListener,
                    IntentFilter(Intent.ACTION_BATTERY_CHANGED)
                )
          // }
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun stop() {
            _context.unregisterReceiver(broadcastBatteryInfoListener)
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        fun destroy() {
            _lifecycle.removeObserver(this)
        }

        // connect if not connected
        fun enable() {
            _enabled = true

            if (_lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
                start()
            }
        }
    }

I am Calling this class from MainActivity onCreate method like this

BatteryInfo(this, lifecycle)

Body:
I have done this with the help of MutableLiveData & LiveData but I am not sure it is a perfect solution or a hacky solution. I want to do a perfect solution that follows MVVM, clean-architecture, and SOLID principle without the creation of multiple objects because it is very costly.

 class BatteryInfo(
            private val _context: Context,
            private val _lifecycle: Lifecycle
        ) : LifecycleObserver {

            val map = HashMap<String, Int>()
            private var _enabled = false
            private val _batteryInfoMap = MutableLiveData<HashMap<String, Int>>()

            val batteryInfo: LiveData<HashMap<String, Int>>
                get() = _batteryInfoMap

            init {
                _lifecycle.addObserver(this)
            }

            private val broadcastBatteryInfoListener = object : BroadcastReceiver() {

                override fun onReceive(context: Context?, intent: Intent?) {

                    intent?.let {

                        val level = it.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
                        val temperature = it.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1)
                        val voltage = it.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1)
                        val technology = it.getIntExtra(BatteryManager.EXTRA_TECHNOLOGY, -1)
                        val plugged = it.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
                        val health = it.getIntExtra(BatteryManager.EXTRA_HEALTH, -1)

                        map["level"] = level
                        map["temperature"] = temperature

                        _batteryInfoMap.value = map
                    }
                }
            }

            @OnLifecycleEvent(Lifecycle.Event.ON_START)
            fun start() {
                if (_enabled) {
                    _context.registerReceiver(
                        broadcastBatteryInfoListener,
                        IntentFilter(Intent.ACTION_BATTERY_CHANGED)
                    )
                }
            }

            @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
            fun stop() {
                _context.unregisterReceiver(broadcastBatteryInfoListener)
            }

            @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
            fun destroy() {
                _lifecycle.removeObserver(this)
            }

            fun enable() {
                _enabled = true

                if (_lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
                    start()
                }
            }
        }

And inside MainActivity onCreate()

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val into = BatteryInfo(this, lifecycle)
        into.enable()

        into.batteryInfo.observe(this, Observer {
            Log.d("TAG", "${it.values}")

        })
    }


问:
Make an F# class or module for a C# interface?
I am totally lost on F# interfaces. I am trying to replace my C# classes with F# types that satisfy the C# interfaces.

I have the following C# interface:

```<code>public interface IPatientName
    {
        string lastName { get; }
        string firstName { get; }
        string mi { get; }
        DateTime? birthDate { get; }
    }
</code>```

In my C# code, I have multiple Dependency Injections and other such, e.g., "List<"IPatientName>".

Assuming I have a typical C# class that implements IPatientName,
e.g.,

```<code>public class PatientName : IPatientName
{
     …………….
}
</code>```

How would a F# module or class be made to satisfy the C# compiler and replace the C# class PatientName with an F# class or module?

Thank you for any help on this.

答:
Implementing an interface is pretty straightforward. Given your example above the code below should suffice. Note: In an F# context Nullable isn't really recommended, but for C# interop it is OK to use. For F# asgnostic code its better to use the Option type which deals with the null problem better. Ionide (VS Code) extensions at time of writing can implement/generate the methods for you after you type the "interface IPatientName" part of the code in a class below.</p>

```<code>open System

// F# version of the interface you described.
type IPatientName =
    abstract member LastName: string with get
    abstract member FirstName: string with get
    abstract member Mi: string with get
    abstract member BirthDate: Nullable<DateTime> with get

// Class implementing interface above.
type PatientName =
    interface IPatientName with
        member this.BirthDate = Nullable(DateTime(2020, 1, 1))
        member this.FirstName = "FirstName"
        member this.LastName = "LastName"
        member this.Mi = "Mi"
</code>```

Body:
I am totally lost on F# interfaces. I am trying to replace my C# classes with F# types that satisfy the C# interfaces.

I have the following C# interface:

public interface IPatientName
    {
        string lastName { get; }
        string firstName { get; }
        string mi { get; }
        DateTime? birthDate { get; }
    }

In my C# code, I have multiple Dependency Injections and other such, e.g., "List<"IPatientName>".

Assuming I have a typical C# class that implements IPatientName,
e.g.,

public class PatientName : IPatientName
{
     …………….
}

How would a F# module or class be made to satisfy the C# compiler and replace the C# class PatientName with an F# class or module?

Thank you for any help on this.

Body:
Implementing an interface is pretty straightforward. Given your example above the code below should suffice. Note: In an F# context Nullable isn't really recommended, but for C# interop it is OK to use. For F# asgnostic code its better to use the Option type which deals with the null problem better. Ionide (VS Code) extensions at time of writing can implement/generate the methods for you after you type the "interface IPatientName" part of the code in a class below.

open System

// F# version of the interface you described.
type IPatientName =
    abstract member LastName: string with get
    abstract member FirstName: string with get
    abstract member Mi: string with get
    abstract member BirthDate: Nullable<DateTime> with get

// Class implementing interface above.
type PatientName =
    interface IPatientName with
        member this.BirthDate = Nullable(DateTime(2020, 1, 1))
        member this.FirstName = "FirstName"
        member this.LastName = "LastName"
        member this.Mi = "Mi"


问:
fetch record form single coulmn
I am trying to get record form product which have multiple website_id in one one column.
I am sharing a screenshot here.

I am trying to fetech record by  websiteid .if website id equal or match with inside of column then query need to fetch data.

```<code>$websiteid=1;
    $productAll=Product::where(['category_id'=>$categoryDetials->id,'status'=>1])->whereIn('website_id',$websiteid)->get();
</code>```

Please let me know it's possible becouse whereIn syntax is working for array and column value is comm seprated .
Please help me if you have any possible solution

答:
You can use whereRaw like as</p>

```<code>    $websiteid = 1;
    $productAll = Product::where(['category_id'=>$categoryDetials->id,'status'=>1])
                          ->whereRaw("find_in_set($websiteid,website_id)")
                          ->get();
</code>```

Title: fetch record form single coulmn

Body:
I am trying to get record form product which have multiple website_id in one one column.
I am sharing a screenshot here.

I am trying to fetech record by  websiteid .if website id equal or match with inside of column then query need to fetch data.

$websiteid=1;
    $productAll=Product::where(['category_id'=>$categoryDetials->id,'status'=>1])->whereIn('website_id',$websiteid)->get();

Please let me know it's possible becouse whereIn syntax is working for array and column value is comm seprated .
Please help me if you have any possible solution

Body:
You can use whereRaw like as

    $websiteid = 1;
    $productAll = Product::where(['category_id'=>$categoryDetials->id,'status'=>1])
                          ->whereRaw("find_in_set($websiteid,website_id)")
                          ->get();


答:
You will have to use whereRaw() and FIND_IN_SET()

```<code>Product::where(['category_id'=>$categoryDetials->id, 'status'=>1])
       ->whereRaw("FIND_IN_SET(" . $websiteIdArray . ", website_id)")
       ->get();
</code>```

Title: fetch record form single coulmn

Body:
You will have to use whereRaw() and FIND_IN_SET()

Product::where(['category_id'=>$categoryDetials->id, 'status'=>1])
       ->whereRaw("FIND_IN_SET(" . $websiteIdArray . ", website_id)")
       ->get();


问:
Swift stuck with occurrenceDate and birthdayContactIdentifier
I've success with EKEvent include calendar identifier, title, start/end time, etc...but only two left I am stuck with is occurrenceDate and birthdayContactIdentifier. Here my code where I am stuck:

```<code>if let getbirthday = get_event.birthdayContactIdentifier {
   print(getbirthday.description)
}
</code>```

This will show contact identifier, which work fine but how can I link to contact with identifier?

```<code>if let getoccurrence = get_event.occurrenceDate {
   print(getoccurrence.description)
}
</code>```

The result show:

```<code>2020-05-30 02:00:00 +0000
2020-05-29 06:00:00 +0000

</code>```

I am not sure why it show May 30 at 2am and May 29 at 6am because I put 8pm to 10:30pm, repeating every weekly. How can I get my app know how often repeating and what time?

Thanks for help!

答:
I found the issue. I use the code:</p>

```<code>if let getrecurrence = get_event.recurrenceRules?.first {
   if getrecurrence.frequency == .daily {print("daily!")}
   if getrecurrence.frequency == .monthly {print("monthly!")}
   if getrecurrence.frequency == .weekly {print("weekly!")}
   if getrecurrence.frequency == .yearly {print("yearly!")}
}
</code>```

Body:
I've success with EKEvent include calendar identifier, title, start/end time, etc...but only two left I am stuck with is occurrenceDate and birthdayContactIdentifier. Here my code where I am stuck:

if let getbirthday = get_event.birthdayContactIdentifier {
   print(getbirthday.description)
}

This will show contact identifier, which work fine but how can I link to contact with identifier?

if let getoccurrence = get_event.occurrenceDate {
   print(getoccurrence.description)
}

The result show:

2020-05-30 02:00:00 +0000
2020-05-29 06:00:00 +0000

I am not sure why it show May 30 at 2am and May 29 at 6am because I put 8pm to 10:30pm, repeating every weekly. How can I get my app know how often repeating and what time?

Thanks for help!

Body:
I found the issue. I use the code:

if let getrecurrence = get_event.recurrenceRules?.first {
   if getrecurrence.frequency == .daily {print("daily!")}
   if getrecurrence.frequency == .monthly {print("monthly!")}
   if getrecurrence.frequency == .weekly {print("weekly!")}
   if getrecurrence.frequency == .yearly {print("yearly!")}
}


问:
How to evaluate an equation with a function?
I'm trying to create a function which will solve for some numeric computation – which is given as a string.

Example:

def calculate(expression):
   # Solve the expression below
   return

# Result should be 19
calculate("5+8-3+9")
```

I have tried using .split() but got stuck.

答:
For a problem like this we can try tackling it by using this, a string calculator. </p>

```<code>'''
Calculates a string of characters only for addition and subtraction
with parentheses. This calculator utilizes the stack method.
'''

import re # imports regular expression library for usage

def calculate(s: str) -> int:

    s = re.sub(r'[A-Za-z\s\t]+', '', s)
    res = 0
    num = 0
    sign = 1
    stack = []
    for ss in s:
        # checks if each element is a digit
        if ss.isdigit():
            num = 10 * num + int(ss)
        # if not a digit, checks if its + or - sign
        elif ss in ["-", "+"]:
            res = res + sign * num
            num = 0
            sign = [-1, 1][ss == "+"]
            '''
            sign = [-1, 1][ss=="+"]  is the same as:
            # int(True) = 1, int(False) = 0. Hence,
            if ss == "+":
                        sign = 1
            else:
                        sign = -1
            '''
    return res + num * sign

s = input("Enter your string: ")
# OR if you'd like, can uncomment this line below and comment the line above.
# s = "5+8-3+9" # As an expression in a string

print(calculate(s))
</code>```

Body:
I'm trying to create a function which will solve for some numeric computation – which is given as a string.

Example:

def calculate(expression):
   # Solve the expression below
   return

# Result should be 19
calculate("5+8-3+9")

I have tried using .split() but got stuck.

Body:
For a problem like this we can try tackling it by using this, a string calculator.

'''
Calculates a string of characters only for addition and subtraction
with parentheses. This calculator utilizes the stack method.
'''

import re # imports regular expression library for usage

def calculate(s: str) -> int:

    s = re.sub(r'[A-Za-z\s\t]+', '', s)
    res = 0
    num = 0
    sign = 1
    stack = []
    for ss in s:
        # checks if each element is a digit
        if ss.isdigit():
            num = 10 * num + int(ss)
        # if not a digit, checks if its + or - sign
        elif ss in ["-", "+"]:
            res = res + sign * num
            num = 0
            sign = [-1, 1][ss == "+"]
            '''
            sign = [-1, 1][ss=="+"]  is the same as:
            # int(True) = 1, int(False) = 0. Hence,
            if ss == "+":
                        sign = 1
            else:
                        sign = -1
            '''
    return res + num * sign

s = input("Enter your string: ")
# OR if you'd like, can uncomment this line below and comment the line above.
# s = "5+8-3+9" # As an expression in a string

print(calculate(s))


问:
Why is there a curled bracket on the List?
Recently stumped upon this line in a program, and I have no idea what the bracket for (List<Level>) is for . Anybody got any idea ?

List<Level> levelList = (List<Level>)dao.getAllLevels();

答:
Its called typecasting. The data returned from dao.getAllLevels() is being casted into type List.

This operation might not always be successful, and in that case jvm/jre throws a ClassCastException. You can read more about object typecasting in Java here.

More about java and type-casting on Stackoverflow:

Java Type-casting Question


问:
How to make blog layout with Html Css
I am a beginner in web designing. I know some basics about layout in CSS.
I am tried to create a blog post layout, given in the picture below.
see image layout
Please help me to do that.</p>

答:
If you know about boostrap than you can use this boostrap card to create that layout you want. Here is the sample code for it.</p>

```<code><div class="card w-50">
<div class="card-img-top d-flex align-items-center bg-light">
  <div>
      <img class="img-fluid" src="http://via.placeholder.com/150x150/1f1a38/ffffff?
       text=Image" alt="Card image cap">
  </div>
 <p class="col p-2 m-0">Text next to the right of the image</p>
</div>
</div>
</code>```

Title: How to make blog layout with Html Css

Body:
If you know about boostrap than you can use this boostrap card to create that layout you want. Here is the sample code for it.

<div class="card w-50">
<div class="card-img-top d-flex align-items-center bg-light">
  <div>
      <img class="img-fluid" src="http://via.placeholder.com/150x150/1f1a38/ffffff?
       text=Image" alt="Card image cap">
  </div>
 <p class="col p-2 m-0">Text next to the right of the image</p>
</div>
</div>


问:
Terraform: Azure CLI Authorization Profile was not found. Please ensure the Azure CLI is installed
I have installed az-cli using azure link and terraform apt-get.
Getting below error while

Error: Error running plan: 1 error(s) occurred:

provider.azurerm: Error building AzureRM Client: Azure CLI Authorization Profile was not found. Please ensure the Azure CLI is installed and then log-in with az login.

Tried to uninstall and reinstall, but no luck.

答: In my case that was because I manually copied Terraform state from local to azurerm backend. When I did it the "terraform way" (change backend, init again, then terraform asks you if you want to copy the old state to the new backend), it started working.</p>


问:
Debounce or throttle event handler in Google Apps Script
I'm looking for a neat solution to debounce or throttle a webhook call used in a Google Sheets Apps Script handler. Creating a simple trigger like onEdit or an "installable trigger" for other changes is straight forward but both will call the handler for every single change. If someone is editing the sheet and updates many rows over a few seconds, I want to fire only one event and not flood my webhook service. The conventional pattern for this in Javascript is to use setTimeout and clearTimeout to ensure the body of the event handler is called only once but setTimeout is not available in the Google Apps Script runtime.

答:
If you need setTimeout and clearTimeout, include this snippet in your code:

https://script.google.com/d/1m7GaM7Z7ivgHaAwXcgpsAwg-e7tMDm9GsN5P-xpcAGT_P6cleF_mKGD3/edit?usp=drive_web


问:
How to disable swiping left or right in Dismissible widget in Flutter?
I want to disable swiping to the right once there are no data in DataBase.

if (data.length > 1) {
  // I can swipe to the left or right
} else {
  // I can't swipe to the right only left
}
```

<p><br>
Is it real to achieve this?
Perhaps, I can return an element to the center once one swiped it to the right
<br></p>

<p><strong>Solution</strong>:
I just used confirmDismiss in Dismissible widget.</p>

```confirmDismiss: (direction) {
  if(data.length > 0 && direction==..)
  // do stuff
  else if(...)
}
```

答:
Following tomblue's idea I came up with another idea which not only comes free of any error (both compilation and runtime) but also allows the developer to prevent swipe to the right or to the left:

I used the ternary with the properties in dismissThresholds set to impossible values. Full example below:

class SwiperState extends State<Swiper> {
    bool _isNotFirstIndex = false;
    bool _isNotLastIndex = true;
    int _currentIndex = 0;

    void nextOne() {
        setState(() {
            _isNotFirstIndex = !(_currentIndex - 1 < 0);
            _isNotLastIndex = !(_currentIndex + 1 == count);
        });
    }

@override
  Widget build(BuildContext context) {
    return Dismissible(
        dismissThresholds:  {DismissDirection.startToEnd: _isNotFirstIndex ? 0.05 : 2.00,
            DismissDirection.endToStart: _isNotLastIndex ? 0.05 : 2.00},
        key: UniqueKey(),
        onDismissed: (DismissDirection direction) {
          if(direction == DismissDirection.endToStart) {
            // dismissed to the left, next one
            nextOne();
          }
          else (do the same with prevOne())
               (...)
```

Body:
I want to disable swiping to the right once there are no data in DataBase.

if (data.length > 1) {
  // I can swipe to the left or right
} else {
  // I can't swipe to the right only left
}

Is it real to achieve this?
Perhaps, I can return an element to the center once one swiped it to the right

Solution:
I just used confirmDismiss in Dismissible widget.

confirmDismiss: (direction) {
  if(data.length > 0 && direction==..)
  // do stuff
  else if(...)
}


问:
progress bar loading not showing response from server?
I am developing news app but TopHeadlinesFragment loading progress bar not showing response from server
what I want to know where I am making mistake what I have to do in order to show response from server. Maybe something wrong with my observer in topHeadlinesFragment.kt or koin network module

below my screenshot of the app

loading progress

below my TopHeadlinesFragment.kt

```<code>class TopHeadlinesFragment : Fragment() {

    private lateinit var binding: FragmentTopHeadlinesBinding
    private val viewModel by viewModel<MainViewModel>()

    private lateinit var topHeadlinesAdapter: TopHeadlinesAdapter
    // private val newsRepository: NewsRepository by inject()

    //3
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_top_headlines, container, false)
        binding.lifecycleOwner = this
        topHeadlinesAdapter = TopHeadlinesAdapter()
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViewModel()
      //  loadingAds()

    }

    private fun initViewModel() {
        viewModel.sportList.observe(this, Observer { result ->

            when (result) {
                is Results.Success -> {
                    val newList = result.data
                    if (newList != null) {
                        topHeadlinesAdapter.updateData(newList)
                    }
                    binding.recyclerView.adapter = topHeadlinesAdapter
                    topHeadlinesAdapter.notifyDataSetChanged()

                    viewModel.showLoading.observe(this, Observer {showLoading ->
                        pb.visibility = if (showLoading) View.VISIBLE else View.GONE
                    })
                }
                is Results.Failure -> {
                    viewModel.showLoading.observe(this, Observer {showLoading ->
                        pb.visibility = if (showLoading) View.INVISIBLE else View.GONE
                })
            }

        }

        viewModel.loadNews()
    })

    }

    }
</code>```

below NewsRepository.kt

```<code>class NewsRepository(
    private val sportNewsApi: SportNewsInterface,
    private val sportNewsDao: SportNewsDao
) {

    companion object{
        const val  TAG=  "Error"
    }

    val data = sportNewsDao.getAllData()

    suspend fun refresh() = withContext(Dispatchers.IO) {
        val articles = sportNewsApi.getNewsAsync().body()?.articles
        if (articles != null) {
            sportNewsDao.addAll(articles)
          Log.e(TAG,"Error")
            Results.Success(articles)
        } else {
            Results.Failure("MyError")
        }
    }
}
</code>```

below My MainViewModel.kt

```<code>class MainViewModel(val newsRepository: NewsRepository) : ViewModel(), CoroutineScope {
    // Coroutine's background job
    val job = Job()

    // Define default thread for Coroutine as Main and add job
    override val coroutineContext: CoroutineContext = Dispatchers.Main + job

    private val _showLoading = MutableLiveData<Boolean>()
    private val _sportList = MutableLiveData<Results>()

    val showLoading: LiveData<Boolean>
        get() = _showLoading

    val sportList: LiveData<Results>
        get() = _sportList

    fun loadNews() {
        // Show progressBar during the operation on the MAIN (default) thread
        _showLoading.value = true
        // launch the Coroutine
        launch {
            // Switching from MAIN to IO thread for API operation
            // Update our data list with the new one from API
            val result =  newsRepository.refresh()
            _sportList.value = result
            _showLoading.value = false
        }
    }

    override fun onCleared() {
        job.cancel()
    }

}
</code>```

below my KoinNetworkModule.kt

```<code>const val BASE_URL = "https://newsapi.org/"
val netModule = module {

    single {
        createWebService<SportNewsInterface>(
            okHttpClient = createHttpClient(),
            factory = RxJava2CallAdapterFactory.create(),
            baseUrl = BASE_URL
        )
    }
}

/* Returns a custom OkHttpClient instance with interceptor. Used for building Retrofit service */
fun createHttpClient(): OkHttpClient {
    val client = OkHttpClient.Builder()
    client.readTimeout(5 * 60, TimeUnit.SECONDS)
    return client.addInterceptor {
        val original = it.request()
        val requestBuilder = original.newBuilder()
        requestBuilder.header("Content-Type", "application/json")
        val request = requestBuilder.method(original.method, original.body).build()
        return@addInterceptor it.proceed(request)
    }.build()
}

/* function to build our Retrofit service */
inline fun <reified T> createWebService(
    okHttpClient: OkHttpClient,
    factory: CallAdapter.Factory, baseUrl: String
): T {
    val retrofit = Retrofit.Builder()
        .baseUrl(baseUrl)
        .addConverterFactory(GsonConverterFactory.create(GsonBuilder().setLenient().create()))
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
        .addCallAdapterFactory(factory)
        .client(okHttpClient)
        .build()
    return retrofit.create(T::class.java)
}
</code>```

答:
I fixed problem by changing my code followingly.</p>

```<code> private fun initViewModel() {
        viewModel.sportList.observe(this, Observer { result ->

            when (result) {
                is Results.Success -> {
                    val newList = result.data
                    if (newList != null) {
                        topHeadlinesAdapter.updateData(newList)
                    }
                    binding.recyclerView.adapter = topHeadlinesAdapter
                    topHeadlinesAdapter.notifyDataSetChanged()
                }
            }
        })

        viewModel.showLoading.observe(this, Observer { showLoading ->
            pb.visibility = if (showLoading) View.VISIBLE else View.GONE
        })

        viewModel.loadNews()
    }
</code>```

Body:
I am developing news app but TopHeadlinesFragment loading progress bar not showing response from server
what I want to know where I am making mistake what I have to do in order to show response from server. Maybe something wrong with my observer in topHeadlinesFragment.kt or koin network module

below my screenshot of the app

loading progress

below my TopHeadlinesFragment.kt

class TopHeadlinesFragment : Fragment() {

    private lateinit var binding: FragmentTopHeadlinesBinding
    private val viewModel by viewModel<MainViewModel>()

    private lateinit var topHeadlinesAdapter: TopHeadlinesAdapter
    // private val newsRepository: NewsRepository by inject()

    //3
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_top_headlines, container, false)
        binding.lifecycleOwner = this
        topHeadlinesAdapter = TopHeadlinesAdapter()
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViewModel()
      //  loadingAds()

    }

    private fun initViewModel() {
        viewModel.sportList.observe(this, Observer { result ->

            when (result) {
                is Results.Success -> {
                    val newList = result.data
                    if (newList != null) {
                        topHeadlinesAdapter.updateData(newList)
                    }
                    binding.recyclerView.adapter = topHeadlinesAdapter
                    topHeadlinesAdapter.notifyDataSetChanged()

                    viewModel.showLoading.observe(this, Observer {showLoading ->
                        pb.visibility = if (showLoading) View.VISIBLE else View.GONE
                    })
                }
                is Results.Failure -> {
                    viewModel.showLoading.observe(this, Observer {showLoading ->
                        pb.visibility = if (showLoading) View.INVISIBLE else View.GONE
                })
            }

        }

        viewModel.loadNews()
    })

    }

    }

below NewsRepository.kt

class NewsRepository(
    private val sportNewsApi: SportNewsInterface,
    private val sportNewsDao: SportNewsDao
) {

    companion object{
        const val  TAG=  "Error"
    }

    val data = sportNewsDao.getAllData()

    suspend fun refresh() = withContext(Dispatchers.IO) {
        val articles = sportNewsApi.getNewsAsync().body()?.articles
        if (articles != null) {
            sportNewsDao.addAll(articles)
          Log.e(TAG,"Error")
            Results.Success(articles)
        } else {
            Results.Failure("MyError")
        }
    }
}

below My MainViewModel.kt

class MainViewModel(val newsRepository: NewsRepository) : ViewModel(), CoroutineScope {
    // Coroutine's background job
    val job = Job()

    // Define default thread for Coroutine as Main and add job
    override val coroutineContext: CoroutineContext = Dispatchers.Main + job

    private val _showLoading = MutableLiveData<Boolean>()
    private val _sportList = MutableLiveData<Results>()

    val showLoading: LiveData<Boolean>
        get() = _showLoading

    val sportList: LiveData<Results>
        get() = _sportList

    fun loadNews() {
        // Show progressBar during the operation on the MAIN (default) thread
        _showLoading.value = true
        // launch the Coroutine
        launch {
            // Switching from MAIN to IO thread for API operation
            // Update our data list with the new one from API
            val result =  newsRepository.refresh()
            _sportList.value = result
            _showLoading.value = false
        }
    }

    override fun onCleared() {
        job.cancel()
    }

}

below my KoinNetworkModule.kt

const val BASE_URL = "https://newsapi.org/"
val netModule = module {

    single {
        createWebService<SportNewsInterface>(
            okHttpClient = createHttpClient(),
            factory = RxJava2CallAdapterFactory.create(),
            baseUrl = BASE_URL
        )
    }
}

/* Returns a custom OkHttpClient instance with interceptor. Used for building Retrofit service */
fun createHttpClient(): OkHttpClient {
    val client = OkHttpClient.Builder()
    client.readTimeout(5 * 60, TimeUnit.SECONDS)
    return client.addInterceptor {
        val original = it.request()
        val requestBuilder = original.newBuilder()
        requestBuilder.header("Content-Type", "application/json")
        val request = requestBuilder.method(original.method, original.body).build()
        return@addInterceptor it.proceed(request)
    }.build()
}

/* function to build our Retrofit service */
inline fun <reified T> createWebService(
    okHttpClient: OkHttpClient,
    factory: CallAdapter.Factory, baseUrl: String
): T {
    val retrofit = Retrofit.Builder()
        .baseUrl(baseUrl)
        .addConverterFactory(GsonConverterFactory.create(GsonBuilder().setLenient().create()))
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
        .addCallAdapterFactory(factory)
        .client(okHttpClient)
        .build()
    return retrofit.create(T::class.java)
}

Body:
I fixed problem by changing my code followingly.

 private fun initViewModel() {
        viewModel.sportList.observe(this, Observer { result ->

            when (result) {
                is Results.Success -> {
                    val newList = result.data
                    if (newList != null) {
                        topHeadlinesAdapter.updateData(newList)
                    }
                    binding.recyclerView.adapter = topHeadlinesAdapter
                    topHeadlinesAdapter.notifyDataSetChanged()
                }
            }
        })

        viewModel.showLoading.observe(this, Observer { showLoading ->
            pb.visibility = if (showLoading) View.VISIBLE else View.GONE
        })

        viewModel.loadNews()
    }


问:
What's a good way to teach my son to program Java
OK, so I've read through various posts about teaching beginner's to program, and there were some helpful things I will look at more closely.  But what I want to know is whether there are any effective tools out there to teach a kid Java specifically?

I want to teach him Java specifically because (a) with my strong background in C I feel that's too complex, (b) Java is the other language I know extremely well and therefore I can assist meaningfully without needing to teach myself a new but (to me) useless language, and (c) I feel that managed languages are the future, and lastly (d) Java is one of the simplest of all the languages I know well (aside from basic).

I learned in basic, and I am open to teaching that first, but I am unaware of a decent free basic shell for Windows (though I haven't really searched, yet since it's not my first choice), and would anyway want to progress quickly to Java.

My son is 8, so that's a couple of years earlier than I started - but he has expressed an
interest in learning to program (possibly because I work from home a lot and he sees me programming all the time).

If no-one can suggest a tool designed for this purpose, I will probably start him off with text/console based apps to teach the basics, and then progress to GUI building.

Oh, one last thing, I am not a fan of IDE's (old school text editor type), so I would not be put off at all by a system that has him typing real code, and would likely prefer that to a toy drag/drop system.

EDIT: Just to clarify; I really am specifically after ways to teach him Java; there are already a good many posts with good answers for other language alternatives - but that's not what I am looking for here.

EDIT: What about Java frameworks for 2D video games - can anyone recommend any of them from personal experience?  I like the idea of him starting with the mechanics in place (main game loop, scoring, etc) and adding the specifics for a game of his own imagining - that's what I did, though for me it was basic on a Commodore VIC-20 and a Sinclair ZX-81.

答: I would not start a child with Java. Teach him something more conceptually clean first. Something like LISP, or Logo. Logo is a surprisingly powerful programming language, and it's a blast to learn since it's visually engaging right out of the box.</p>

OwnerDisplayName: Kiwi

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Apocalisp


问:
Stuck in the middle
When should I use margin-left:auto; margin-right:auto to center and when should I use margin-left:50%; margin-right:50%?

Maybe "auto" when I am centering something contained in another element & 50% when I am centering on the page?

Or I am I just hopelessly confused?

答:
margin-left:50% ; margin-right:50%; would imply that the item you are centering has no width.

For a block level element like a div, the best way to center it is:

div.centered { margin: 0 auto; }
```

The 0 before the auto refers to top and bottom so that can be set to whatever you like. The important part is the auto which will cause the left and right margins to be automatically set and they will be equal regardless of how wide your element is.

Update: As pointed out by Phelios, a width should be specified for the div for this approach to work

Title: Stuck in the middle

Body:
margin-left:50% ; margin-right:50%; would imply that the item you are centering has no width.

For a block level element like a div, the best way to center it is:

div.centered { margin: 0 auto; }

The 0 before the auto refers to top and bottom so that can be set to whatever you like. The important part is the auto which will cause the left and right margins to be automatically set and they will be equal regardless of how wide your element is.

Update: As pointed out by Phelios, a width should be specified for the div for this approach to work


问:
AsyncStorage functions just producing garbage in react native
So I implemented this code in a file from the react native docs.

```<code>class Storage {

    //store data in 'key'

    store = async (key, data) => {
        try {
            await AsyncStorage.setItem(key, data);
        } catch (error) {
            // Error saving data
            console.log(error.message);
        }
    };

    retrieve = async (key) => {
        try {
            const   value = await AsyncStorage.getItem(key);
            if (value !== null) {
                // We have data!!
                console.log(value);
            }
        } catch (error) {
            // Error retrieving data
            console.log(error.message);
        }
    };

}
</code>```

And this in other I want to use to actually store and retrieve the variables:

```<code>strg.store('test', 'testing');
testing =  strg.retrieve('test');
</code>```

I kept getting an error but then looking it up here I figured out my storage output was an object and not a string as I expected. So I used JSON.stringify(***) and this gibberish came out instead of a "testing".

{"_40":0, "_65":0, "_55":null,"_72":null}
```

edit: I figure out how to use the console to debug and I found out the 'testing' was inside the promise object that comes out of my function. I read a little about async functions and now I want to know how do I extract the values from the promises?

答:
This is how i did it and it works like a charm</p>

```<code>import { AsyncStorage } from 'react-native';

module.exports = {
    retrieve: async (value) => {
        try {
            let data = await AsyncStorage.getItem(value);
            return data;
        } catch (err) {
            return err;
        }
    },
    store: async (key, value) => {
        try {
            // stringify the value since value can only be string.
            if (typeof (value) === 'object')
                value = JSON.stringify(value)
            return await AsyncStorage.setItem(key, value);
        } catch (err) {
            console.log(err)
            return err;
        }
    }
}
</code>```

Body:
So I implemented this code in a file from the react native docs.

class Storage {

    //store data in 'key'

    store = async (key, data) => {
        try {
            await AsyncStorage.setItem(key, data);
        } catch (error) {
            // Error saving data
            console.log(error.message);
        }
    };

    retrieve = async (key) => {
        try {
            const   value = await AsyncStorage.getItem(key);
            if (value !== null) {
                // We have data!!
                console.log(value);
            }
        } catch (error) {
            // Error retrieving data
            console.log(error.message);
        }
    };

}

And this in other I want to use to actually store and retrieve the variables:

strg.store('test', 'testing');
testing =  strg.retrieve('test');

I kept getting an error but then looking it up here I figured out my storage output was an object and not a string as I expected. So I used JSON.stringify(***) and this gibberish came out instead of a "testing".

{"_40":0, "_65":0, "_55":null,"_72":null}

edit: I figure out how to use the console to debug and I found out the 'testing' was inside the promise object that comes out of my function. I read a little about async functions and now I want to know how do I extract the values from the promises?

Body:
This is how i did it and it works like a charm

import { AsyncStorage } from 'react-native';

module.exports = {
    retrieve: async (value) => {
        try {
            let data = await AsyncStorage.getItem(value);
            return data;
        } catch (err) {
            return err;
        }
    },
    store: async (key, value) => {
        try {
            // stringify the value since value can only be string.
            if (typeof (value) === 'object')
                value = JSON.stringify(value)
            return await AsyncStorage.setItem(key, value);
        } catch (err) {
            console.log(err)
            return err;
        }
    }
}


问:
Two strings are anagrams or not question quitted with code 11 on C++ Clion
```<code>#include <iostream>
#include <string>
#include <cctype>
using namespace std;

void LowerCharacters(string& text);
void OutPutEachLetter(string text, int* ptr);
void comparePointers();

int main() {
    string text1, text2; bool isAnagrams = true;
    int *ptr1=NULL, *ptr2=NULL;
    cout<<"Please enter first string ";
    getline(cin,text1);
    cout<<"Please enter second string ";
    getline(cin,text2);
    LowerCharacters(text1);
    LowerCharacters(text2);
    OutPutEachLetter(text1, ptr1);
    OutPutEachLetter(text2, ptr2);
    for(int i =0; i<26;i++) {
        if (ptr1[i] != ptr2[i]) {
            isAnagrams = false;
        }
    }
    if(isAnagrams)
        cout<<"These two strings are anagrams";
    else
        cout<<"These two strings are not anagrams";
    delete []ptr1; delete []ptr2;
    ptr1=NULL; ptr2=NULL;
}

void LowerCharacters(string& text) {
    for (int i = 0; i < text.length(); i++) {
            text[i]=tolower(text[i]);
        }
    }

void OutPutEachLetter(string text, int* ptr){

    ptr = new int[26];
    *ptr = {0};
    for(int i =0;i<text.length()-1;i++)
    {
        ptr[text[i]-'a']++;
    }
    for(int j=0;j<26;j++){
        if(ptr[j]!=0){
            cout<<ptr[j]<<"\t"<<char(j+'a')<<endl;
        }
    }
}
</code>```

Above was my code. I thought it would have worked but it did not. it printed the ptr1 successfully but never printed the ptr2. I want to know why... Any help will be appreciated!
I am kind of new to pointer stuff, I just wanted to try my best to use the pointer in my code so that I can practice more. I know that I can totally just create two static arrays in the main part and then write the array in my function OutputEachLetter as an argument and use the pass as a reference like int &arr. However, I really want to know why is my current code wrong and why am I not allowed to use this kind of code.

答:
You could just do a little effort by adding algorithm library plus you're using C++, take some benefits of it. Just use the transform() for conversion of strings into lower case, and sort them then see if they're equal or not.

Everything could  be done in a simplified way.

Consider the written program:

```<code>#include <iostream>
#include <algorithm>

int main(void) {
    std::string str1, str2;

    std::cout << "Enter the first string: ";
    std::getline(std::cin, str1);

    std::cout << "Enter the second string: ";
    std::getline(std::cin, str2);

    /* --- this --- */
    transform(str1.begin(), str1.end(), str1.begin(), ::tolower);
    transform(str2.begin(), str2.end(), str2.begin(), ::tolower);

    std::sort(str1.begin(), str1.end());
    std::sort(str2.begin(), str2.end());

    if (str1 == str2)
        std::cout << "Both strings are anagrams";
    else
        std::cout << "No anagrams";
    std::cout << std::endl;

    return 0;
}
</code>```

Body:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;

void LowerCharacters(string& text);
void OutPutEachLetter(string text, int* ptr);
void comparePointers();

int main() {
    string text1, text2; bool isAnagrams = true;
    int *ptr1=NULL, *ptr2=NULL;
    cout<<"Please enter first string ";
    getline(cin,text1);
    cout<<"Please enter second string ";
    getline(cin,text2);
    LowerCharacters(text1);
    LowerCharacters(text2);
    OutPutEachLetter(text1, ptr1);
    OutPutEachLetter(text2, ptr2);
    for(int i =0; i<26;i++) {
        if (ptr1[i] != ptr2[i]) {
            isAnagrams = false;
        }
    }
    if(isAnagrams)
        cout<<"These two strings are anagrams";
    else
        cout<<"These two strings are not anagrams";
    delete []ptr1; delete []ptr2;
    ptr1=NULL; ptr2=NULL;
}

void LowerCharacters(string& text) {
    for (int i = 0; i < text.length(); i++) {
            text[i]=tolower(text[i]);
        }
    }

void OutPutEachLetter(string text, int* ptr){

    ptr = new int[26];
    *ptr = {0};
    for(int i =0;i<text.length()-1;i++)
    {
        ptr[text[i]-'a']++;
    }
    for(int j=0;j<26;j++){
        if(ptr[j]!=0){
            cout<<ptr[j]<<"\t"<<char(j+'a')<<endl;
        }
    }
}

Above was my code. I thought it would have worked but it did not. it printed the ptr1 successfully but never printed the ptr2. I want to know why... Any help will be appreciated!
I am kind of new to pointer stuff, I just wanted to try my best to use the pointer in my code so that I can practice more. I know that I can totally just create two static arrays in the main part and then write the array in my function OutputEachLetter as an argument and use the pass as a reference like int &arr. However, I really want to know why is my current code wrong and why am I not allowed to use this kind of code.

Body:
You could just do a little effort by adding algorithm library plus you're using C++, take some benefits of it. Just use the transform() for conversion of strings into lower case, and sort them then see if they're equal or not.

Everything could  be done in a simplified way.

Consider the written program:

#include <iostream>
#include <algorithm>

int main(void) {
    std::string str1, str2;

    std::cout << "Enter the first string: ";
    std::getline(std::cin, str1);

    std::cout << "Enter the second string: ";
    std::getline(std::cin, str2);

    /* --- this --- */
    transform(str1.begin(), str1.end(), str1.begin(), ::tolower);
    transform(str2.begin(), str2.end(), str2.begin(), ::tolower);

    std::sort(str1.begin(), str1.end());
    std::sort(str2.begin(), str2.end());

    if (str1 == str2)
        std::cout << "Both strings are anagrams";
    else
        std::cout << "No anagrams";
    std::cout << std::endl;

    return 0;
}