text:
Q: org.springframework.security.oauth2.common.exceptions.InvalidGrantException: Bad credentials I'm developing Spring Boot + Authorization Server +  OAuth Resource Server . In this example I can easily query though postman over spring-microservices-oauth-server and get the protected data. I created the client to access the data which postman is doing. But I am getting below error, which doesn't get clear to me. Using Spring Boot v2.1.1.RELEASE and spring-cloud-dependencies version Greenwich.RC2.

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is error="access_denied", error_description="Access token denied."] with root cause

Error:
org.springframework.security.oauth2.common.exceptions.InvalidGrantException: Bad credentials
    at org.springframework.security.oauth2.common.exceptions.OAuth2ExceptionJackson2Deserializer.deserialize(OAuth2ExceptionJackson2Deserializer.java:90) ~[spring-security-oauth2-2.3.3.RELEASE.jar:na]
    at org.springframework.security.oauth2.common.exceptions.OAuth2ExceptionJackson2Deserializer.deserialize(OAuth2ExceptionJackson2Deserializer.java:33) ~[spring-security-oauth2-2.3.3.RELEASE.jar:na]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3084) ~[jackson-databind-2.9.7.jar:2.9.7]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:239) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readInternal(AbstractJackson2HttpMessageConverter.java:219) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:199) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport$AccessTokenErrorHandler.handleError(OAuth2AccessTokenSupport.java:237) ~[spring-security-oauth2-2.3.3.RELEASE.jar:na]
    at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:777) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:735) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:690) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport.retrieveToken(OAuth2AccessTokenSupport.java:137) ~[spring-security-oauth2-2.3.3.RELEASE.jar:na]
    at org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordAccessTokenProvider.obtainAccessToken(ResourceOwnerPasswordAccessTokenProvider.java:47) ~[spring-security-oauth2-2.3.3.RELEASE.jar:na]
    at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainNewAccessTokenInternal(AccessTokenProviderChain.java:148) ~[spring-security-oauth2-2.3.3.RELEASE.jar:na]
    at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainAccessToken(AccessTokenProviderChain.java:121) ~[spring-security-oauth2-2.3.3.RELEASE.jar:na]
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:221) ~[spring-security-oauth2-2.3.3.RELEASE.jar:na]
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken(OAuth2RestTemplate.java:173) ~[spring-security-oauth2-2.3.3.RELEASE.jar:na]
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.createRequest(OAuth2RestTemplate.java:105) ~[spring-security-oauth2-2.3.3.RELEASE.jar:na]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:730) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.doExecute(OAuth2RestTemplate.java:128) ~[spring-security-oauth2-2.3.3.RELEASE.jar:na]
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:636) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at com.oreilly.cloud.SpringMicroservicesOauthClientApplication.execute(SpringMicroservicesOauthClientApplication.java:57) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_171]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_171]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_171]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_171]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.13.jar:9.0.13]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter.doFilter(OAuth2ClientContextFilter.java:60) ~[spring-security-oauth2-2.3.3.RELEASE.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.java:90) ~[spring-boot-actuator-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter.doFilterInternal(DefaultLogoutPageGeneratingFilter.java:52) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:206) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:100) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:74) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:117) ~[spring-boot-actuator-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:106) ~[spring-boot-actuator-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:791) [tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417) [tomcat-embed-core-9.0.13.jar:9.0.13]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.13.jar:9.0.13]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_171]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_171]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.13.jar:9.0.13]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_171]

spring-microservices-oauth-server
AuthorizationServerConfig.java
@Configuration
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter{
    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
            .inMemory()
            .withClient("webapp")
            .secret("{noop}websecret")
            //.authorizedGrantTypes("password", "refresh_token")
            .authorizedGrantTypes("password")
            .scopes("read,write,trust")
            .accessTokenValiditySeconds(1800);
    }
}

WebSecurityConfig.java
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();

        // @formatter:off
        auth
            .inMemoryAuthentication()
            .withUser("user1").password(encoder.encode("password1")).roles("USER")
            .and()
            .withUser("john").password(encoder.encode("password1")).roles("USER", "ADMIN")
            .and()
            .withUser("sally").password(encoder.encode("password1")).roles("ADMIN");
        // @formatter:on
    }
}

SpringMicroservicesOauthServerApplication.java
@SpringBootApplication
@EnableAuthorizationServer
@EnableResourceServer
@RestController
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringMicroservicesOauthServerApplication {

    @RequestMapping("/resource/endpoint")
    @PreAuthorize("hasRole('ADMIN')")
    public String endpoint() {
        return "This message is protected by the resource server !!!!";
    }

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

This code works very fine if I call token and protected resources. The same I wanted to create it through the client UI. I created below client project.
WebSecurityConfig.java
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .anyRequest()
            .authenticated()
            .and()
            .formLogin()
            .and()
            .httpBasic();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();

        // @formatter:off
        auth
            .inMemoryAuthentication()
            .withUser("user1").password(encoder.encode("password1")).roles("USER")
            .and()
            .withUser("john").password(encoder.encode("password1")).roles("USER", "ADMIN")
            .and()
            .withUser("sally").password(encoder.encode("password1")).roles("ADMIN");

        auth.eraseCredentials(false);
        // @formatter:on
    }
}

SpringMicroservicesOauthClientApplication.java
@SpringBootApplication
@EnableOAuth2Client
@RestController
public class SpringMicroservicesOauthClientApplication {

    @Autowired
    private OAuth2RestTemplate restTemplate;

    @Bean
    public OAuth2RestTemplate restTemplate() {
        return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext());
    }

    @Bean
    public OAuth2ProtectedResourceDetails resource() {
        ResourceOwnerPasswordResourceDetails details = new ResourceOwnerPasswordResourceDetails();
        details.setAccessTokenUri("http://localhost:9090/oauth/token");
        details.setClientId("webapp");
        details.setClientSecret("websecret");
        details.setGrantType("password");
        return details;
    }

    @RequestMapping("/execute")
    public String execute(Principal principal) throws URISyntaxException {
        User user = (User) ((Authentication) principal).getPrincipal();
        URI uri = new URI("http://localhost:9090/resource/endpoint");
        RequestEntity<String> request = new RequestEntity<>(HttpMethod.POST, uri);

        AccessTokenRequest accessTokenRequest = this.restTemplate.getOAuth2ClientContext().getAccessTokenRequest();
        accessTokenRequest.set("username", user.getUsername());
        accessTokenRequest.set("password", user.getPassword());

        return restTemplate.exchange(request, String.class).getBody();
    }

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

EDIT-1: - Through Postman code works fine. Here is curl command from postman.
But when I call the code from the Client code it gives me error.

curl -X POST 'http://localhost:9090/oauth/token?grant_type=password&username=user1&password=password1' -H 'authorization: Basic d2ViYXBwOndlYnNlY3JldA==' -H 'cache-control: no-cache' -H 'postman-token: 0b0547b9-223d-0583-3e11-abe45cfc12af'

{
    "access_token": "99693b5a-6cfb-4049-8641-2f2a0cccb224",
    "token_type": "bearer",
    "refresh_token": "25b33fdf-83ad-43a8-afa9-e4d457f02244",
    "expires_in": 1799,
    "scope": "read,write,trust"
}

A: I cannot see your Postman and your client's request information. If you can make request by Postman, then your back-end code should be fine.
Normally, "Bad credentials" exception happens when the username or password is incorrect. I suggest you double check the client's request headers and parameters comparing with the Postman.
From your edit, those two requests are not calling same API. The curl command requested access token, but your client requested "execute" API.
However, I found you did not add "Authorization" header in your client request. Your client should add this header to authorize itself. Authorization header value should be:
Bearer access_token (replace access_token with the one you get from oauth/token request)


text:
Q: Domain and Range with functions in brackets For the function
$f(x, y) = \sqrt{(x-1)^2+(y-2)^2 -1}$
Would it be sufficient to write the domain as
$(x-1)^2 + (y-2)^2 ≤ 1$
or is that too vague? Then, the range would be $z ≥ 0$ but how could that be expressed in terms of $x$ if the value has to be greater than or equal to $1$?

A: Your idea is pretty fine, but be careful about the direction of the inequality. If you have $\sqrt{z}$, then you want $z \ge 0$, not $z \le 0$. Since $f : \Bbb R^2 \to \Bbb R$, you could write the domain by
$$\mathrm{dom}(f) = \left\{ (x,y) \in \Bbb R^2 \; \middle| (x-1)^2 + (y-2)^2 \ge 1 \right\}$$
as a result. The range of $f$ could simply be given by $\Bbb R_{\ge 0}$ if you want a symbol for it. You just want the points it is possible for $f$ to map to, regardless of the constraints that need be placed on $x,y$ in order for that to happen.
For instance, you could have $x=y-1$. Then the radicand is given by
$$(x-1)^2 + (y-2)^2 - 1 \longrightarrow 2(y-2)^2 - 1$$
Clearly the function $g(y) = \sqrt{2(y-2)^2 - 1}$, for wherever $y$ ensures $g(y)$ is defined, has range $\Bbb R_{\ge 0}$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Open Additional Device Properties via Commandline In Windows 10 under Settings > System > Sound > Device Properties there is a link to a related setting  called "Additional device properties", where you have the Tabs General/Listen/Levels/Advanced.
I would like to directly display the advanced device properties for a given DeviceID. Any ideas how to execute it via commandline?
All I found so far is this command, which displays the properties of the device manager, but that's just quite not what I want. Since the settings is reachable from the Sound settings, I assume it has somehow to be related to mmsys.cpl?
rundll32.exe devmgr.dll,DeviceProperties_RunDLL /DeviceID XXXXXXXXXXXX

A: I traced the dialog window, and its invocation is by the command:
"C:\WINDOWS\System32\rundll32.exe" C:\WINDOWS\System32\shell32.dll,Control_RunDLL C:\WINDOWS\System32\mmsys.cpl ms-mmsys:,{0.0.0.00000000}.{71313e65-fd54-4bcd-ba60-916aa5af22f4},general

I got to this dialog via
Settings > System > Sound > Device properties >
Additional device properties.


text:
Q: I'm trying to display MySQL queries in a web browser using Python I am trying to run MySQL commands through Python source code and have it display in my web browser.
When I compile the code in an editor (Komodo Edit) it complies and returns the expected set of rows, but when I try to view in a browser the source code is displayed, not the query result I seek...
Here's what I have...
import mysql.connector
conn = None

try:
    conn = mysql.connector.Connect(host="localhost", user="jump", password="secret")
    print('Connected to MySQL!')
except Exception as ex:
    print('cannot connect to MySQL : exception : ' + str(ex))

cursor = conn.cursor()
cursor.close()
print('terminating connection with MySQL')
conn.close()

...I'm pretty sure the source is good, and that somewhere I missed a configuration step or some such.
   I can get my command prompt to open the source file and display the query results, so I've got a connection between Python and MySQL server, which I verified through the MySQL workbench also.
Thanks for any help y'all can give!
-M


text:
Q: Access Nested Models from function Angular I'm trying to build searchFn in my ng-select based on this example
https://stackblitz.com/edit/angular-bz6drh
Component.ts
  customSearchFn(term: string, item: Person) {
      term = term.toLowerCase();
      return item.name.toLowerCase().indexOf(term) > -1 || item.department.name.toLowerCase() === term;
  }

Model.ts
export interface Person {
    id: string;
    name: string;
    description: string;
    department: Array<Department>;
}

export interface Department {
    id: string;
    name: string;
    description: string;
}

As you can see in my component I'm trying to access item.department.name which is not working.
Its showing Property 'name' does not exist on type 'Department[]'.

A: After a discussion with the OP, it turns out that the model was incorrect. This is the correct model:
export interface Person {
    id: string;
    name: string;
    description: string;
    department: Department;
}


text:
Q: rename all files after extension Is it possible to write a script to rename all files after the extension?
Example in the folder, there are :
hello.txt-123ahr
bye.txt-56athe
test.txt-98hg12

I want the output:
hello.txt
bye.txt
test.txt

A: If you just want to remove everything from the dash forwards, you can use Parameter expansion:
#!/bin/bash
for file in *.txt-* ; do
    mv "$file" "${file%-*}"
done

Where ${file%-*} means "remove from $file everytning from the last dash". If you want to start from the first dash, use %%.
Note that you might overwrite some files if their leading parts are equivalent, e.g. hello.txt-123abc and hello.txt-456xyz.


text:
Q: Skype Button: How to prevent vertical space I just started learning HTML, CSS and JS. I am trying to add Skype button to my web, but it creates blank lines above and below. How do I remove those blank lines and make Skype button appear inline with text coded before Skype button code? (Sorry, I am very new to stackoverflow, so not able to post image of my result.
This is the sample code I am trying with.
<link rel="stylesheet" type="text/css" href="960-Grid-System-master/code/css/960_12_col.css" />

    Contact XXXXXXX XXXXX

footer

A: The skype button api creates a paragraph

...

Which causes your spacing issue. To get around this you can insert some js like this

To your call to add your text to the generated paragraph.


text:
Q: GUI-button to exit loop, Move-Item Job I'm struggling to break the while loop when the "Off" button is being pressed.
Instead, after starting the moving process, I am running into an endless loop.
$objForm.Controls.Add($StartButton)
$objForm.Controls.Add($OffButton)

$OffButton = New-Object System.Windows.Forms.Button
$OffButton.Location = New-Object System.Drawing.Size(340,105)
$OffButton.Size = New-Object System.Drawing.Size(90,28)
$OffButton.Text = 'Off'
$OffButton.Name = 'Off'
$OffButton.Font = [System.Drawing.Font]::New("Microsoft Sans Serif", 11)
$OffButton.Add_Click({$script:AktiveLoop = $False})
$objForm.Controls.Add($OffButton)

$StartButton = New-Object System.Windows.Forms.Button
$StartButton.Location = New-Object System.Drawing.Size(340,135)
$StartButton.Size = New-Object System.Drawing.Size(90,28)
$StartButton.Text = 'Start'
$StartButton.Name = 'Start'
$StartButton.Font = [System.Drawing.Font]::New("Microsoft Sans Serif", 11)
$StartButton.Add_Click({
    $script:AktiveLoop = $true

    while ($script:AktiveLoop -eq $true) {
        Move-Item $source -Destination $destination
        Start-Sleep -Seconds 1.0

        if ($script:AktiveLoop = $False) {
            break
        }
    }
})
[void] $objForm.ShowDialog()

A: Although there is discussion about using DoEvents, the fact that your button 'Off' click does not seem to be fired has to do with the Start-Sleep you are putting in the loop.
Start-Sleep makes the form unresponsive. If you use [System.Windows.Forms.Application]::DoEvents() instead the button click events are processed.
Also, from a user point of view, it is best to disable the 'Off 'button when the form is first drawn and toggle the enabled startus of both buttons inside te Click events.
For this I have made some changes to the code given in the example:
Add-Type -AssemblyName System.Windows.Forms

$objForm   = New-Object System.Windows.Forms.Form

$OffButton = New-Object System.Windows.Forms.Button
$OffButton.Location = New-Object System.Drawing.Size(340,105)
$OffButton.Size = New-Object System.Drawing.Size(90,28)
$OffButton.Text = 'Off'
$OffButton.Name = 'Off'
$OffButton.Font = [System.Drawing.Font]::New("Microsoft Sans Serif", 11)
# initially disable the 'Off' button
$OffButton.Enabled   = $false
$OffButton.Add_Click({
    $script:AktiveLoop   = $false
    $OffButton.Enabled   = $false
    $StartButton.Enabled = $true

})
$objForm.Controls.Add($OffButton)

$StartButton = New-Object System.Windows.Forms.Button
$StartButton.Location = New-Object System.Drawing.Size(340,135)
$StartButton.Size = New-Object System.Drawing.Size(90,28)
$StartButton.Text = 'Start'
$StartButton.Name = 'Start'
$StartButton.Font = [System.Drawing.Font]::New("Microsoft Sans Serif", 11)
# initially enable the 'Off' button
$StartButton.Enabled = $true
$StartButton.Add_Click({
    # switch the buttons Enabled status so the user can not click the same button twice
    $OffButton.Enabled   = $true
    $StartButton.Enabled = $false
    $script:AktiveLoop   = $true

    while ($script:AktiveLoop) {
        # perform some action here. (added -WhatIf here for testing)
        Move-Item $source -Destination $destination -WhatIf

        # Start-Sleep makes the form unresponsive, so don't use that.

        # DoEvents() suspends the current thread and processes
        # window messages like a click on the 'Off' button.
        [System.Windows.Forms.Application]::DoEvents()
    }
})
$objForm.Controls.Add($StartButton)

[void] $objForm.ShowDialog()
$objForm.Dispose()

p.s. You added the buttons to the form even before you have defined them, so I removed that.
Hope this helps


text:
Q: Iterate a list and add values to a dictionary I am trying to create a dictionary where values are obtained from iterating a list. The keys are in the tuple format (i,j).
e.g. if i = 3, j = 3, the keys are
(1,1), (1,2), (1,3), (2,1), (2,2), (2,3), (3,1), (3,2), (3,3).
If my list is as follows,
lst = list(range(1, 10))

How do I obtain a dictionary like this?
{(0, 0): 1, (0, 1): 2, (0, 2): 3, (1, 0): 4, (1, 1): 5, (1, 2): 6, (2, 0): 7, (2, 1): 8, (2, 2): 9}
I have tried:
dict = {(i,j): d for d in lst for i in range(1, i+1) for j in range(1, j+1)}

but the values of my dictionary are strictly the last value of lst. This is my output instead:
>>> {(0, 0): 9, (0, 1): 9, (0, 2): 9, (1, 0): 9, (1, 1): 9, (1, 2): 9, (2, 0): 9, (2, 1): 9, (2, 2): 9}

A: If you already have your list of tuples, list_of_tuples, then this would work:
d = {L:i for i,L in enumerate(list_of_tuples)}

or if a separate list of length len(list_of_tuples) exists, called lst, then you could do
d = {L:lst[i] for i,L in enumerate(list_of_tuples)}


text:
Q: How to initialise structure with a field pointing to another field? Given this struct :
typedef struct test {
  char field1[20];
  char *field2;
} test_s

How can initialize this kind of structure with a designated initializer, knowing that I want field2 to point to field1 ?
test_s test = {.field1[0] = '\0', .field2 = .field1};

doesn't work.

A: In case of a single-item declaration you can use the name of the variable being declared, because the compiler can take address at any time during initialization:
test_s test = {.field1[0] = '\0', .field2 = test.field1};

Demo.


text:
Q: PHP understanding a small snippet code for extracting checkbox values I have a snippet of PHP code, it works but I was curious to know why.
Green: <input type="checkbox" name="color[]" value="green" />
Black: <input type="checkbox" name="color[]" value="black" />
White: <input type="checkbox" name="color[]" value="white" />
Blue:  <input type="checkbox" name="color[]" value="blue"  />
Red:   <input type="checkbox" name="color[]" value="red"   />

then here is what I don't get for this PHP code below, how is $colors an array, I thought you have to at least have $colors[] = $_POST['color'].
if (isset($_POST['color'])) {
  $colors = $_POST['color'];
}
echo $colors[0];

Thanks for helping me better understand this.

A: You don't need to explicitly add [] in PHP. Notice that you don't even need to define the type! This is PHP :)
$_POST['color'] is an array, so $colors will also be!
Read: http://www.html-form-guide.com/php-form/php-form-checkbox.html
Edit
In PHP, if you write $colors[] = $var, you are actually adding $var to the end of that array. If the array is empty, $colors[0] == $var.
$colors = $_POST['color']; // $colors receives the array
$colors[] = $_POST['color']; // $colors[0] receives the array, if $colors was empty

More info: http://php.net/manual/en/language.types.array.php#language.types.array.syntax.modifying

A: In HTML, every element with [] in its name is gonna be treated as an array.
Useful in cases like:
Choose your interests<br/>
<input type='checkbox' name='interests[]' value='Fashion'> Fashion
<input type='checkbox' name='interests[]' value='Cars'> Cars
<input type='checkbox' name='interests[]' value='Health'> Health
<input type='checkbox' name='interests[]' value='Programming'> Programming

Now you will acces them as an array in php:
$_POST['interests'][0] //-> Fashion


text:
Q: Cannot access Transaction in method I've created an implicit transaction like so:
Using ts As New TransactionScope(TransactionScopeOption.Required, New TimeSpan(1, 0, 0, 0))

MethodA()
ts.Complete()

End Using

MethodA() in turn calls a number of methods which successfully enlist within the ambient transaction and I can see it:

however one method (which is 4 deep on the call stack from the creation of TransactionScope above) it seems we no longer have access to the ambient transaction:

It was my belief that this will be available anywhere lower on the stack within the transaction, and is probably is the reason why code within this method has no access to the data within this transaction.
Any ideas why the ambient transaction isn't available?

A: if Transaction isn't declared, it sounds like that file simply lacks the using directive that would bring it into scope. Try setting the watch against
System.Transactions.Trasaction.Current.TransactionTraceId.TransactionIdentifier

instead, as that will work with or without the using directive.
If it were the case that the ambient transaction was not available, then Transaction would still be fine, but Transaction.Current would be null. A common reason for this is anything that switches thread, for example async code. Knowing what flows over the execution-context is tricky.


text:
Q: PostgreSQL CURSOR with "order by" clause Let's suppose there is a Query called A and it takes 2sec.
SELECT ... FROM ... ORDER BY "users_device"."id"  # Query A
# It contains join clause.
# It takes 2sec

However, When I run A with declaring CURSOR, it takes 8sec.
DECLARE "cursor" NO SCROLL CURSOR WITH HOLD FOR SELECT ... FROM ... ORDER BY "users_device"."id"
# It takes 8sec

I have tried to compare Query Plan between them and then I found A with CURSOR seems to try to avoid sorting operation.
The below is actual query plan.
# A without CURSOR
+--------------------------------------------------------------------------------------------------------------------------------------------------------------
| QUERY PLAN
|--------------------------------------------------------------------------------------------------------------------------------------------------------------
| Sort  (cost=433944.70..434050.91 rows=42485 width=147) (actual time=2664.192..2669.168 rows=35949 loops=1)
|   Sort Key: users_device.id DESC
|   Sort Method: external merge  Disk: 5536kB
|   ->  Nested Loop  (cost=239036.59..427483.24 rows=42485 width=147) (actual time=1956.219..2631.077 rows=35949 loops=1)
|         ->  Nested Loop  (cost=239036.16..404723.17 rows=43069 width=151) (actual time=1956.209..2502.529 rows=39556 loops=1)
|               ->  Hash Join  (cost=239035.73..367340.95 rows=51402 width=12) (actual time=1956.192..2249.085 rows=63844 loops=1)
|                     Hash Cond: (users_serviceuser_favorites.from_serviceuser_id = users_serviceuser.id)
|                     ->  Bitmap Heap Scan on users_serviceuser_favorites  (cost=1988.30..119110.71 rows=72756 width=4) (actual time=22.182..74.569 rows=66736 lo
|                           Recheck Cond: (to_serviceuser_id = 773433)
|                           Heap Blocks: exact=43597
|                           ->  Bitmap Index Scan on users_serviceuser_favorites_011e5c87  (cost=0.00..1970.11 rows=72756 width=0) (actual time=13.108..13.108 ro
|                                 Index Cond: (to_serviceuser_id = 773433)
|                     ->  Hash  (cost=196162.09..196162.09 rows=2492028 width=8) (actual time=1932.025..1932.025 rows=2503575 loops=1)
|                           Buckets: 131072  Batches: 64  Memory Usage: 2564kB
|                           ->  Seq Scan on users_serviceuser  (cost=0.00..196162.09 rows=2492028 width=8) (actual time=0.184..1517.721 rows=2503575 loops=1)
|                                 Filter: (status = 1)
|                                 Rows Removed by Filter: 1016611
|               ->  Index Scan using users_device_e8701ad4 on users_device  (cost=0.43..0.72 rows=1 width=151) (actual time=0.003..0.004 rows=1 loops=63844)
|                     Index Cond: (user_id = users_serviceuser.id)
|                     Filter: (status = 0)
|                     Rows Removed by Filter: 1
|         ->  Index Scan using users_pushsetting_pkey on users_pushsetting  (cost=0.43..0.52 rows=1 width=4) (actual time=0.003..0.003 rows=1 loops=39556)
|               Index Cond: (id = users_serviceuser.push_settings_id)
|               Filter: live
|               Rows Removed by Filter: 0
| Planning time: 2.537 ms
| Execution time: 2671.895 ms
+--------------------------------------------------------------------------------------------------------------------------------------------------------------

# A with CURSOR (You can see there is no another sorting operation
+--------------------------------------------------------------------------------------------------------------------------------------------------------------
| QUERY PLAN
|--------------------------------------------------------------------------------------------------------------------------------------------------------------
| Nested Loop  (cost=1.85..3204962.54 rows=42484 width=147) (actual time=0.324..8345.880 rows=35945 loops=1)
|   ->  Nested Loop  (cost=1.42..3182203.00 rows=43068 width=151) (actual time=0.314..8206.619 rows=39552 loops=1)
|         ->  Nested Loop  (cost=0.99..3124567.60 rows=84403 width=155) (actual time=0.302..8035.916 rows=43584 loops=1)
|               ->  Index Scan Backward using users_device_pkey on users_device  (cost=0.43..423536.24 rows=2955421 width=151) (actual time=0.017..2659.130 row
|                     Filter: (status = 0)
|                     Rows Removed by Filter: 692112
|               ->  Index Only Scan using users_serviceuser_favorites_from_serviceuser_id_ac0a7b1d_uniq on users_serviceuser_favorites  (cost=0.56..0.89 rows=2 width
|                     Index Cond: ((from_serviceuser_id = users_device.user_id) AND (to_serviceuser_id = 773433))
|                     Heap Fetches: 38956
|         ->  Index Scan using users_serviceuser_pkey on users_serviceuser  (cost=0.43..0.67 rows=1 width=8) (actual time=0.003..0.004 rows=1 loops=43584)
|               Index Cond: (id = users_device.user_id)
|               Filter: (status = 1)
|               Rows Removed by Filter: 0
|   ->  Index Scan using users_pushsetting_pkey on users_pushsetting  (cost=0.43..0.52 rows=1 width=4) (actual time=0.003..0.003 rows=1 loops=39552)
|         Index Cond: (id = users_serviceuser.push_settings_id)
|         Filter: live
|         Rows Removed by Filter: 0
| Planning time: 4.056 ms
| Execution time: 8348.095 ms
+--------------------------------------------------------------------------------------------------------------------------------------------------------------

When declaring CURSOR, Optimizer chooses "users_device"."id"(users_device_pkey) index scan first so that all joined table is sorted by "users_device"."id" without another sorting operation. As the result, it doesn't need to do order by "users_device"."id" later even though this choice results in poor Query performance.
Why does optimizer choose a different plan by CURSOR?
Does it avoid sorting?
if so, why?

A: I can't find this in documentation but I'd speculate, that when you use cursor the database looks more at estimated start-up cost (the time to the first row of output) than estimated total cost (the time to the last row of output).
In your example the slow plan is estimated to output the first row in 1.85 cost-units, and the fast plan in 433944.70 cost-units. So it looks like the database prefers the slow plan when you used cursor to be able to provide partial results as soon as possible.
This seems reasonable - you used a cursor instead of an ordinary query, probably because you prefer to start working on your data as soon as possible.
I think you can make it work fast and still retrieve data in chunks with fetch by explicitly creating the temporary table:
create temporary table t as select ... /* skip order by */;
declare c cursor with hold for select * from t order by id;

As @mastaBlasta pointed out in a comment there's an option that controls for how much is first result preferred over a whole result for cursors: cursor_tuple_fraction.


text:
Q: Setting image resourse by obtaining tag position for an imageview android I am making use of recycler view. I have a layout that is highlighted in light red,this layout is included for each item in the recycler view. The light red layout is placed over the background image. I am using setTag method to identify the clicks of the buttons in red layout. That is working properly when i click i get the position. The problem is i want to change the image at specific position.
For example : Consider the heart button. I have set a tag on it like this.
heartButton = findViewById(id);
heartButton.setTag(position);
now i get the position by using the getTag method. But now i want to change the image of the heartButton at the a specific position. Is there something like
heartButton.getTag(position).setImageResouce(drawable);
If not how do i do this then.

A: use setBackgroundResource(R.drawable.XXX)
http://developer.android.com/reference/android/view/View.html#setBackgroundResource(int)

A: Proper way to do this is,
You have to keep the state of the heart button stored in the model(POJO) which is passed to custom adapter.
e.g.
class ModelListItem{
public static final int HEART=1,BROKEN_HEART=2;

int heartButtonState;

}

Now in onClick() of heart button, get that object from adapter using position,cosidering you have already figured it out on how to preserve position from heart button
ModelListItem item = (ModelListItem)adapter.getItem(position)

Change the state of heart button;
item.setHeartButtonState(ModelListItem.BROKEN_HEART);
   adapter.notifyDatasetChanged();

You already know below explaination but just in case
To work this properly,in your getView methode of adapter you need to put the check on heartButtonState(); and use appropriate image resource.
getView(BOILERPLATE){
 BOILERPLATE

 switch(item.getheartButtonState()){
 case ModelItemList.HEART:
   heartbutton.setImageResource(heart_image);
 break;
 case ModelItemList.BROKEN_HEART:
   heartbutton.setImageResource(broken_heart_image);
 break;
 }

A: I made a custom click listener and updated the like in the setter getter.But this works only when the view has been moved out of the view (i think it is the scrapeview)
The Setter Getter Class
public class DemoData {

    int background;
    boolean liked;

    public DemoData(int background) {
        this.background = background;
    }

    public int getBackground() {
        return background;
    }

//    public void setBackground(int background) {
//        this.background = background;
//    }

    public boolean isLiked() {
        return liked;
    }

    public void setLiked(boolean liked) {
        this.liked = liked;
    }
}

The onBindViewHolder function of the recycler view
@Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        background = (ImageView) holder.view.findViewById(R.id.image);
        layout = (LinearLayout) holder.view.findViewById(R.id.layout);

        delete = (ImageView) layout.findViewById(R.id.delete);
        lock = (ImageView) layout.findViewById(R.id.lock);

        delete.setTag("delete_"+position);
        lock.setTag("lock_"+position);

        if(Constants.demoDatas.get(position).isLiked()){
            delete.setImageResource(R.drawable.ic_launcher);
        }
        else{
            delete.setImageResource(android.R.drawable.ic_delete);
        }

        delete.setOnClickListener(new CustomClickListener(position));
        lock.setOnClickListener(new CustomClickListener(position));

    }

The custom click listener is as below
public class CustomClickListener implements View.OnClickListener {

    int position;

    public CustomClickListener(int position) {

        this.position = position;
    }

    @Override
    public void onClick(View v) {

        String tag = (String) v.getTag();
        String identifier[] = tag.split("_");

        // this line saves my state in the Setter Getter Class
        Constants.demoDatas.get(position).setLiked(true);

    }
}


text:
Q: How to configure Java Kerberos in sqljdbc4.jar Could anyone explain me ho to configure Java Kerberos by using sqljdbc4.jar.
Because I'm getting error second time i run my application, error displayed com.microsoft.sqlserver.jdbc.SQLServerException: Integrated authentication failed.
(NOTE- Error Displaying occurs only For servlet Projects. i'm using apache tomcat)
There is tutorial here about Kerberos. But i don't understand how to include it to my cording.
    public Connection Get_connection(PrintWriter out)
{
try
        {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            String url = "jdbc:sqlserver://localhost:1433; databaseName = Colombo_Health; integratedSecurity=true; authenticationScheme=JavaKerberos";
            con = DriverManager.getConnection(url,"","");
            out.println("Connection Established");
        }
        catch (ClassNotFoundException e)
        {

         out.println("Class not Found       " +e.toString());
        }
        catch (Exception e)
        {
         out.println("Driver not Found    "+e.toString());
        }

            return con;

}

*

*I'm on Windows 10 with SQL sever 2014.

*I have copied sqljdbc_auth.dll to system 32

A: Assuming from the amount of information you have provided, I think the error lies in not setting your connection's properties. Add con.setServerName(value) and con.setDatabaseName(value)  along with these Other Properties that may apply

A: Looks like you're using the wrong authenticationScheme. By specifying JavaKerberos you tell the client to use the Java implementation of Kerberos. If you want to use sqljdbc_auth.dll for authentication, you should be using NativeAuthentication as your authentication scheme.


text:
Q: D1's auto and scope difference in memory allocation D's docs saying that when you use scope for local variables, then they will be allocated on stack (even if you're allocating class instance). But what about auto keyword? Does it guarantee that the instance will be allocated on stack?

*

*void foo() { auto instance = new MyClass();}

*void foo() { scope instance = new MyClass();}
So can I suggest that this two statements are equal (in terms of allocation)?

A: No, auto only infers the type.
There's no point in using auto if you want it to be allocated on the stack; that's what scope is (was) for.
They've brilliantly (read: not so much) decided to remove scope, delete, etc. from the language, so it will probably allocate on the heap anyway. Your best bet is to use the function called scoped in one of the modules, to allocate on the stack.

A: To answer the second question: in D1 those two statements are not equal. First one allocates on the heap, second one is (supposed) to allocate on the stack.


text:
Q: rewrite all urls that start with.., I want to rewrite the following url:
 http://localhost/albums/album_name/22

to:
http://localhost/album.php?id=22

I want only urls starting with /albums/ to be rewritten. I tried this, but it doesn't work.
RewriteRule /albums/^[^/]+/([\d]+)$ /album.php?gallery_id=$1 [L]

A: You have a ^ that is in the wrong location (how did I miss that???)
RewriteRule ^albums/[^/]+/([\d]+)$ /album.php?gallery_id=$1 [L]


text:
Q: Is there a point in accepting a surrender in FTL? In FTL if I damage an enemy ship there is sometimes an option to accept their surrender. Is there any point in this? I always get more scrap if I either kill their crew or destroy their ship.

A: The main point is that the fight is over immediately. If your ship is in bad shape, and the enemy still has some weapon systems up, that can be very desirable.
You also tend to get more fuel from accepting a surrender; fuel is frequently destroyed along with the ship.
Lastly, there are a few fights where accepting surrender carries additional benefits. For example, slaver ships will often give you a slave as a new crew member, which can't happen if you blow up the ship. Similarly, there is a quest where your goal is to discourage some pirates; if you blow them up, the quest giver won't give you any additional reward. In these situations, you'll know ahead of time whether the surrender carries these extra benefits, so you don't have to blindly guess.


text:
Q: Could Jack Sparrow escape from Davy Jones' Locker on his own? Was it possible for Jack Sparrow to escape from Davy Jones' Locker if the others had not come for his rescue. This came to my mind as he was able to come to the sea on his own.

A: It's unclear, really.
Firstly, Jack Sparrow[1] had earned his place in The Locker, after being eaten by the Kraken, and Damned by Davey Jones. He had been placed there specifically, by Davey's/The Kraken's "magics". When the crew came to rescue him, they were mortals coming to rescue a damned soul, and as is the case in most situations with entrance through a back door to the afterlife (or similar places), throwing living people into a place where there should be none, kinda messes things up a bit. The crew (i.e. the living) had the ability to leave of their own accord, through the backdoor they opened to get in, and their arrival could have potentially started the ball rolling for Jack[2] (emphasis mine):

The Locker was used by Davy Jones to relegate souls that either refused to join his crew or Jones himself deemed unfit to serve aboard the Flying Dutchman. The interior of the Locker represented a soul's worst fear, so its appearance was believed to be perceived differently by everyone who entered it.
For Jack Sparrow, the Locker was a vast expanse of hot sand, on which he and his ship, the Black Pearl, were marooned with no hope of reaching the sea. Here, Jack was confronted by several hallucinations, each one presenting various aspects of his persona, created to send him mad over time. This punishment played on Sparrow's love of the sea (in that he equated it with freedom), along with his pride in being "the one and only" Captain Jack Sparrow.

From memory, the crabs appeared only after the crew had managed to make their way towards the entrance into the Locker; perhaps as they entered through the portal. (I personally believe these two events are linked).
However... he was not the only one to escape
There are two other pirates within the PotC universe have also escaped: Black Bart and Jocard, whom both appear to have been freed in some way, due to Jack's intervention with them in one way or another. There is no evidence or understanding as to how either of them escaped, but it was only after they ran into Captain Jack:

Jack Sparrow later encountered Black Bart in Davy Jones' Locker, after the former was taken there by the Kraken. [...] The two subsequently fought, and Roberts was defeated by Sparrow. After being stabbed by Sparrow, Roberts gave a maniacal laugh and then, simply disappeared, leaving only his boots and sword behind.

Jocard lost all hope of being free, until another imprisoned Pirate Lord, Jack Sparrow, tracked Jocard down and dueled Black Bart. Sparrow won the duel, and freed Jocard from his cell. It is unknown how Jocard escaped the Locker, as he was not onboard the Black Pearl when it escaped, and neither did he have the mysterious navigational charts of Sao Feng.

The problem here is that there is a lot of magic involved in this whole adventure. Mythical monsters and gods and parallel dimensions, as well as many hints that Captain Jack Sparrow may certainly be more attuned to all of it than most. Most are in it for their own glory, whereas Jack simply wants to enjoy the freedom of sailing the high seas; a master of the ocean, and second only to the power of the sea.

EDIT: MissouriSpartan raised a good point about the crabs being a connection point to Calypso, which actually explains the crabs in the Locker (emphasis mine):

On the quest for freeing Jack Sparrow from the Locker, the crew led by Barbossa captained the Hai Peng into World's End. They landed in the Locker, where Jack Sparrow noticed that the Pearl was being dragged across the sand by crabs. The ship reached the crew with the help of the crabs that were actually under the control of Calypso. After escaping the Locker, the Black Pearl went on its way to meet with the Brethren Court.

Source
This is how Jack arrived at the ocean, with the Black Pearl - it was specifically Calypso (i.e. Tia Dalma) that brought Jack to the ocean, to meet the crew.

[1] Captain... Captain Jack Sparrow.
[2] We're still talking about Captain Jack here, not the monkey.

A: No, he couldn't. Let's take a look at what was needed to actually escape the locker
A Ship (or boat) in the water
Yes Jack had the Black Pearl but he was neither near water, nor had the crew to actually operate it (remember those clones of him weren't real). In order to get out of the Locker he would need to get it in the water and successfully turn it upside down which leads into the next point
A crew
In order to turn the ship upside down he would need multiple people, he can't turn the ship upside down with only himself.
The knowledge to get out
The only reason any of them escape The Locker is because Jack successfully figures out the riddle "Up is Down" had he not had the map and had he not looked at it, they'd still be stuck in there
To be in the water
Let's also remember that, again, the only reason any of them get out is because Tia Dalma successfully used her crabs to get the boat from on the sand to in the ocean. Had they all arrived there, with the map, with the ship still miles or km away from the ocean, they'd still be stuck there.
Since Jack had none of that we can conclude that no, it was impossible for him to escape The Locker alone.


text:
Q: How to remove duplicate records from Huge csv file and store it into Database in Mulesoft using Anypoint Studio Suppose I have a huge CSV files say it contains 10000 records and it has 3 fields say ID, Name and Age and it also has some duplicate records. Here I want to remove duplicate records based on ID field and store the all the unique records in Database.
How should I achieve it in Mulesoft using Anypoint Studio?

A: You can use the dataweave to identify unique records. And then insert intoDB.
Flow will be like File Connector(Reading File) >> Dataweave(identify unique records) >> DB connector(DB insert).
Please refer this for more details.
https://docs.mulesoft.com/mule-user-guide/v/3.8/dataweave-operators#distinct-by
Hope this helps.

A: You can try using the distinct option in dataweave and create an output as csv format file itself.
Check the link below for distinct operator.
https://docs.mulesoft.com/mule-user-guide/v/3.9/dataweave-operators#distinct-by


text:
Q: Манипуляции с макросами Есть вот такой простой блок кода, который печатает b, я что-то упускаю из вида, почему так происходит?
#include <iostream>

constexpr int STACKUSE = 1;

int main() {

#if STACKUSE == 1
        std::cout << "a" << std::endl;
#else
        std::cout << "b" << std::endl;
#endif

   return 0;
}

A: Ваш код не работает по причине того, что препроцессор выполняет директивы ещё до всех переменных и исполнения кода. Ваш код компилируется только потому, что по умолчанию у препроцессора все не определённые макросы равны 0 (Не знаю как на других компиляторах, но у меня и у автора, судя по всему, это так). Препроцессор не видит никаких STACKUSE. Ему нужны макросы: #define STACKUSE 1

A: Потому что препроцессор в переменных не разбирается.
Хотите получить a? Работайте через препроцессор...
#define STACKUSE  1
int main() {
#if STACKUSE == 1
        std::cout << "a" << std::endl;
#else
        std::cout << "b" << std::endl;
#endif

Если же вы хотите добиться того же с помощью компилятора, то писать надо так:
constexpr int STACKUSE = 1;
int main() {
    if constexpr (STACKUSE == 1)
        std::cout << "a" << std::endl;
    else
        std::cout << "b" << std::endl;


text:
Q: c# accessing variables defined in different .cs files It may be the basic of c#.But, I can't find out a solution..
I have 3 classes (let it be 1.cs,2.cs,3.cs) in my application. I want to use in 3.cs class, a variable or string  that is defined in 2.cs. How can it be done?

A: 1) Declare the string or variable you want to access as PUBLIC in 2.cs
2) Create an object of class 2.cs in 3.cs
3) Access the variable using this object.

A: if is is an not static class then u can use it like that
 2 csFileNo2=new 2();

 csFileNo2.YourStringVar;

or if this is an static class like
class static 2
{
  public static csFileNo2="Your string";
}

then use it like that
 2.csFileNo2;

remember that its just an example . numbers are not allow as first char of class or function name .
best of luck

A: There are many different ways to access variables in other classes, the easiest way to this is by using Inheritance, for instance:
public class C1 {
   public static int x;
}

public class C2 : C1 {
   //Now this class can access the x value from the C1 class
}

another way to do this without inheritence would be to access the variable this way  :
C1.x

You can read about inheritance in Here


text:
Q: Can I use the Ubuntu SDK Preview in Linux Mint? Can I use Linux Mint to develop applications for Ubuntu Touch with the Ubuntu SDK preview?

A: Ubuntu sdk is open source , and ubuntu and mint uses same package management system . So therectically it is possible to install ubuntu sdk in linux mint . But it is not officially supported


text:
Q: Lookup field value from VF page not been assigned to Visual Flow variable I have created an VF page and embedded a visual workflow in it. VF page has an lookup field, but I am having problem in assigning value to the flow variable through this.I have to click on save button and pass the arguments through url to same page then assign the values in constructor.
Can this be done without clicking on save button?
For lookup I have tried using Dynamic choice element but the problem is that it displays the result on next screen once you enter the String to be searched
The visual force fields and flow fields appear separately.Is there any way I can Display it in Same page?
    Here is the sample code-

<apex:page controller="AmendmentCreationWizardController" title="New Contract Amendment">

<apex:sectionHeader title="New Contract Amendment"/>

    <apex:form >

         <apex:outputLabel value="Contract Emailed To" style="font-weight:bold;">    </apex:outputLabel>
          <apex:inputField id="Account" value="{!Contact.ReportsToId}"  />
          <apex:commandButton value="Save" action="{!getContactDetails}"/>

      </apex:form>
  <flow:interview name="Contract_Amendment_Creation_Wizard" interview="{!myFlow}" buttonLocation="bottom" finishLocation="{!newPage}">
        <apex:param name="ContactId" value="{!selectedContactId}"/>
        <apex:param name="contract_Id" value="{!selectedContractId}"/>
    </flow:interview>

</apex:page>

-----Controller----
public with sharing class AmendmentCreationWizardController{

    public PageReference getNewPage() {
    if(myFlow!=null){
        if(myFlow.AmendmentType =='Booth Change Amendment'){
           return new PageReference('/apex/BoothChangeAmendmentWizard?id='+myFlow.contract_Id+'&AmdId='+myFlow.amendment_Id);
         system.debug('ContractId->>'+myFlow.contract_Id);
         system.debug('ContractId->>'+myFlow.AmendmentType);
         system.debug('ContractId->>'+myFlow.amendment_Id);
        // return new PageReference('/apex/BoothChangeAmendmentWizard');

        }else{
        if(myFlow.AmendmentType =='Cancellation'){
            return new PageReference('/apex/OpportunityCancelWizard?conAmdId='+myFlow.amendment_Id+'&id='+myFlow.contract_Id);
        }else{
            return new PageReference('/'+myFlow.amendment_Id);
        }
        }
    }
        return new PageReference('null');
    }

  public String selectedContactId{get;set;}
  public String selectedContractId{get;set;}
  public Contact contact {get;set;}
  Public string Conract;
  public Flow.Interview.Contract_Amendment_Creation_Wizard myFlow{get;set;}

  //public flow.interview.Contract_Amendment_Creation_Wizard dflow{get;set;}

  public AmendmentCreationWizardController() {
      selectedContactId = 'test';
      selectedContactId  = apexpages.currentpage().getparameters().get('ContactId');
      //selectedContactId = '003n0000008T4WL';
      selectedContractId =apexpages.currentpage().getparameters().get('ContractId');
      contact = new Contact();
  }

  public PageReference getContactDetails() {
        selectedContactId = Contact.ReportsToId;
        PageReference congratsPage = Page.ContractAmendmentCreationWizard;
        congratsPage.setRedirect(true);
        congratsPage.getParameters().put('ContactId',selectedContactId);
        congratsPage.getParameters().put('ContractId',selectedContractId);
        return congratsPage;
  }
}

A: I have tried the following its working,
The problem here is that it is refreshing the page.
Can I do this without refreshing the page?
<apex:page Controller="AmendmentCreationWizardController" title="New Contract Amendment">

<apex:sectionHeader title="New Contract Amendment"/>

    <apex:form >

         <apex:outputLabel value="Contract Emailed To" style="font-weight:bold;" rendered="{!selectedContactId == NULL}">    </apex:outputLabel>
          <apex:inputField id="Account" value="{!Contact.ReportsToId}" rendered="{!selectedContactId == NULL}" onChange="test1()"/>

          <apex:actionFunction name="test1" action="{!getContactDetails}" rerender="Test_2"/>

    </apex:form>
    <apex:outputPanel id="Test_2">
    <flow:interview name="Contract_Amendment_Creation_Wizard" interview="{!myFlow}"  id="Flow_1"  buttonLocation="bottom"  finishLocation="{!newPage}">
        <apex:param name="ContactId" value="{!selectedContactId}"/>
        <apex:param name="contract_Id" value="{!selectedContractId}"/>
  </flow:interview>
  </apex:outputPanel>

</apex:page>


text:
Q: Javascript form success I can't seem to get a success message to pop up with my form on my site. The message gets received but no indication is giving to the user via alert as it's meant to. Anyone have any ideas? Thank you :)

$(function() { $("input,textarea").jqBootstrapValidation({ preventSubmit: true, submitError: function($form, event, errors) { // additional error messages or events }, submitSuccess: function($form, event) { event.preventDefault(); // prevent default
submit behaviour // get values from FORM var name = $("input#name").val(); var email = $("input#email").val(); var phone = $("input#phone").val(); var message = $("textarea#message").val(); var firstName = name; // For Success/Failure Message // Check
for white space in name for Success/Fail message if (firstName.indexOf(' ') >= 0) { firstName = name.split(' ').slice(0, -1).join(' '); } $.ajax({ url: "././mail/contact_me.php", type: "POST", data: { name: name, phone: phone, email: email, message: message
}, cache: false, success: function() { // Success message $('#success').html("

"); $('#success > .alert-success').html("
  <button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×") .append("
  </button>"); $('#success > .alert-success') .append("
  Your message has been sent. "); $('#success > .alert-success') .append('

'); //clear all fields $('#contactForm').trigger("reset"); }, error: function() { // Fail message $('#success').html("

"); $('#success > .alert-danger').html("
  <button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×") .append("
  </button>"); $('#success > .alert-danger').append("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('
');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            });
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
    $('#success').html('');
});

A: I don't know about the functions you are using, but when I google for "Javascript message box", I receive a link to W3Schools "http://www.w3schools.com/js/js_popup.asp", mentioning the three functions alert, confirm and prompt.
Does this help?

A: $(function() {

    $("input,textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "././mail/contact_me.php",
                type: "POST",
                data: {
                    name: name,
                    email: email,
                    message: message
                },
                cache: false,
                success: function() {
                    // Success message
                    $('#success').html("
");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("Your message has been sent. ");
                    $('#success > .alert-success')
                        .append('
');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("
");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-danger').append("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('
');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            })
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
    $('#success').html('');
});


text:
Q: Run Parse operations in background I have an app, that gets data from the Parse server. Below is the code I'm using to go through all of the rows in "Offer" class and store them inside offerList array. Everything is working as expected, but I keep getting
warnBlockingOperationOnMainThread()

warnings in Xcode. Calling the whole function or it's body inside
DispatchQueue.global().async

also doesn't help. Here's the actual func:
func parseOfferList(){
    var amount: Int = 0
    offerList.removeAll()
    let offerQuery = PFQuery(className: "Offer")
    offerQuery.countObjectsInBackground { (count, error) in
        if error == nil {
            amount = Int(count)

            for i in 1...amount-1{
                let offerObj = try! offerQuery.whereKey("ID", equalTo: i).getFirstObject()
                var tempOffer = Offer()
                tempOffer.id = offerObj.object(forKey: "ID") as! Int
                tempOffer.name = offerObj.object(forKey: "name") as! String
                tempOffer.desc = offerObj.object(forKey: "desc") as! String
                tempOffer.lowSale = offerObj.object(forKey: "lowSale") as! Int
                tempOffer.topSale = offerObj.object(forKey: "topSale") as! Int

            offerList.append(tempOffer)
            }
        }
    }
}

I want to run this function right when the app starts, so when user logs in, offerList is already filled with info. Any ways to achieve this?


text:
Q: extract substring in R Suppose I have list of string "S[+229]EC[+57]VDSTDNSSK[+229]PSSEPTSHVAR" and need to get a vector of string that contains only numbers with bracket like  eg. [+229][+57].
Is there a convenient way in R to do this?

A: Using base R, then try it with
> unlist(regmatches(s,gregexpr("\\[\\+\\d+\\]",s)))
[1] "[+229]" "[+57]"  "[+229]"

Or you can use
> gsub(".*?(\\[.*\\]).*","\\1",gsub("\\].*?\\[","] | [",s))
[1] "[+229] | [+57] | [+229]"

A: We can use str_extract_all from stringr
stringr::str_extract_all(x, "\\[\\+\\d+\\]")[[1]]
#[1] "[+229]" "[+57]"  "[+229]"

Wrap it in unique if you need only unique values.

Similarly, in base R using regmatches and gregexpr
regmatches(x, gregexpr("\\[\\+\\d+\\]", x))[[1]]

data
x <- "S[+229]EC[+57]VDSTDNSSK[+229]PSSEPTSHVAR"

A: Seems like you want to remove the alphabetical characters, so
gsub("[[:alpha:]]", "", x)

where [:alpha:] is the class of alphabetical (lower-case and upper-case) characters, [[:alpha:]] says 'match any single alphabetical character', and gsub() says substitute, globally, any alphabetical character with the empty string "". This seems better than trying to match bracketed numbers, which requires figuring out which characters need to be escaped with a (double!) \\.
If the intention is to return the unique bracketed numbers, then the approach is to extract the matches (rather than remove the unwanted characters). Instead of using gsub() to substitute matches to a regular expression with another value, I'll use gregexpr() to identify the matches, and regmatches() to extract the matches. Since numbers always occur in [], I'll simplify the regular expression to match one or more (+) characters from the collection +[:digit:].
> xx <- regmatches(x, gregexpr("[+[:digit:]]+", x))
> xx
[[1]]
[1] "+229" "+57"  "+229"

xx is a list of length equal to the length of x. I'll write a function that, for any element of this list, makes the values unique, surrounds the values with [ and ], and concatenates them
fun <- function(x)
    paste0("[", unique(x), "]", collapse = "")

This needs to be applied to each element of the list, and simplified to a vector, a task for sapply().
> sapply(xx, fun)
[1] "[+229][+57]"

A minor improvement is to use vapply(), so that the result is robust (always returning a character vector with length equal to x) to zero-length inputs
> x = character()
> xx <- regmatches(x, gregexpr("[+[:digit:]]+", x))
> sapply(xx, fun)               # Hey, this returns a list :(
list()
> vapply(xx, fun, "character")  # vapply() deals with 0-length inputs
character(0)


text:
Q: Nodejs mocha/should on silent mode I try to find an option on mocha to avoid having so huge error explanation when one of my should assertion fail.
  5 passing (561ms)
  1 failing

  1) Actors Actors list should get a list of well formed actors:
 Uncaught AssertionError: expected ... to have property properties
  at test/actors.js:70:47
  at Array.forEach (native)
  at Test.<anonymous> (test/actors.js:65:35)
  at Test.emit (events.js:95:17)
  at IncomingMessage.emit (events.js:117:20)
  at _stream_readable.js:943:16

I'd like to have just the passing and failing infos but not the rest. Any idea ?
Cheers,


text:
Q: Script works in the shell but not via GUI dd-wrt router I have the following script working very well when I ssh into my dd-wrt router and issue the command
/opt/bin/curl --url "smtps://smtp.gmail.com:465" --ssl-reqd --mail-from "username@gmail.com" --mail-rcpt "username@gmail.com" --upload-file /mnt/mail.txt --user "username@gmail.com:password" --insecure

but when I issue the same commands via GUI; Administration/commands then the same script doesn't work.
any working solution will be a great help, thanks

A: Log in into the machine and type the command:
which sh

Put this value as a first line, preceding it with th #! characters, like
#!/bin/sh

What is your shell version? Look carefully at the first lines after you connected via ssh to your router. It's similar to:
BusyBox v1.15.3 (2011-11-24 00:44:20 CET) built-in shell (ash)
Enter 'help' for a list of built-in commands.

You may want to log the output of the command for debug purposes:
#!/bin/sh
/opt/bin/curl --url "smtps://smtp.gmail.com:465" --ssl-reqd --mail-from "username@gmail.com" --mail-rcpt "username@gmail.com" --upload-file /mnt/mail.txt --user "username@gmail.com:password" --insecure 2>&1 | logger -t $0

It will log the output using syslog facility. If it happens you have no syslog installed, you can log the output to a file:
#!/bin/sh
/opt/bin/curl --url "smtps://smtp.gmail.com:465" --ssl-reqd --mail-from "username@gmail.com" --mail-rcpt "username@gmail.com" --upload-file /mnt/mail.txt --user "username@gmail.com:password" --insecure >> /tmp/mylogfile 2>&1

Also, make sure, the script has an executable attribute set:
chmod a+rx /path/to/your/script


text:
Q: Beautyful soup не может найти значение BS спокойно парсит любые другие данные из блока, но на попытку спарсить счёт выдает None.
При этом значение счёта есть в исходном коде.
Код парсера:
import requests
from bs4 import BeautifulSoup

url = 'https://www.forebet.com/ru/prognozi-na-segodnq/prognozi-mnee-bolee' #Ссылка на ресурс для парса
r = requests.get(url)
#print(r.status_code)

soup = BeautifulSoup(r.text, "lxml")

#Тестовый сбор данных с первого блока

homeTeam = soup.find('div', class_='rcnt tr_0').find('span', class_='homeTeam')
awayTeam = soup.find('div', class_='rcnt tr_0').find('span', class_='awayTeam')
chance = soup.find('div', class_='rcnt tr_0').find('span', class_='fpr')
kef = soup.find('div', class_='rcnt tr_0').find('div', class_='avg_sc tabonly')
time = soup.find('div', class_='rcnt tr_0').find('span', class_='l_min')
score = soup.find('div', class_='rcnt tr_0').find('b', class_='l_scr')

def GetRes(): #Тестовое получение результатов
    print('Домашняя команда: ', homeTeam.text)
    print('Гостевая команда: ', awayTeam.text)
    print('Более: ',int(chance.text))
    print('Колличество голов: ', kef.text)
    print('Текущая минута: ', time.text)
    print('Счет: ', score)

GetRes()

A: Очивидно что вы не там ищите. Попробуйте:
score = soup.find('div', class_='lscr_td lResTdSmall').find('b', class_='l_scr').text

а ещё вы можете доработать, и получить вообще все очки.
Вот пример: (обратите внимание на find_all() )
score = [i.find('b', class_='l_scr').text for i in soup.find_all('div', class_='lscr_td lResTdSmall')]

По аналогии, вы вообще можете собрать всё что есть на странице в один объект/list of dicts.


text: Q: Prove $\det(e^{tA})=e^{t\cdot{tr} (A)}$ I wonder the condition of A to make the following statement true: $\det(e^{tA})=e^{t\cdot{tr} (A)}$, where A is an $n\times n$ matrix. If A is diagonalizable, then the statement can be proved. So, will the statement holds for A which isn't diagonalizable? I have tried using the Jordan form, but it is too complicated to obtain the result. Thank you!


text:
Q: Не получается записать данные в список Python получаю определённый тип данных, и я хочу записать эти данные в список. Данные получаются в виде словаря. Ниже пример получаемых данны
[{'89756720.000.000014': ['5765675', '45654654']}]
[{'89756720.000.000014': ['5765675', '45654654', '876876687', '465465456', '234653454']}]
[{'36546524.101.889045': ['5765675', '45654654', '23423454', '543425786']}]

мой код записывает только один из данных из всего в таком формате:
{'36546524.101.889045': ['5765675', '45654654', '23423454', '543425786']}

Как видно в примере выше, записывает только последнее что выводит код. Мой ожидаемый результат:
[{'89756720.000.000014': ['5765675', '45654654']}, {'89756720.000.000014': ['5765675', '45654654', '876876687', '465465456', '234653454']}, {'36546524.101.889045': ['5765675', '45654654', '23423454', '543425786']}]

Сам код:
for profile_info in links_array:
    profile_response = session2.get(profile_info, headers=header).text

    soup = BeautifulSoup(profile_response, 'html.parser')
    items = soup.find_all('div', class_='list-view')

    new_datas = []
    for item in items:
        new_datas.append({
            profile_info: [item['data-key'] for item in soup.find_all('div', attrs={'data-key': True})],
        })

    for item in new_datas:
        with open('datas.txt', 'w') as out:
            out.writelines("%s\n" % line for line in item)
    codes_len += 1

    print(new_datas)

A: for item in new_datas:
    with open('datas.txt', 'w') as out:
        out.writelines("%s\n" % line for line in item)

Так вы перезаписываете файл на каждой итерации цикла. Поэтому сохраняется только последнее значение. Нужно делать наоборот - сначала открывать файл на запись, а потом уже делать цикл по коллекции:
with open('datas.txt', 'w') as out:
    for item in new_datas:
        out.writelines("%s\n" % line for line in item)


text:
Q: SQL Server : select from parent where id doesnt exist in either child tables I need to select all rows from our customer table where they have no rows in the call table and no rows in the call archive table. Seems simple, but I have wrapped myself up in knots trying to get the query running.
So the structure of the tables is below: customer is the parent, with call and call archive both linked to the customer_id.
Can anyone help me out here please!
CREATE TABLE [dbo].[customer]
(
    [customer_Id] [varchar](50) NOT NULL
    CONSTRAINT [PK_customer]
        PRIMARY KEY CLUSTERED ([customer_Id] ASC)
)

CREATE TABLE [dbo].[call]
(
    [call_Id] [int] NOT NULL,
    [customer_Id] [int] NULL,
    [call_description] [varchar](50) NULL,

    CONSTRAINT [PK_call]
        PRIMARY KEY CLUSTERED ([call_Id] ASC)
)

ALTER TABLE [dbo].[call] WITH CHECK
    ADD CONSTRAINT [FK_call_customer]
        FOREIGN KEY([customerKey]) REFERENCES [dbo].[customer] ([customerkey])
GO

CREATE TABLE [dbo].[callArchive]
(
    [call_Id] [int] NOT NULL,
    [customer_Id] [int] NULL,
    [call_description] [varchar](50) NULL,

    CONSTRAINT [PK_call]
        PRIMARY KEY CLUSTERED ([call_Id] ASC)
)

ALTER TABLE [dbo].[call] WITH CHECK
    ADD CONSTRAINT [FK_call_customer]
        FOREIGN KEY([customerKey]) REFERENCES [dbo].[customer] ([customerkey])
GO

I tried doing a select count on the call_id columns using left outer joins but I am getting records in there that I was not expecting to see:
SELECT
    COUNT(call.Call_id) AS Calls,
    COUNT(callArchive.Call_id) AS Archive_Calls
FROM
    customer
LEFT OUTER JOIN
    call ON customer.customer_id = call.customer_id
LEFT OUTER JOIN
    callArchive ON customer.customer_id = callArchive.customer_id
HAVING
    ((COUNT(callArchive.Call_id) = 0)
     AND (COUNT(call.Call_id) = 0))
ORDER BY
    customer.customer_dateAdded DESC

A: Instead of faffing around with joins, a much simpler approach would be to use the not exists operator:
SELECT *
FROM   [customer] c
WHERE  NOT EXISTS (SELECT *
                   FROM   [call]
                   WHERE  [call].customer_id = c.customer_id) AND
       NOT EXISTS (SELECT *
                   FROM   [callArchive]
                   WHERE  [callArchive].customer_id = c.customer_id)

A: Faffing around with joins?  Joins as 'not simple'?  OK...now it's getting personal.  :-P
SELECT * FROM   [customer] cu

LEFT JOIN call c on cu.customer_id = c.customerID
LEFT JOIN callArchive ca on cu.customer_id = ca.customerID

WHERE c.customerID is null AND ca.customerID is null


text:
Q: Failed to load config "airbnb" to extend from - gitlab ci I tried to do and redo the Airbnb eslint installation in various ways, but I always get this build error inside GitLab-ci. It works in my local environment.
I created the project with the create-react-app, installed the dependencies separately so as not to overwrite the eslint version. But I've tried to install all dependencies together using npx install-peerdeps --dev eslint-config-airbnb and reinstalling the version of eslint created by creating react app.
I've also tried to set dependencies directly in package.json instead of creating a configuration file
My package.json:
{
  "name": "assinatura",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.4.1",
    "@emotion/styled": "^11.3.0",
    "@mui/material": "^5.0.2",
    "@react-pdf-viewer/core": "^2.9.1",
    "@react-pdf-viewer/page-navigation": "^2.9.1",
    "@react-pdf-viewer/zoom": "^2.9.1",
    "axios": "^0.21.4",
    "bootstrap": "^5.0.2",
    "enzyme-to-json": "^3.6.2",
    "pdfjs-dist": "2.6.347",
    "progress-bar": "^0.1.1",
    "prop-types": "^15.7.2",
    "query-string": "^7.0.1",
    "react": "^17.0.2",
    "react-bootstrap": "^2.0.0-rc.0",
    "react-dom": "^17.0.2",
    "react-icons": "^4.2.0",
    "react-meta-tags": "^1.0.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.3",
    "react-signature-canvas": "^1.0.3",
    "styled-components": "^5.3.1",
    "web-vitals": "^1.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "test:coverage": "react-scripts test --coverage",
    "eject": "react-scripts eject",
    "postinstall": "node ./postconfig.js",
    "eslint": "eslint .",
    "eslint-fix": "eslint --fix .",
    "build:staging": "sh -ac '. ./.env.staging; react-scripts build'"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "enzyme": "^3.11.0",
    "enzyme-adapter-react-16": "^1.15.6",
    "eslint-config-airbnb": "^18.2.1",
    "eslint-config-airbnb-base": "^14.2.1",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-jsx-a11y": "^6.4.1",
    "eslint-plugin-prettier": "^4.0.0",
    "prettier": "^2.4.1"
  }
}

My .eslintrc:
{
  "extends": [
    "react-app",
    "airbnb",
    "plugin:jsx-a11y/recommended",
    "prettier"
  ],
  "plugins": [
    "jsx-a11y",
    "prettier"
  ],
  "rules": {
    "semi": 0,
    "prettier/prettier": [
      "error", {
        "semi": false
      }
    ]
  }
}

and I put node_modules on .eslintignore
Has anyone ever experienced this?

A: In your .eslintrc or where your eslint config is,
look for the extends object and remove the "airbnb" from the array if it is not needed.
from ==>    "extends": ["airbnb", "prettier", "plugin:react/jsx-runtime", "plugin:jsx-a11y/recommended", "plugin:react-hooks/recommended"],

to ==>    "extends": ["prettier", "plugin:react/jsx-runtime", "plugin:jsx-a11y/recommended", "plugin:react-hooks/recommended"],

OR install the packages
npm install -g install-peerdeps install-peerdeps --dev eslint-config-airbnb install-peerdeps --dev eslint-config-airbnb-base

A: I had a similar issue on a react app while deploying through GitHub and was code built.
npm install -g install-peerdeps
install-peerdeps --dev eslint-config-airbnb
install-peerdeps --dev eslint-config-airbnb-base

Will fix it for you too

A: "eslintConfig": {
"extends": [
"react-app",
"react-app/test"
]
},

A: You can simply run this in cmd:
npm i eslint-config-airbnb-base

A: These Command-Line worked for me
rm -rf node_modules
sudo npm install eslint --save
sudo npm install eslint-config-airbnb-base --save
sudo npm install eslint-plugin-markdown --save
sudo npm install eslint-plugin-import --save
npm i
npx eslint --version


text:
Q: How to update 2 different rows depending on the WHERE and AND I want to update a table, and depending on the where and AND depends of the row I want to update, so if message_to and message_id match update message_deleted_to OR if message_user, message_id matches them update the messaged_deleted_from
My table:
CREATE TABLE IF NOT EXISTS `messages` (
  `message_id` int(11) NOT NULL,
  `message_user` int(11) NOT NULL,
  `message_subject` varchar(100) NOT NULL,
  `message_body` text NOT NULL,
  `message_to` int(11) NOT NULL,
  `message_from_read` int(1) NOT NULL DEFAULT '1',
  `message_to_read` int(11) NOT NULL DEFAULT '0',
  `message_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `message_deleted_from` int(11) NOT NULL DEFAULT '0',
  `message_deleted_to` int(11) NOT NULL,
  `message_permdeleted` int(11) NOT NULL DEFAULT '0',
  `message_type` varchar(11) NOT NULL,
  `message_deleted` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=35 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `messages`
--

INSERT INTO `messages` (`message_id`, `message_user`, `message_subject`, `message_body`, `message_to`, `message_from_read`, `message_to_read`, `message_date`, `message_deleted_from`, `message_deleted_to`, `message_permdeleted`, `message_type`, `message_deleted`) VALUES
(6, 12, 'lol', 'lol', 1, 1, 0, '2015-12-14 04:54:32', 0, 0, 0, 'sent', 0),

What I want to accomplish (I know this code won't work, I'm just trying to show you what I want to do)
UPDATE messages
    SET message_deleted_from = 1
    WHERE message_user = ?
    AND message_id = ?

    OR SET messages_delete_to = 1
    WHERE message_to
    AND message_id = ?

A: You can try this:
UPDATE messages
    SET message_deleted_from =
    CASE WHEN message_user = ?
    AND message_id = ? THEN 1 ELSE message_deleted_from END,

    messages_delete_to =
    CASE WHEN message_to=?
    AND message_id = ? THEN 1 ELSE messages_delete_to END

A: Your code isn't too far off.
UPDATE messages
SET message_deleted_from = 1
WHERE (message_user = ? AND message_id = ?)

UPDATE messages
SET message_deleted_to = 1
WHERE (message_to = ? AND message_id = ?)


text:
Q: Raspberry PI 2 termal printer not printing correctly I have the Raspberry Pi 2 and the thermal printer SP-MP-E3. When I'm connecting the printer's RX pin to raspberry's TX pin the printer printing continuously something in Cheneese characters. Here is the image

I disabled the serial interface from the raspberry but when I'm connecting the pin I have the same problem
Extra info :
I'm trying to use the port ttyAMA0 ( serial port for TX ) with JSSC library
I'm trying to use the ESC/POS
I changed the mod on raspbian for the serial port with the command "sudo chmod 777 /dev/ttyAMA0"
How can I do ?

A: The problem is the exists. When we connect a device to GPOS raspberry sendin signal for communication for this device. When it is a printer then printning continiously. The solution is to disable the serial interface
Here is the steps on rasbian
1 - Open terminal
2 - Write "sudo raspi-config" and press enter
3 - Go to advanced settings
4 - Disable the serial interface
5 - Restart rasbian


text:
Q: How to Connect to Bluetooth (Adapter) under Artix (Arch) OpenRC I have a Bluetooth USB adapter that I plug into my desktop PC to help me connect to Bluetooth stuff. It works perfectly under Windows 10. Except that I really can't get it to work with Artix OpenRC dual-boot, despite having installed all of the relevant packages and having watched and read many tutorials. (My headphones are Sony's LE_WH-1000XM3)
The closest I could get to something working was following this Gentoo OpenRC tutorial, but, at the very end, when trying connect device_mac_address all I get is a vague error message — yes, I have done rfkill unblock bluetooth —:
Attempting to connect to XX:XX:XX:XX:XX:XX
Failed to connect: org.bluez.Error.Failed

And, if I try to pair it again, I get Failed to pair: org.bluez.Error.AlreadyExists. Quite frankly, I find bluetoothctl's error messages quite terse and cryptic.

I have many packages installed, including:
alsa-utils
blueberry
blueman
bluez
bluez-tools
bluez-utils
bluetooth
bluetooth-openrc
pavucontrol
pulseaudio-alsa
pulseaudio-bluetooth
pulseaudio-ctl

So far, I have been using my headphones through cable, but even then I can't say the behavior has been very consistent. Sometimes I have to open pavucontrol and hack around to see if a specific configuration manages to enable to headphones.

A: Weirdly, if I open Blueberry and Pavucontrol at the same time, everything works. And the sound quality is even better than I thought.
I've been going through this setup for some days already and it hasn't failed me yet.
Additionally, if I close any of the programs I mentioned, after about 30s, the Bluetooth connection is terminated, i.e., I have to keep both open. I guess most desktop environments kind of do this, by keeping them in the background.


text:
Q: setAlpha() not working for buttons within Fragment lifecycle functions (Android) In one fragment in my application, a simple private method controls whether the "submit" button is activated or not:
private void activateSubmitButton(boolean activate){
    if (activate){
        submit.setClickable(true);
        submit.setAlpha((float)1);
    }else{
        submit.setClickable(false);
        submit.setAlpha((float)0.5);
    }
}

The Button object is created inside the OnCreateView() function of the Fragment:
submit = (Button) v.findViewById(R.id.newdutch_acceptbutton);

This is the button in question in the layout:
<Button
   android:id="@+id/newdutch_acceptbutton"
   android:text="ACCEPT"
   android:textSize="15sp"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   style="@style/acceptbutton"/>

My problem is the following: The default state of the button should be deactivated when the Fragment is created. In order to do this, the activateSubmitButton(FALSE) method is called from the onCreateView() method. However, the setAlpha() function doesn't work when it is called from any of the lifecycle methods of the Fragment. I've tried moving it inside the OnResume() method with no success.
This method activateSubmitButton() is called from many places in the Fragment's code, however. For example, when the user has filled all the boxes, the button's alpha is set to (float)1, and when the user erases one of the boxes, it goes back to (float)0.5. In these instances, everything works as it should.
What could be happening?