text:
Q: java.lang.NoClassDefFoundError: jakarta/servlet/http/HttpServletRequest Using Kubernetes, exactly the kubectl apply -f ./auth.yaml statement, i'm trying to run a Authorization Server in a pod, but when I check out the logs, this show me the following error:
 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::               (v2.6.13)

2022-12-07 01:33:30.099  INFO 1 --- [           main] o.v.s.msvc.auth.MsvcAuthApplication      : Starting MsvcAuthApplication v1.0-SNAPSHOT using Java 18.0.2.1 on msvc-auth-7d696f776d-hpk99 with PID 1 (/app/msvc-auth-1.0-SNAPSHOT.jar started by root in /app)
2022-12-07 01:33:30.203  INFO 1 --- [           main] o.v.s.msvc.auth.MsvcAuthApplication      : The following 1 profile is active: "kubernetes"
2022-12-07 01:33:48.711  INFO 1 --- [           main] o.s.c.k.client.KubernetesClientUtils     : Created API client in the cluster.
2022-12-07 01:33:48.913  INFO 1 --- [           main] o.s.c.a.ConfigurationClassPostProcessor  : Cannot enhance @Configuration bean definition 'org.springframework.cloud.kubernetes.client.KubernetesClientAutoConfiguration' since its singleton instance has been created too early. The typical cause is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.
2022-12-07 01:33:49.794  INFO 1 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=9e09a67e-4528-373e-99ad-3031c15d14ab
2022-12-07 01:33:50.922  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'io.kubernetes.client.spring.extended.manifests.config.KubernetesManifestsAutoConfiguration' of type [io.kubernetes.client.spring.extended.manifests.config.KubernetesManifestsAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2022-12-07 01:33:51.113  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.commons.config.CommonsConfigAutoConfiguration' of type [org.springframework.cloud.commons.config.CommonsConfigAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2022-12-07 01:33:51.184  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.client.loadbalancer.LoadBalancerDefaultMappingsProviderAutoConfiguration' of type [org.springframework.cloud.client.loadbalancer.LoadBalancerDefaultMappingsProviderAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2022-12-07 01:33:51.187  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'loadBalancerClientsDefaultsMappingsProvider' of type [org.springframework.cloud.client.loadbalancer.LoadBalancerDefaultMappingsProviderAutoConfiguration$$Lambda$420/0x0000000800f30898] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2022-12-07 01:33:51.205  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'defaultsBindHandlerAdvisor' of type [org.springframework.cloud.commons.config.DefaultsBindHandlerAdvisor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2022-12-07 01:33:51.311  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'kubernetes.manifests-io.kubernetes.client.spring.extended.manifests.config.KubernetesManifestsProperties' of type [io.kubernetes.client.spring.extended.manifests.config.KubernetesManifestsProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2022-12-07 01:33:51.412  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration' of type [org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2022-12-07 01:33:51.419  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration$ReactorDeferringLoadBalancerFilterConfig' of type [org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration$ReactorDeferringLoadBalancerFilterConfig] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2022-12-07 01:33:51.489  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'reactorDeferringLoadBalancerExchangeFilterFunction' of type [org.springframework.cloud.client.loadbalancer.reactive.DeferringLoadBalancerExchangeFilterFunction] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2022-12-07 01:33:58.301  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 9000 (http)
2022-12-07 01:33:58.393  INFO 1 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-12-07 01:33:58.393  INFO 1 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.68]
2022-12-07 01:33:58.795  INFO 1 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-12-07 01:33:58.796  INFO 1 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 26917 ms
2022-12-07 01:34:01.099  WARN 1 --- [           main] o.s.security.core.userdetails.User       : User.withDefaultPasswordEncoder() is considered unsafe for production and is only intended for sample applications.
2022-12-07 01:34:02.385  WARN 1 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authorizationServerSecurityFilterChain' defined in class path resource [org/villamzr/springcloud/msvc/auth/SecurityConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'authorizationServerSecurityFilterChain' threw exception; nested exception is java.lang.NoClassDefFoundError: jakarta/servlet/http/HttpServletRequest
2022-12-07 01:34:02.413  INFO 1 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2022-12-07 01:34:02.677  INFO 1 --- [           main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-12-07 01:34:02.991 ERROR 1 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authorizationServerSecurityFilterChain' defined in class path resource [org/villamzr/springcloud/msvc/auth/SecurityConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'authorizationServerSecurityFilterChain' threw exception; nested exception is java.lang.NoClassDefFoundError: jakarta/servlet/http/HttpServletRequest
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:658) ~[spring-beans-5.3.23.jar!/:5.3.23]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:638) ~[spring-beans-5.3.23.jar!/:5.3.23]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352) ~[spring-beans-5.3.23.jar!/:5.3.23]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195) ~[spring-beans-5.3.23.jar!/:5.3.23]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.23.jar!/:5.3.23]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.23.jar!/:5.3.23]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.23.jar!/:5.3.23]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.23.jar!/:5.3.23]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.23.jar!/:5.3.23]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.23.jar!/:5.3.23]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:955) ~[spring-beans-5.3.23.jar!/:5.3.23]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.23.jar!/:5.3.23]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.23.jar!/:5.3.23]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.13.jar!/:2.6.13]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:745) ~[spring-boot-2.6.13.jar!/:2.6.13]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:420) ~[spring-boot-2.6.13.jar!/:2.6.13]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) ~[spring-boot-2.6.13.jar!/:2.6.13]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1317) ~[spring-boot-2.6.13.jar!/:2.6.13]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.6.13.jar!/:2.6.13]
        at org.villamzr.springcloud.msvc.auth.MsvcAuthApplication.main(MsvcAuthApplication.java:12) ~[classes!/:1.0-SNAPSHOT]
        at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) ~[na:na]
        at java.base/java.lang.reflect.Method.invoke(Method.java:577) ~[na:na]
        at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49) ~[msvc-auth-1.0-SNAPSHOT.jar:1.0-SNAPSHOT]
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:108) ~[msvc-auth-1.0-SNAPSHOT.jar:1.0-SNAPSHOT]
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:58) ~[msvc-auth-1.0-SNAPSHOT.jar:1.0-SNAPSHOT]
        at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:88) ~[msvc-auth-1.0-SNAPSHOT.jar:1.0-SNAPSHOT]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'authorizationServerSecurityFilterChain' threw exception; nested exception is java.lang.NoClassDefFoundError: jakarta/servlet/http/HttpServletRequest
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.3.23.jar!/:5.3.23]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653) ~[spring-beans-5.3.23.jar!/:5.3.23]
        ... 25 common frames omitted
Caused by: java.lang.NoClassDefFoundError: jakarta/servlet/http/HttpServletRequest
        at org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer.getEndpointsMatcher(OAuth2AuthorizationServerConfigurer.java:235) ~[spring-security-oauth2-authorization-server-1.0.0.jar!/:1.0.0]
        at org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(OAuth2AuthorizationServerConfiguration.java:63) ~[spring-security-oauth2-authorization-server-1.0.0.jar!/:1.0.0]
        at org.villamzr.springcloud.msvc.auth.SecurityConfig.authorizationServerSecurityFilterChain(SecurityConfig.java:51) ~[classes!/:1.0-SNAPSHOT]
        at org.villamzr.springcloud.msvc.auth.SecurityConfig$$EnhancerBySpringCGLIB$$477933bf.CGLIB$authorizationServerSecurityFilterChain$1(<generated>) ~[classes!/:1.0-SNAPSHOT]
        at org.villamzr.springcloud.msvc.auth.SecurityConfig$$EnhancerBySpringCGLIB$$477933bf$$FastClassBySpringCGLIB$$a983a242.invoke(<generated>) ~[classes!/:1.0-SNAPSHOT]
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.3.23.jar!/:5.3.23]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331) ~[spring-context-5.3.23.jar!/:5.3.23]
        at org.villamzr.springcloud.msvc.auth.SecurityConfig$$EnhancerBySpringCGLIB$$477933bf.authorizationServerSecurityFilterChain(<generated>) ~[classes!/:1.0-SNAPSHOT]
        at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) ~[na:na]
        at java.base/java.lang.reflect.Method.invoke(Method.java:577) ~[na:na]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.3.23.jar!/:5.3.23]
        ... 26 common frames omitted
Caused by: java.lang.ClassNotFoundException: jakarta.servlet.http.HttpServletRequest
        at java.base/java.net.URLClassLoader.findClass(URLClassLoader.java:445) ~[na:na]
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:588) ~[na:na]
        at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:151) ~[msvc-auth-1.0-SNAPSHOT.jar:1.0-SNAPSHOT]
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) ~[na:na]
        ... 37 common frames omitted

This is the auth.yaml configuration.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: msvc-auth
spec:
  replicas: 1
  selector:
    matchLabels:
      app: msvc-auth
  template:
    metadata:
      labels:
        app: msvc-auth
    spec:
      containers:
        - image: villamzr/auth:latest
          name: msvc-auth
          ports:
            - containerPort: 9000
          env:
            - name: LB_USUARIOS_URI
              valueFrom:
                configMapKeyRef:
                  name: msvc-usuarios
                  key: lb_usuarios_uri
---
apiVersion: v1
kind: Service
metadata:
  name: msvc-auth
spec:
  type: LoadBalancer
  ports:
    - port: 9000
      protocol: TCP
      targetPort: 9000
  selector:
    app: msvc-auth

this one is the pom.xml of the microservice
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.villamzr.springcloud.msvc</groupId>
      <artifactId>curso-kubernetes</artifactId>
      <version>1.0-SNAPSHOT</version>
   </parent>
   <groupId>org.villamzr.springcloud.msvc.auth</groupId>
   <artifactId>msvc-auth</artifactId>
   <name>msvc-auth</name>
   <description>Demo project for Spring Boot</description>
   <properties>
      <java.version>18</java.version>
      <spring-cloud.version>2021.0.5</spring-cloud.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-security</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.security</groupId>
         <artifactId>spring-security-oauth2-client</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.security</groupId>
         <artifactId>spring-security-oauth2-authorization-server</artifactId>
         <version>1.0.0</version>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-webflux</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-kubernetes-client</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-kubernetes-client-loadbalancer</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>io.projectreactor</groupId>
         <artifactId>reactor-test</artifactId>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework.security</groupId>
         <artifactId>spring-security-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>
   <dependencyManagement>
      <dependencies>
         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
         </dependency>
      </dependencies>
   </dependencyManagement>
   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>

and this one is the Securityconfig
package org.villamzr.springcloud.msvc.auth;

import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer;
import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings;
import org.springframework.security.oauth2.server.authorization.settings.ClientSettings;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.UUID;

@Configuration
public class SecurityConfig {

    @Autowired
    private Environment env;

    @Bean
    @Order(1)
    public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http)
            throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        http.getConfigurer(OAuth2AuthorizationServerConfigurer.class)
                .oidc(Customizer.withDefaults());  // Enable OpenID Connect 1.0
        http
                // Redirect to the login page when not authenticated from the
                // authorization endpoint
                .exceptionHandling((exceptions) -> exceptions
                        .authenticationEntryPoint(
                                new LoginUrlAuthenticationEntryPoint("/login"))
                )
                // Accept access tokens for User Info and/or Client Registration
                .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);

        return http.build();
    }

    @Bean
    @Order(2)
    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http)
            throws Exception {
        http
                .authorizeHttpRequests((authorize) -> authorize
                        .anyRequest().authenticated()
                )
                // Form login handles the redirect to the login page from the
                // authorization server filter chain
                .formLogin(Customizer.withDefaults());

        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails userDetails = User.withDefaultPasswordEncoder()
                .username("admin")
                .password("12345")
                .roles("USER")
                .build();

        return new InMemoryUserDetailsManager(userDetails);
    }

    @Bean
    public RegisteredClientRepository registeredClientRepository() {
        RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
                .clientId("usuarios-client")
                .clientSecret("{noop}12345")
                .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
                .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
                .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
                .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
                .redirectUri(env.getProperty("LB_USUARIOS_URI")+"/login/oauth2/code/msvc-usuarios-client")
                .redirectUri(env.getProperty("LB_USUARIOS_URI")+"/authorized")
                .scope(OidcScopes.OPENID)
                .scope(OidcScopes.PROFILE)
                .scope("read")
                .scope("write")
                .clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
                .build();

        return new InMemoryRegisteredClientRepository(registeredClient);
    }

    @Bean
    public JWKSource<SecurityContext> jwkSource() {
        KeyPair keyPair = generateRsaKey();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        RSAKey rsaKey = new RSAKey.Builder(publicKey)
                .privateKey(privateKey)
                .keyID(UUID.randomUUID().toString())
                .build();
        JWKSet jwkSet = new JWKSet(rsaKey);
        return new ImmutableJWKSet<>(jwkSet);
    }

    private static KeyPair generateRsaKey() {
        KeyPair keyPair;
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048);
            keyPair = keyPairGenerator.generateKeyPair();
        }
        catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
        return keyPair;
    }

    @Bean
    public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
        return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource);
    }

    @Bean
    public AuthorizationServerSettings authorizationServerSettings() {
        return AuthorizationServerSettings.builder().build();
    }
}

SOLUTIONS I TESTED BUT IT DOWS NOT WORK

*

*I changed the tomcat server version to 10.x

*I added the jakarta-api dependency to pom.xml of microservice, with 3.x, 5.x and 6.x versions

*I added the @EnableWebSecurity
NOTES

*

*I'm using java 18

*I'm using Oauth 2.1 and authorization server 1.0.0

A: How are you building your Docker image? Whatever method you're using, it appears you're not including a web server (eg Tomcat or Jetty) in that image.

A: I was using Spring Boot 3 but was missing:
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


text:
Q: How do you make a http post request from api having params and body in flutter? I am a newbie in fetching data from APIs
I have an api endpoint containing two query params and also having a body of string and int.
I want to make an already existing post to be featured on the home page with time limit.
in my repo I have written this

class FeaturePost {
  Future featurePost(int duration, String period) async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    var token = preferences.getString('token').toString();
    final queryParameters = {
      'postpId': 'postId',
      'id': 'id',
    };
http.post(Uri.dataFromString("https/url.com/api/v1/post?" parameters: queryParameters),
        headers: {
          'Content-Type': 'application/json',
          'x-access-token': token,
        },
        body: {
          "duration": duration,
          "period": period
        });

here's my button
                                                   GestureDetector(
                                                    onTap: () async {
                                                      setState(() {
                                                        period =
                                                            "${dropdownValue}";
                                                      });
                                                      if (_postKey
                                                          .currentState!
                                                          .validate()) {
                                                        var create =
                                                            PostModel(
                                                          postId:
                                                              widget.postId,
                                                          id: widget.userId,
                                                          period: period,
                                                          duration: int.parse(
                                                              durationController
                                                                  .text),
                                                        );
                                                        createPost
                                                            .newPostDuration(
                                                          create,
                                                          widget.postId,
                                                        );
                                                      }
                                                    },
                                                    child: Center(
                                                        child: Text('Make Post Featured',),

                                                    ),
                                                  )

my controller
class FeaturePostController extends GetxController {
  final featureAPostRepo = FeaturePost();

  Future<dynamic> newFeaturedPost(ostpId, id) async {
    try {
      final result = await featureAnAdRepo.featureAnAd(postId, id);
      Get.back();
      await fromFeaturedAds.fetchFeaturedAds();
      // Get.snackBar('Success', 'Post Featured Successfully');

      print(result);
      return result;
    } catch (e) {
      throw Exception(e);
    }
  }
}

this is the response i get
Unhandled Exception: Null check operator used on a null value.

A: Since you're getting Null check operator used on a null value exception, it's probably because you haven't assigned your _postKey to the form that you are trying to validate. Make sure you're wrapping all your fields inside a form and that your key is assigned to the key parameter of that form

A: I was able to fix it. It was because I wasn't parsing all required params properly. All I had to do was add "postId" and "Id" like this ```featurePost(String postId, String Id, int duration, String period) and some rearrangements and it worked

redpajama_set_name: RedPajamaStackExchange


text: Q: Decipher and parsing protocol and url from packet payload We are using pf_ring to capture packets. We are able to decipher information like source and destination ip, mac etc from the header information. Now we are moving into payload to decide the type of protocol, url and other information. We see that tcpdump and wireshark have done good parsing. I have download tcpdump but cant find where is the parsing done to find out the application protocol and url. I know it exist so we dont want to reinvent the wheel.


text:
Q: API URLs and Parameters to be configurable in Drupal/PHP I have a drupal 8 website and have a lot of integrations(using curl) in custom modules.
The URLs of these APIs and its parameters need to be configurable by an admin panel.
What is the best way to do that?
Building a custom table and a custom form to save it or is there a specific module or create an entity type in admin configuration?
Here is my code:
      $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => "**https://test?parameter1=test&parameter2=test"**,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_HTTPHEADER => [
                "Content-Type: application/json",
                "accept: application/json",
                **"Authorization: Basic XXX"**
            ],
        ]);

A: You should create a Configuration Form to enter config values, and then Configuration API will save those values in config table.
When need to retrieve config values you can use:
$config = \Drupal::config('<your_config_name>');
$value = $config->get('<your_key>');


text:
Q: cannot map ec2 instance to elastic ip address trying from web console and as well through command line to associate the elastic ip to a micro instance using command:
ec2-associate-address -i <instance id> <elastic ip address>

It continuously gives error:

Client.InvalidParameterCombination: You must specify an allocation id when mapping an address to a VPC instance (Service: AmazonEC2; Status Code: 400; Error Code: InvalidParameterCombination; Request ID:

Followed the guide from:https://aws.amazon.com/articles/1346.
Anyone else is facing this issue. Infact I cannot select a running instance from the screen : elastic ip --> associate address and hence web console is out of question...
thanks in advance for any clue...

A: Exactly what it says on the tin. For an instance in a VPC, you have to provide an allocation ID when you associate an address. See: Elastic IP Addresses for details.
The ec2-associate-address style calls are ancient and I believe unmaintained at this point. You should be using the newer AWS CLI.
Your issue with the console is likely not having any EIPs available for VPC use. You cannot use a non-VPC EIP in a VPC. Allocate a new EIP and make sure you select VPC when doing so.

A: For VPC, you also need to specify the allocation id of the elastic ip. You are also using old style CLI. To fix your situation, get the allocation-id of the elastic ip.
ec2-describe-addresses <elastic ip address>

This will return a eipalloc-xxxxxxxx. Now associate it with the instance.
ec2-associate-address -i <instance-id> -a <eipalloc-xxxxxxxx>

Now the IP is associated with the instance.


text:
Q: How To Connect Two Domain I have a question. For example i have two domain:

*

*www.1.com (Php, MySQL, code, etc).

*www.2.com (Files for download).

Now how can i connect this two websites together?

How want I do?
  I want this : how can I connect this two domain for "Call" www.2.com from
  www.1.com to download/upload files without access in www.2.com
  I draw a picture for good understanding (sorry for my bad english).

Connect Two Domains ( Image )

A: You would probably use cURL from php.  cURL can do so many things, so you can probably google "php curl upload" or something the get more specific answers.  But the key-word you are looking for is probably cURL.
Please note that if you are going server-to-server, CORS will not make any difference -- CORS only affects client-to-server.


text:
Q: WooCommerce: Add a custom field in Product Short Description meta box I would like to add a custom field in Product short description WooCommerce Meta box.
This meta box is already built but I can't find a way to add an extra field to that meta box.
This is the code I found in woocommerce.
add_meta_box( 'postexcerpt', __( 'Product Short Description', 'woocommerce' ), 'WC_Meta_Box_Product_Short_Description::output', 'product', 'normal' );

Any help is highly appreciated.
Thanks in advance.


text:
Q: Not update button title when start countdown In my Vaadin project when click button then I need:

*

*Start countdown (10 seconds)

*Replace button's caption by left seconds (10,9,8 and so on)

I try this:
private Button buttonNext, buttonSendSMS;

private void runCountDown() {
        logger.info("countDown_start");
        buttonSendSMS.setEnabled(false);
        final Timer timer = new Timer();

        timer.scheduleAtFixedRate(new TimerTask() {
            int leftSeconds = 10;

            public void run() {
                leftSeconds--;

                UI.getCurrent().access(new Runnable() {

                    @Override
                    public void run() {
                        logger.info("leftSeconds = " + leftSeconds);
                        buttonSendSMS.setCaption(leftSeconds + "");
                    }
                });

                if (leftSeconds < 0) {
                    logger.info("countDown_finish");
                    timer.cancel();
                    buttonSendSMS.setEnabled(true);
                    new MessageService(getWzContext().getLang());
                    buttonSendSMS.setCaption(MessageService.getMessage("resend.sms"));
                }
            }
        }, 0, 1000);
    }

When click button here log:
 INFO] 12.01.2021 17:35:58.112 [Timer-0] com.myproject.client.ui.wz.SmsCodeStepWz$2$1.run(SmsCodeStepWz.java:202)
    leftSeconds = 9
INFO] 12.01.2021 17:35:59.111 [Timer-0] com.myproject.client.ui.wz.SmsCodeStepWz$2$1.run(SmsCodeStepWz.java:202)
    leftSeconds = 8
[INFO] 12.01.2021 17:36:00.110 [Timer-0] com.myproject.client.ui.wz.SmsCodeStepWz$2$1.run(SmsCodeStepWz.java:202)
    leftSeconds = 7
[INFO] 12.01.2021 17:36:01.110 [Timer-0] com.myproject.client.ui.wz.SmsCodeStepWz$2$1.run(SmsCodeStepWz.java:202)
    leftSeconds = 6
[INFO] 12.01.2021 17:36:02.111 [Timer-0] com.myproject.client.ui.wz.SmsCodeStepWz$2$1.run(SmsCodeStepWz.java:202)
    leftSeconds = 5
[INFO] 12.01.2021 17:36:03.110 [Timer-0] com.myproject.client.ui.wz.SmsCodeStepWz$2$1.run(SmsCodeStepWz.java:202)
    leftSeconds = 4
[INFO] 12.01.2021 17:36:04.110 [Timer-0] com.myproject.client.ui.wz.SmsCodeStepWz$2$1.run(SmsCodeStepWz.java:202)
    leftSeconds = 3

But on Web page replace button's caption to 9. Nice.
But after one second NOT REPLACE by 8. And nothing happened. Button's caption is only 9.
As you can see I try to update button's caption on UI thread but it not help.

A: I just tried your code with Vaadin version 8.12.0 and it works fine. It sounds like you don't have Server Push properly configured. In the simplest case, you need to add @Push annotation on your class for your code to work.
EDIT:
The following similar example works fine in Vaadin 7.7.17.
@Push
public class MyUI extends UI {

    @Override
    protected void init(VaadinRequest vaadinRequest) {
        final VerticalLayout layout = new VerticalLayout();
        setContent(layout);

        Button button = new Button("", e -> Notification.show("Hello world"));
        layout.addComponents(button);

        button.setEnabled(false);
        final Timer timer = new Timer();

        timer.scheduleAtFixedRate(new TimerTask() {
            int leftSeconds = 10;

            @Override
            public void run() {
                leftSeconds--;

                UI.getCurrent().access(() -> button.setCaption(leftSeconds + ""));

                if (leftSeconds < 1) {
                    timer.cancel();
                    UI.getCurrent().access(() -> {
                        button.setCaption("Click me");
                        button.setEnabled(true);
                    });
                }
            }
        }, 0, 1000);

    }

    @WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
    @VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
    public static class MyUIServlet extends VaadinServlet {
    }
}

A: Testing based on question
Based on your question I created a demo application for Vaadin 7.3.6 and tested this use case. Unfortunately I couldn't reproduce your issue based on the provided information.
Here are the steps I took

*

*Created a new Vaadin 7.3.6 application using the Maven Archetype command

mvn archetype:generate \
   -DarchetypeGroupId=com.vaadin \
   -DarchetypeArtifactId=vaadin-archetype-application \
   -DarchetypeVersion=7.3.6 \
   -DgroupId=io.github.pgerhard \
   -DartifactId=stackoverflow-65687155 \
   -Dversion=0.0.1-SNAPSHOT \
   -Dpackaging=war

*Updated the generated UI class with the timer logic. Here is the updated code of my UI class

package io.github.pgerhard;

import javax.servlet.annotation.WebServlet;

import com.vaadin.annotations.Push;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;

import java.util.Timer;
import java.util.TimerTask;

@Push
@Theme("mytheme")
@SuppressWarnings("serial")
public class MyVaadinUI extends UI {

    @WebServlet(value = "/*", asyncSupported = true)
    @VaadinServletConfiguration(productionMode = false, ui = MyVaadinUI.class, widgetset = "io.github.pgerhard.AppWidgetSet")
    public static class Servlet extends VaadinServlet {
    }

    @Override
    protected void init(VaadinRequest request) {
        final VerticalLayout layout = new VerticalLayout();
        layout.setMargin(true);
        setContent(layout);

        final Timer timer = new Timer();
        final Button button = new Button("Start Countdown");
        final Label countDownLabel = new Label("Count Down Running ");
        countDownLabel.setVisible(false);

        button.addClickListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                countDownLabel.setVisible(true);
                layout.addComponent(countDownLabel);
                button.setCaption("10");
                button.setEnabled(false);

                timer.scheduleAtFixedRate(new TimerTask() {
                    int secondsLeft = 10;

                    @Override
                    public void run() {
                        System.out.printf("Seconds left: %d%n", secondsLeft);

                        if (secondsLeft < 0) {
                            timer.cancel();
                            UI.getCurrent().access(new Runnable() {
                                @Override
                                public void run() {
                                    button.setCaption("Start Countdown");
                                    countDownLabel.setVisible(false);
                                    button.setEnabled(true);
                                }
                            });
                        } else {
                            UI.getCurrent().access(new Runnable() {
                                @Override
                                public void run() {
                                    button.setCaption(String.valueOf(secondsLeft));
                                }
                            });
                        }

                        secondsLeft--;
                    }
                }, 0, 1000);
            }
        });
        layout.addComponent(button);
        layout.addComponent(countDownLabel);
    }

}

*Built the project using mvn clean install

*Started the Jetty server included by the Maven archetype using mvn jetty:run
All of my code, details on my OS and Java version are available on Github https://github.com/pgerhard/stackoverflow-65687155
As  Tarek mentioned in his answer adding @Push enabled the UI to be update from the server side for me.
Alternative Causes
Without further details on your exact scenario I can come up with the following reasons why this does not work

*

*By default Vaadin 7.3.6 uses Transport.WEBSOCKET for Server Push using the @Push annotation. This may be being blocked in your deployment, you could try changing to using Transport.LONG_POLLING

*The issue is not related to Vaadin but rather your servlet container

Also, while this not related the issue regarding the updating of your buttons caption, I believe the provided code contains another bug. When the count down is finished you are enabling the button again, however you are not accessing the UI in order to this. Thus the update will not be pushed to the client. I believe you should change
if (leftSeconds < 0) {
    logger.info("countDown_finish");
    timer.cancel();
    buttonSendSMS.setEnabled(true);
    new MessageService(getWzContext().getLang());
    buttonSendSMS.setCaption(MessageService.getMessage("resend.sms"));
}

to
if (leftSeconds < 0) {
    logger.info("countDown_finish");
    timer.cancel();
    new MessageService(getWzContext().getLang());
    UI.getCurrent().access(new Runnable() {
        @Override
        public void run() {
            buttonSendSMS.setEnabled(true);
            buttonSendSMS.setCaption(MessageService.getMessage("resend.sms"));
        }
    });
}

Note the call to UI.getCurrent().access() and then enabling the button inside this, along with updating the caption.


text:
Q: Laravel 5.3 multiple file uploads How can I upload multiple files in Laravel 5.3.
If I try it with 1 image it works but multiple images are not uploaded.
This is my code:
if($request->hasFile('attachment')) {
    foreach($request->allFiles('attachments') as $file) {
        $file->store('users/' . $user->id . '/messages');
    }
}

A: It works now like this:
$files = $request->file('attachment');

if($request->hasFile('attachment'))
{
    foreach ($files as $file) {
        $file->store('users/' . $this->user->id . '/messages');
    }
}

I had to append [] after the value of the name attribute, so:
<input type="file" name="attachment[]" multiple>

A: Solved it with this one a simplier approach. Just make sure that your input file type is like this <input type="file" name="images[]" multiple>
$i = 0;
foreach($request->file('images') as $file){
    $photo = new Photo;
    // name it differently by time and count
    $imageName = time() . $i . '.' . $file->getClientOriginalExtension();
    // move the file to desired folder
    $file->move('folderName/', $imageName);
    // assign the location of folder to the model
    $photo->image = 'folderName/' . $imageName;
    $photo->status = 1;
    $photo->save();
    $i++;
}

A: This is Controller to upload multiple files in laravel:
    public function fileUpload(Request $request)
    {
        if ($request->hasfile('filenames')) {
            foreach ($request->file('filenames') as $file) {
                $name = $file->getClientOriginalName();
                $file->move(public_path() . '/mytestfile/', $name);
                $data[] = $name;
            }
            return back()->with('Success!','Data Added!');
        }
    }

This view file in resources:

    <title>Multiple Image Upload</title>

    <link rel="stylesheet" href="3.3.6/css/bootstrap.min.css">

Test Muliple Image Upload

    <form method="post" action="{{url('image-upload')}}" enctype="multipart/form-data">
        {{csrf_field()}}

            <input type="file" name="filenames[]" class="myfrm form-control" multiple>

                <button class="btn btn-success" type="button">Add</button>

        <button type="submit" class="btn btn-success" style="margin-top:10px">Submit</button>
    </form>

A: Try some thing like this:
public function multiple_upload() {
    // getting all of the post data
    $files = Input::file('images');

    // Making counting of uploaded images
    $file_count = count($files);

    // start count how many uploaded
    $uploadcount = 0;

    foreach($files as $file) {
        $rules = array('file' => 'required');

        //'required|mimes:png,gif,jpeg,txt,pdf,doc'

        $validator = Validator::make(array('file'=> $file), $rules);

        if($validator->passes()){
             $destinationPath = 'uploads';
             $filename = $file->getClientOriginalName();
             $upload_success = $file->move($destinationPath, $filename);
             $uploadcount ++;
         }
    }
}

A: Controller.Php / Laravel 5.7.28
$files = $request->file('product_image_id');
if($request->hasFile('product_image_id')){
    foreach ($files as $file) {
        $name = time(). $file->getClientOriginalName();
        $file->move('images',$name);
        $productImage = ProductImage::create(['image'=>$name]);
        $input ['product_image_id'] = $productImage->id;
    }
}

A: If you want to still working with blade you can use this:
{{ Form::open(array('url' => 'upload', 'files'=>true)); }}
{{ Form::file('gallery[]', array('multiple'=>true,'accept'=>'image/*'));  }}
{{ Form::submit();  }}
{{ Form::close();  }}

And in your Controller :
files = $request->file('gallery');

if($request->hasFile('gallery'))
{
    foreach ($files as $file) {
       // $file->store('users/' . $this->user->id . '/messages');
        //dump($file);
    }
}

A: This is how my blade looks like:

                                Photo

                                    {{-- <input type="file" name="images[]" multiple> --}}
                                    <input type="file" class="form-control form-control-file"
                                     id="gallery-image" value="{{ old('gallery-image') }}" required name="gallery-image[]" multiple/>
                                     Advised image dimensions: 1920 x 450 pixels. File size should be less than 2Mb per image.

                                @error('image')

                                    {{ $message }}

                                @enderror

And this is how the store function in the controller looks like:
public function store(Request $request){
    $validation = Validator::make($request->all(), array(
        'gallery-id'    => 'required|integer|min:0',
        'gallery-image' => 'required|image|nullable|mimes:jpeg,png,jpg,gif|max:2048',
    ));
    $fileNameToStore="no-image.jpg";

    if(request('gallery-image'))
    {
        $iCount=0;
        foreach($request->file('gallery-image') as $thisImage){
            $fileNameWithExtension = $thisImage->getClientOriginalName();
            $memberName = Auth::user()->MemberProfile->member_tourist_office_name;

            $extension=$thisImage->getClientOriginalExtension();

            $fileNameToStore = $fileName.'_'.time().$iCount.'.'.$extension;

            $path= $thisImage->storeAs('public/images/members/gallery-images',$fileNameToStore);

            $isEnabled                                   = "0";
            $galleryImage                                = new GalleryImage();
            $galleryImage->gallery_id                    = request('gallery-id');
            $galleryImage->gallery_image_caption         = " ";
            $galleryImage->gallery_image                 = $fileNameToStore;
            $galleryImage->isEnabled                     = $isEnabled;

            $galleryImage->save();
            $iCount++;
        }
        return redirect('/galleryimage/create')->with('success', 'Image(s) successfully added to gallery!');
    }
}

A: public function MultiImage(Request $request)
{
    $postimage=new Photo;

   if($request->hasfile("file")){
        foreach($request->file("file") as $img) {
            $filename = $img->getClientOriginalName();
            Image::make($img)->resize(200, 200)->save('banner/uploads/photo/'.$filename);
            $uploadPath = 'banner/uploads/photo/'.$filename;
            $data[]=$filename;
        }
        $postimage->code = time();
        $postimage->name = $filename;
        $postimage->private_state = $request->input('private_state');
        $postimage->description = $request->input('description');
        $postimage->titre = $request->input('titre');
        $postimage->mute = $request->input('mute');
        $postimage->user_id = $request->input('user_id');
        $postimage->save();
    }
    return redirect()->route('timeline-photos');
}

je veux enregistrer plusieurs images dans la base de donnees avec laravel. voici mon code et ca n'enregistre qu'une seule image.
cordialement,


text:
Q: How do I lowercase a string and also change space into underscore in python? How can I change a string into lowercase and change space into an underscore in python?
For example, I have a string which Ground Improvement
I want it to be ground_improvement
For now, I know how to that manually use replace.
df['type'] = df['type'].replace('Ground Improvement', 'ground_improvement')

But it's only for ground improvement, I want to make some automation so if there comes any string into the type column, the script will always change into the format I want.
Thankyou.

A: Use lower and replace on whitespace
df['type'] = df['type'].str.replace(' ','_').str.lower()

input:
df = pd.DataFrame({'type':['Ground Improvement']})
df

looks like this

    type
0   Ground Improvement

output

    type
0   ground_improvement

A: Just two lines: -
s = "Ground Improvement"
s = str.lower() # Converts the entire string to lower case
s = str.replace(' ', '_') # Replaces the spaces with _

And There you have ground_improvement stored in s!


text:
Q: Is there a way to get DataNode's DiskUsage using java client? I want to get disk-usage status of a DataNode over RPC/ Java Client. I know there is a way using WebAPI and parsing the response.
But, I am looking for RPC based approach only.


text:
Q: Navigate from One lwc to another and then back to that component on particular div Parent Component

 <lightning-input value={value} onchange={handleValue}>
 </lightning-button>

 <lightning-button variant="neutral" label="Back" onclick=
  {gotochildcomponent}>
 </lightning-button>
 <lightning-button variant="neutral" label="save" onclick=
  {saveadata}>
 </lightning-button>

    <c-add-accesory location-id-to-get={locationidtopass}></c-add-accesory>

Child Component
<template>

Accessory Category

         <template for:each={AccessoryCategoryData} for:item="item">
            <lightning-button class={item.color}  variant={item.variant} value={item.value} key={item.Index} label={item.label}
               data-value={item.FormatId} onclick={AccessoryCategoryDataFn}>
            </lightning-button>
         </template>

         <lightning-button variant="neutral" label="Back" onclick={backtoSecondivofParentComponent}></lightning-button>

</template>

I have 2 div in my parent component 2nd div shows after 1st div hide so on the second div there is a button which takes me to child component and on child component there is a button with onclick "BacktoCongratsScreen".
So I want to go back to the second div in the Parent component.

A: How do you navigate between components? If you are not using lightning/navigation, you can use a function property on the div to toggle the components.
To pass the toggle property from parent to child, you can use as if you are passing attributes in aura, but if it's child to parent you can use an event that will fire from the child component's button event.

A: Once you go to Child component, again write a
 inside <template if:true={condition}> which calls the Parent component and pass some parameters as well if needed.
Ex -
Below your child component code, but inside root  tag.
Both in Parent & Child component, create @track firstdiv. In child set that variable to false on click of back button & set is to return call of parent callback as shown below.
<template if:true={condition}>

      <c-parent-component firstdiv={firstdiv}></c-parent-component>

</template>

Just set proper boolean values in Child component's JS & you can achieve it.


text:
Q: QField Create Geometry I use QField for tree surveys. I use Geometry generator to create the crown (canopy) spread based on crown radius taken at N, S E and W. This works, but the crown is 'virtual' and cannot be edited. Rather than use 'Geometry Generator' or a 'Virtual Layer', I would like to automatically create the geometry in an editable layer. I'm aware QField does not yet support Python. But is there some other way of creating editable geometries based on the attribute values of a layer?
O


text:
Q: "Invalid Request" while trying to get eBay user Access Token. No specific error number given This is the extremely vague response I'm getting, while trying to get a user access token:
{
"error":"invalid_request",
"error_description":"request is invalid",
"error_uri":null
}

Here is my code:
$headers = array (
        "Authorization: ".sprintf(
                     'Basic %s',
                     base64_encode(sprintf('%s:%s', $client_id, $client_secret))
                 )." ",
        'Content-Type:application/x-www-form-urlencoded'

);

$apiURL = "https://api.sandbox.ebay.com/identity/v1/oauth2/token";
$urlParams = array (
        "grant_type" => "authorization_code",
        "code" => $auth_code,
        "redirect_uri" => "xxx-xxx-xxx-SBX-ccd-xxx"
);
$data_json = json_encode($urlParams);

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt ( $ch, CURLOPT_POST, 1 );
curl_setopt ( $ch, CURLOPT_HEADER, 1 );

curl_setopt($ch, CURLOPT_URL, $apiURL);
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data_json );

$resp = curl_exec ( $ch );
curl_close ( $ch );

print_r ( $resp );

How can I debug this when it doesn't even hint at what's wrong with my request?
I've been through this page step-by-step:
https://developer.ebay.com/devzone/rest/ebay-rest/content/oauth-gen-user-token.html#Updating

A: It seems that you encode your body in Json while the authorization server expects body parameters in POST field format.
The headers should also contains key/value pairs but you are sending only a list of values
Could you please try with the following code:
$headers = array (
        'Authorization' => sprintf('Basic %s',base64_encode(sprintf('%s:%s', $client_id, $client_secret))),
        'Content-Type'  => 'application/x-www-form-urlencoded'
);

$apiURL = "https://api.sandbox.ebay.com/identity/v1/oauth2/token";
$urlParams = array (
        "grant_type" => "authorization_code",
        "code" => $auth_code,
        "redirect_uri" => "xxx-xxx-xxx-SBX-ccd-xxx"
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Should be removed on production
curl_setopt ( $ch, CURLOPT_POST, 1 );
curl_setopt ( $ch, CURLOPT_HEADER, 1 );

curl_setopt($ch, CURLOPT_URL, $apiURL);
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $urlParams );

$resp = curl_exec ( $ch );
curl_close ( $ch );

print_r ( $resp );

A: Authorization header should have a following format:
'Authorization' => sprintf('Basic <%s>',base64_encode(sprintf('%s:%s', $client_id, $client_secret)))


text:
Q: How can make schedule job in Python to pop elements of the list? I want to pop each element of string list below for every given time interval.
I have tried following code at my end but every time it fetches only last element.
import schedule
import time
def job():
    #print("I'm working...")
    string = [1, 2, 3, 4]
    print (string.pop())

schedule.every(0.1).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)

while 1:
    schedule.run_pending()
    time.sleep(1)

The result I am getting is 4 4 4 4. I expect 4 3 2 1.


text:
Q: Does calculating correlation between two dataframes require a loop? I have a set of large dataframes that look like A and B:
A <- data.frame(A1=c(1,2,3,4,5),B1=c(6,7,8,9,10),C1=c(11,12,13,14,15 ))

  A1 B1 C1
1  1  6 11
2  2  7 12
3  3  8 13
4  4  9 14
5  5 10 15

B <- data.frame(A2=c(6,7,7,10,11),B2=c(2,1,3,8,11),C2=c(1,5,16,7,8))

  A2 B2 C2
1  6  2  1
2  7  1  5
3  7  3 16
4 10  8  7
5 11 11  8

I would like to create a vector (C) that denotes the Pearson correlation between A1 & A2, B1 & B2, and C1 & C2. In this case, for example, those correlations are:
[1] 0.95 0.92 0.46

A: You can use friend of apply functions, Map, for that.
Map(function(x,y) cor(x,y),A,B)
$A1
[1] 0.9481224

$B1
[1] 0.9190183

$C1
[1] 0.459588

If you want the output as vector as suggested by @Jilber :
unlist(Map(function(x,y) cor(x,y),A,B))
       A1        B1        C1
0.9481224 0.9190183 0.4595880

Or you can just use:
 unlist(Map(cor,A,B))
       A1        B1        C1
0.9481224 0.9190183 0.459588

A: Another alternative you can use mapply function
> mapply(function(x,y) cor(x,y),A,B)
       A1        B1        C1
0.9481224 0.9190183 0.4595880

Or just mapply(cor, A, B) as suggested by @Aaron.

A: cor accepts two data.frames:
A<-data.frame(A1=c(1,2,3,4,5),B1=c(6,7,8,9,10),C1=c(11,12,13,14,15 ))

B<-data.frame(A2=c(6,7,7,10,11),B2=c(2,1,3,8,11),C2=c(1,5,16,7,8))

cor(A,B)

#           A2        B2       C2
# A1 0.9481224 0.9190183 0.459588
# B1 0.9481224 0.9190183 0.459588
# C1 0.9481224 0.9190183 0.459588

diag(cor(A,B))
#[1] 0.9481224 0.9190183 0.4595880

Edit:
Here are some benchmarks:
Unit: microseconds
                   expr     min       lq   median       uq      max neval
        diag(cor(A, B)) 230.292 238.4225 243.0115 255.0295  352.955   100
      mapply(cor, A, B) 267.076 281.5120 286.8030 299.5260  375.087   100
 unlist(Map(cor, A, B)) 250.053 259.1045 264.5635 275.9035 1146.140   100

Edit2:
And some better benchmarks using
set.seed(42)
A <- as.data.frame(matrix(rnorm(10*n),ncol=n))
B <- as.data.frame(matrix(rnorm(10*n),ncol=n))

However, I should probably mention that these benchmarks strongly depend on the number of rows.
Edit3: Since I was asked for the benchmarking code, here it is.
b <- sapply(2^(1:12), function(n) {
    set.seed(42)
    A <- as.data.frame(matrix(rnorm(10*n),ncol=n))
    B <- as.data.frame(matrix(rnorm(10*n),ncol=n))

    require(microbenchmark)
    res <- print(microbenchmark(
                   diag(cor(A,B)),
                   mapply(cor, A, B),
                   unlist(Map(cor,A,B)),
                   times=10
                 ),unit="us")
    res$median
})

b <- t(b)

matplot(x=1:12,log10(b),type="l",
        ylab="log10(median [µs])",
        xlab="log2(n)",col=1:3,lty=1)
legend("topleft", legend=c("diag(cor(A, B))",
                           "mapply(cor, A, B)",
                           "unlist(Map(cor,A,B))"),lty=1, col=1:3)


text:
Q: Rank of homology group $x_0$ is the unique a global minimum and let $c=f(x_0)$ in a Hilbert space, let $\theta$ be an other critical point of $f$ non minimum.
the Morse type number of $x_0$ is
$$m_q(x_0)=R_q(f^{c+\varepsilon}\cap U_{x_0},f^{c-\varepsilon}\cap U_{x_0})=R_q(U_{x_0},\emptyset)=\left\{\begin{array}{lc} 1 & \text{if}\ q=0 \\ 0 & \text{if}\ q\neq 0\end{array}\right. $$
for $\varepsilon >0$ small, where $$R_q(f^{c+\varepsilon}\cap U_{x_0},f^{c-\varepsilon}\cap U_{x_0})$$ is the rank of the relative singuler homology group $$H_q(f^{c+\varepsilon}\cap U_{x_0},f^{c-\varepsilon}\cap U_{x_0}), f^{\alpha}=\{x\in H, f(x)\leq \alpha\}$$
if i assume that there were no other critical points than $\theta$ and $x_0$, then there would be no critical points in $H\setminus f^b$, if $b> \max\{ f(\theta),c\}$
I dont understand why then we have that : $$R_q(f^b)=R_q(H)=\left\{\begin{array}{lc} 1 & \text{if}\ q=0 \\ 0 & \text{if}\ q\neq 0\end{array}\right. $$
in the paper they say that because $f^b$ is a retract deformation of $H$ , but i don't understand why in this case the morse index is equal to zero ????
Please help me
Thank you.


text:
Q: Should we create local web services within an Asp.Net application which are called by the application itself? I've moved to a new project team and while going over the codebase, found that the team have created a number of local web services which then get called by server code in other web pages within the same application.
I'm somewhat puzzled by this architecture, as I'd thought local web services were something you'd then access from the client, or from other distinct applications.
However by communicating with the local web service from other server code in our application, it seems to me that we're going through the rigmarole of wrapping the message into XML/Soap and thru the html stack to the service and then back again and will end up adding a shedful of time and slow down the application.
Have mentioned my concerns on this to my new colleagues, and theres been a bit of debate. Just wondered what others thought of this approach and am I right to be concerned?
Thanks
Mickey

A: Using local web services is not a bad thing.  It can increase the modularization (increased cohesion, decreased coupling) of a given application.  Moving the target code into a web service can be thought of like creating a shared library (DLL, .so, etc.) with the important benefit of being easily called from different processes.  It's like getting RPC or DCOM for much less headache.  As long as you keep the calling convention clear, it shouldn't be a problem to create applications that are almost entirely made up of web service calls.  It's the application version of Mash-ups.

A: Even though yoru web service gets called by 1 client at the moment, perhaps there will be other clients in the future. From that point of view I'd be more concerned about whether the application partition makes sense architecturally. That is, is that a good separation of concerns? Of course performance is another consideration.

A: I think you are right to be a bit surprised that the team would implement a web service call within the application - why pay the overhead?
The real problem, though, isn't necessarily the web service call - this is a legitimate technique.  The greater problem is likely to be in your division of responsibilities.  The web service handler is akin to the UI in a standard page: there to handle the interaction with the outside world.  It should be passing off the arguments it receives to a business logic object.
The advantages of a separate business logic object are manifold: easier unit testing and the ability to call directly into the same function from within your code are the most prominent.  Thus, they should probably refactor the logic out of the web service and into a business logic object and call the object directly rather than incurring the overhead of the web service call.


text:
Q: Can we always define the projection in a ball of raius $R$ for any Polish metric space $X$? I'm generalizing some theorems to Polish metric spaces, which were originally proved for $\mathbb R^n$. Hence, as I'm adapting the proofs, I'm checking whether where I can reuse the same arguments. In one of my proofs, I had the following:
"Define $\pi_R : \mathbb R^n \to B(R)$ to be the projection operator on the closed ball with radius $R$ and centered at zero".
Now I'd like to use this for an $X$ metric Polish space. Can I "safely" assume that there exists such projection operator $\pi_R: X \to B(R)$ such that the closed ball is centered at some
$x_0 \in X$? How can I know that this map is well defined?

A: The answer is "no". Consider the separable real Banach space $\ell^2$. Any closed subspace of $\ell^2$ is Polish, a fact we shall soon use.
Let $e_n$ be the $n$th basis vector, i.e. $e_n$ is the sequence such that the $n$th entry in the sequence is $1$, while the other entries are $0$. Let
$$C = \left\{\frac{1 + \frac{1}{n}}{4}e_{n+1} : n \ge 1\right\}$$
and
$$X = C \cup \{2e_1\}.$$
Note that every point in $X$ is isolated, and hence $X \subseteq \ell^2$ is closed, and hence a Polish space in its own right. If we have distinct $\frac{n + 1}{2n} e_n$ and $\frac{m + 1}{2m} e_m$ in $C$, then
$$\left\|\frac{n + 1}{4n} e_n - \frac{m + 1}{4m} e_m\right\|^2 = \left(\frac{n + 1}{4n}\right)^2 + \left(\frac{m + 1}{4m}\right)^2 \le \frac{1}{2} + \frac{1}{2} = 1,$$
but
$$\left\|\frac{n + 1}{4n} e_n - 2e_1\right\|^2 = \left(\frac{n + 1}{4n}\right)^2 + 4 \ge 4.$$
Therefore, $C$ is the closed unit ball in $X$, centred at any point in $C$. We can now show that $2e_1$ has no closest point, i.e. the projection map simply does not extend to this point in $X$. We see that
$$\left\|\frac{n + 1}{4n} e_n - 2e_1\right\|^2 = \left(\frac{n + 1}{4n}\right)^2 + 4  \to \frac{17}{4},$$
while remaining strictly greater than $\frac{17}{4}$ for every $n \ge 2$. Therefore, there is no point in $C$ that achieves the infimal distance of $\frac{\sqrt{17}}{2}$ to any unit ball centred in $C$.


text:
Q: mapping values are not allowed in salt I got
        Rendering SLS 'base:nginx' failed: mapping values are not allowed here; line 6
when I run this code in ansible.
parent_dict = [{'nginx-1.13.2.tar.gz':'https://nginx.org/download/nginx-1.13.2.tar.gz'},{'zlib-1.2.11.tar.gz':'https://www.zlib.net/zlib-1.2.11.tar.gz'}]

{% for dict_item in parent_dict %}
   {% for key, value in dict_item.items() %}
  install-zlib:
    cmd.run:
      - name: |
          cd /tmp
          curl -L  {{ value }} -o {{ key }}
          tar xzf {{ key }}
          rm -rf {{ key }}
      - creates: /tmp/{{ key }}
   {% endfor %}
{% endfor %}

A: A few things of note:

*

*The assignment to parent_dict isn't enclosed in Jinja2's delimiters {% and %}.

*There is an unnecessary indentation of 2 spaces before the entire block of install-zlib, which may make it an invalid YAML if you have any other YAML content in the same template with a different indentation.

*With your loop iterated twice, you will end up with duplicating ID of install-zlib. You should make it install-{{ key }} instead.

The error message "mapping values are not allowed here" itself is from the YAML parser, which usually indicates that you are using a colon in unexpected places, which I don't see here, but could be the case since it's apparent that you did not simply copy and paste your code here, or you'd be reporting a different error of parent_dict being undefined due to the issue #1 above.


text:
Q: How to fill combobox with Datatable column C# I'm trying to add items to a combo box using a data table that already has some columns but I just want one of them values into the combo box. What i'm doing is this:
cbReviewers.DataSource = Reviewers_table.Columns[1];

but is not working, do you know how could I do it?

A: I think you need to use Display and Value members properties to work with display data.
cbReviewers.DataSource = Reviewers_table
cbReviewers.DisplayMember = "ColumnNameThatContainsText"
cbReviewers.ValueMember = "ColumnNameThatContainsValue"


text:
Q: Example calculation of estimating GMM parameters using EM I'm trying to study expectation maximization and I've almost got the idea. What I'm missing is a concrete example. Could someone familiar with the subject give me a concrete example how one would apply expectation maximization algorithm for Gaussian mixture models?
I have tried to google for examples, but it seems to be difficult to find a good one. Could you show all the theoretical steps and then apply the steps with a numerical example? You don't need to repeat the algorithm for many iterations, one is enough :)
If this question is too long to answer might someone give me references where I could find a good and clear examples?
Thnx for any help!

A: This is a quick reference to mixture models and EM: it is helpful to fix notation and it describes the link between EM and k-means.
Here, at paragraph 4 you can find an example involving Gaussian mixtures with some computations involving sampling and subsequent outcome analysis.
If you are interested also in generalized linear mixture models, please have a look at  chapter 3 of this book: there is a description of likelihood inference via EM, numerical simulations and sampling.


text:
Q: Unable to insert data into Database using Flask I tried using Flask and SQLite. The python code is given below. When the code is executed. It accepts one request and successfully inserts it and throws error for the rest of the requests.
I tried the SQLite code like this
def insertData(name, email, phone, college):
    conn = sqlite3.connect('connect.sqlite')
    cursor = conn.cursor()
    cursor.execute('''INSERT INTO user ('Name','Email','MobileNumber','College') VALUES(?,?,?,?)''', (name, email, phone, college))
    conn.commit()
    cursor.close()

insertDate("A", "a@gmail.com", "9999999999", "ABC")
insertDate("B", "b@gmail.com", "9999999998", "DEF")
insertDate("C", "c@gmail.com", "9999999997", "GHI")

and it successfully inserted 3 records but same using flask is not woking.
This is the actual code for flask
Python Code
from flask import Flask
from flask import request
import sqlite3, json
import wsgiserver

app = Flask(__name__)

@app.route('/connect/register', methods=['POST'])
def register():
    name = request.form.get('name')
    college = request.form.get('college')
    email = request.form.get('email')
    phone = request.form.get('phone')
    conn = sqlite3.connect('connect.sqlite')
    cursor = conn.cursor()
    cursor.execute('''INSERT INTO user ('Name','Email','MobileNumber','College') VALUES(?,?,?,?)''', (name, email, phone, college))
    conn.commit()
    cursor.close()
    return json.dumps(request.form)

if __name__ == '__main__':
    app.run(host='192.168.0.2',port=8080,debug=True)

Error
Traceback (most recent call last):
  File "/Users/debugger24/anaconda/lib/python3.5/site-packages/flask/app.py", line 2000, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/debugger24/anaconda/lib/python3.5/site-packages/flask/app.py", line 1991, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/Users/debugger24/anaconda/lib/python3.5/site-packages/flask/app.py", line 1567, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/debugger24/anaconda/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/Users/debugger24/anaconda/lib/python3.5/site-packages/flask/app.py", line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/debugger24/anaconda/lib/python3.5/site-packages/flask/app.py", line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/debugger24/anaconda/lib/python3.5/site-packages/flask/app.py", line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/debugger24/anaconda/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/Users/debugger24/anaconda/lib/python3.5/site-packages/flask/app.py", line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/debugger24/anaconda/lib/python3.5/site-packages/flask/app.py", line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/debugger24/Development/ConnectAPI/main.py", line 26, in register
    insertDate(name, email, phone, college)
  File "/Users/debugger24/Development/ConnectAPI/main.py", line 15, in insertDate
    cursor.execute('''INSERT INTO user ('Name','Email','MobileNumber','College') VALUES(?,?,?,?)''', (name, email, phone, college))
sqlite3.OperationalError: database is locked

A: You need to close connection object not cursor object, didn't close connection object that's why database is locked.
conn.close() instead of cursor.close()

A: what if just use sqlalchemy? ORM seems easier and clearer to see but also safer
db.session.add(Table(info = info ))
db.session.commit()
i found it easier than using cursor and all that


text:
Q: How to import cell value to array to insert into a DB or an object? I am working on how to import information from an excel file to different tables in a DB, the problem is that I have implemented the following code, but at the time of executing it I can not see if I have correctly read the information in the cells, now After reading them I want to start categorizing what information interests me, then choose what information I should insert into an object or a DB
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Web;
using System.Text;
using Microsoft.CSharp;
using Microsoft.Office.Interop.Excel;
using System.Linq;
using System.Runtime.InteropServices;

namespace WebApplication2
{
   public class ImportExcel
   {

    public void GetValuesExcel()
    {

        Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(@"C:\Users\JULIO.xlsx");
        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet = xlWorkBook.Sheets[1];
        Microsoft.Office.Interop.Excel.Range xlRange = xlWorkSheet.UsedRange;

        int rowCount = xlRange.Rows.Count;
        int colCount = xlRange.Columns.Count;

        for (int i = 1; i <= rowCount; i++)
        {
            for (int j = 1; j <= colCount; j++)
            {
                //new line
                if (j == 1)
                    Console.Write("\r\n");

                //write the value to the console
                if (xlRange.Cells[i, j] != null)
                    Console.Write(xlRange.Cells[i, j].ToString() + "\t");
            }
        }

        //cleanup
        GC.Collect();
        GC.WaitForPendingFinalizers();

        //rule of thumb for releasing com objects:
        //  never use two dots, all COM objects must be referenced and released individually
        //  ex: [somthing].[something].[something] is bad

        //release com objects to fully kill excel process from running in the background
        Marshal.ReleaseComObject(xlRange);
        Marshal.ReleaseComObject(xlWorkSheet);

        //close and release
        xlWorkBook.Close();
        Marshal.ReleaseComObject(xlWorkBook);

        //quit and release
        xlApp.Quit();
        Marshal.ReleaseComObject(xlApp);
    }

    public void Main(string[] args)
    {
        GetValuesExcel();

    }
   }
 }

The excel table contains the following rows:

*

*Package

*Number

*Username

*Creation

*date

*cost

*Departure date

*Arrival date


text: Q: Gatling: How can I eliminate the adding of the timestamp to the name of output folder? I would a specific name to the output directory of my gatling test without timestamp. I use maven method. Help please.


text:
Q: git commit gives error: empty commit set passed When trying to revert to a previous commit, I tried:
git revert --no-commit 0766c053..HEAD

However this gave an error:
empty commit set passed

Question: What does the error mean, and what went wrong with the revert command?

A: It seems to me that you misused the double dot annotation to specify a commit range.
So your range doesn't return any commits which means that revert can't do anything, since you effictively said "revert no commits".
The gitpro book explains the double dot annotation (link to chapter) pretty solid:

The most common range specification is the double-dot syntax. This basically asks Git to resolve a range of commits that are reachable from one commit but aren't reachable from another. For example, say you have a commit history that looks like Figure 6-1.

You want to see what is in your experiment branch that hasn't yet been merged into your master branch. You can ask Git to show you a log of just those commits with master..experiment — that means "all commits reachable by experiment that aren't reachable by master." For the sake of brevity and clarity in these examples, I'll use the letters of the commit objects from the diagram in place of the actual log output in the order that they would display:
$ git log master..experiment
D
C
If, on the other hand, you want to see the opposite — all commits in master that aren't in experiment — you can reverse the branch names. experiment..master shows you everything in master not reachable from experiment:
$ git log experiment..master
F
E

A: Remove the ..HEAD part. At least on my system (git v2.7.4) this resolved the issue.

git revert --no-commit 0766c053


text:
Q: How does Line Of Sight work? I'm a little confused by how the LOS system works. On a few occasions I've had my units be attacked when I thought they should be hidden from the enemy. I do not mean just in Full Cover since I understand that doesn't confirm complete protection. I'm talking about instances where my units are on the other side of a raised area that should have entirely blocked sight.
One notable occasion had an alien attack one of my units when a fountain stood between them, along with two or three steps upwards making the fountain area a very high section.
Are there any tools, options or recommendations on how to better judge my troops visibility?

A: The following correct information to the best of my knowledge, but is generally based on my own gameplay experience and memory, and not backed with SCIENCE (TM). I'm happy to correct any errors noted in comments.
General Line of Sight and Cover
This Image (it's large) provides a great guide to cover and it's effects on line of sight(LOS). I found it via reddit, but I'm not sure of it's original source.
Based on my experience, low cover doesn't block line of sight, and high cover does block line of sight. However, it's important to note that if your unit is peeking around the edge of a piece of high cover, the enemy can see them peeking out, and can still establish a line of sight, even though most of your unit is behind high cover.
When thinking about cover and line of sight, it's important to consider that your soldiers are "active" at all times, looking over their shoulders, peeking out from cover, sometimes even automatically sidestepping a space to take a better shot. Being active in such a way allows your units to maintain a 360 degree line of sight, but also exposes them to enemy fire. Your unit may be in cover, but they're peeking out from it constantly to maintain line of sight on the enemy, and that gives the enemy a line of sight on your soldier.
A good rule of thumb is, if you can see your enemy, there's some kind of line of sight between him and you. If you're being shot at from within the fog of war, then I'm not sure what's going on there. I've only seen that happen when I'm hunkered down (which reduces a unit's line of sight).
Unfortunately, when all your soldiers are bunched together, it's hard to know which particular soldier is giving you visibility on any particular square. The game doesn't provide any way to determine a soldier's individual LOS when multiple soldiers have overlapping fields of view.
The Hill Scenario
For the "Hill Scenario" you described, here's what I'm imagining (side view from ground)
        __+__
  _____|FFFFF|_____
S|HHHHHHHHHHHHHHHHH|X

H: Hill (terrain)
F: Fountain (cover object)
S: Soldier
X: X-Ray

Let's assume that the fountain is a half-cover object for now. In the above section, we assume that half-cover doesn't affect line of sight. This should always be true on flat ground. However, in three dimensions, the relevant question seems to be, "if the terrain is a half-step up, and the fountain is a piece of half-cover, shouldn't that equal full cover, and block line of sight?" The image I linked to above does not address this scenario.
Realistically, line of sight should probably be blocked in this scenario. However, you got shot, so it obviously wasn't.
I'd theorize that the game simply treats low cover objects as not blocking line of sight, and doesn't actually calculate total "height" of cover.
If this is the case, we can completely disregard the fountain (pretend it's invisible and immaterial). This means that the elevation of the Hill would be the key to determining LOS.
If the side of the hill is the height of low cover, then there would still be line of sight across the hill, when ignoring the fountain.
If the hill is the height of full cover, then I feel like it should block line of sight, and this is probably a bug. I could see a possible argument that the soldier could be actively peeking his head out over the hill, creating a LOS across the hill. However, based on the unit height and animations of the soldiers, it seems like it would be very difficult for one of them to fire over a piece of high cover.
If the hill is higher than a full-cover object, then there should definitely be no line of sight across the hill, even ignoring the fountain.
If the fountain is full-height cover, then it should block LOS between the two units regardless of the hill height.


text:
Q: Simple cube and square sum function won't run (C) Learning C, trying to code a program that outputs the sum of the cube and square of an inputted number.
#include <stdio.h>

main()
{
int a;
scanf("%d",a);
printf("%d",cube(a)+sqr(a));
}

cube(int x)
{
return(x*x*x);
}

sqr(int arg)
{
return(arg*arg);
}

When I run the program it outputs some seemingly random string of numbers after I input a number. Any way to fix it without changing the usage of returns to assign variables?

A: scanf needs a pointer:
scanf("%d",&a);

instead of
scanf("%d",a);

A: int a;
scanf("%d",a);

          ^

must be &a. d conversion specifier for scanf expects a pointer to int argument.

A: You need to define a return type to your functions !
#include <stdio.h>

int main()
{
  int a;
  scanf("%d",a);
  printf("%d",cube(a)+sqr(a));
  return 0;
}

int cube(int x)
{
  return(x*x*x);
}

int sqr(int arg)
{
  return(arg*arg);
}

A: You have not given address of "a" in scanf function.
Please use:
scanf("%d", &a);


text:
Q: Rspec/Capybara - Select Form should trigger Onchange event when testing I'm new to TDD and I actually wrote the code before the tests. The code itself works fine and from the main page the onChange event applies. However, when testing, even though a different option is chosen as the selected option(so the option does change), it seems that the onchange event is not actualled trigger when testing and it stays on the same page.it says expected: "/ctscans/index", got: "/" (using ==)
welcome_spec.rb
require 'spec_helper'

describe "Welcome Page" do
    before {visit root_path}
    subject{page}
        describe "with Ctscan selected" do

            before {select("CT Scan", :from => "procedure")}

            it {should have_select('procedure', :selected => 'CT Scan')}
            it "redirects to" do
                select 'MRI', :from => 'procedure'
                current_path.should == ctscans_index_path
            end
        end

end

views/welcome/index.html.erb
<%=select_tag(:procedure, options_for_select(@paths, :selected => @paths[0]),:onchange => "gotoNewPage()")%>

<script type="text/javascript">
function gotoNewPage() {
        if (document.getElementById('procedure').value){
            window.location.href = document.getElementById('procedure').value;
        }
}
</script>

A: You haven't indicated that the spec needs to use a javascript driver. Try
describe "with Ctscan selected", js: true do ...


text:
Q: How do you manage your Django applications? I just wanted to try to build a project with django. Therefore I have a (basic) question on how to manage such a project. Since I cannot find any guidelines or so on how to split a project into applications.
Let's take a kind of SO as an example. Which applications would you use?
I'd say there should be the applications "users" and "questions". But what if there was a topic system with static articles, too. Maybe they also could receive votes.
How to build the apps structure then? One app for "questions", "votes" and "topics" or just one app "content"?
I have no idea what to do. Maybe it's because I know not very much about Django yet, but I'm interested either...

A: There aren't hard-and-fast rules, but I would say it's better to err on the side of more specialized applications.  Ideally an application should handle just one functional concern: i.e. "tagging" or "commenting" or "auth/auth" or "posts."  This type of design will also help you reuse available open source applications instead of reinventing the wheel (i.e. Django comes with auth and comments apps, django-tagging or django-taggable can almost certainly do what you need, etc).
Generic foreign keys can help you decouple applications such as tagging or commenting that might be applied to models from several other applications.

A: You should try and separate the project in as much applications as possible. For most projects an application will not contain more than 5 models. For example a project like SO would have separate applications for UsersProfiles, Questions, Tags (there's a ready one in django for this), etc. If there was a system with static pages that'd be a separate application too (there are ready ones for this purpose). You should also try and make your applications as generic as possible, so you may reuse them in other projects. There's a good presentation on reusable apps.

A: Just like any set of dependencies... try to find the most useful stand-alone aspects of the project and make those stand-alone apps.  Other Django Apps will have higher level functionality, and reuse the parts of the lowest level apps that you have set up.
In my project,  I have a calendar app with its own Event object in its models.  I also have a carpool database set up, and for the departure time and the duration I use the calendar's Event object right in my RideShare tables. The carpooling database is calendar-aware, and gets all the nice .ics export and calendar views from the calendar app for 'free.'
There are some tricks to getting the Apps reusable, like naming the templates directory: project/app2/templates/app2/index.html.  This lets you refer to app2/index.html from any other app, and get the right template.  I picked that one up looking at the built-in reusable apps in Django itself.  Pinax is a bit of a monster size-wise but it also demonstrates a nice reusable App structure.
If in doubt, forget about reusable apps for now.  Put all your messages and polls in one app and get through one rev.  You'll discover during the process what steps feel unnecessary, and could be broken out as something stand-alone in the future.

A: A good question to ask yourself when deciding whether or not to write an app is "could I use this in another project?".  If you think you could, then consider what it would take to make the application as independent as possible; How can you reduce the dependancies so that the app doesn't rely on anything specific to a particular project.
Some of the ways you can do this are:

*

*Giving each app its own urls.py

*Allowing model types to be passed in as parameters rather than explicitly declaring what models are used in your views.  Generic views use this principle.

*Make your templates easily overridden by having some sort of template_name parameter passed in your urls.py

*Make sure you can do reverse url lookups with your objects and views.  This means naming your views in the urls.py and creating get_absolute_url methods on your models.

*In some cases like Tagging, GenericForeignKeys can be used to associate a model in your app to any other model, regardless of whether it has ForeignKeys "looking back" at it.

A: I'll tell you how I am approaching such question: I usually sit with a sheet of paper and draw the boxes (functionalities) and arrows (interdependencies between functionalities). I am sure there are methodologies or other things that could help you, but my approach usually works for me (YMMV, of course).
Knowing what a site is supposed to be is basic, though. ;)


text:
Q: Ambiguity regarding the definition of 'path' in graph theory While going through the Introductory chapter of 'Graph Theory' by Bondy and Murty, I came across the definition of 'path' that says it's a sequence of vertices in such a way that two vertices are adjacent if they are consecutive in the sequence and non-adjacent otherwise.
However, on different sources I read that a path is just a sequence of vertices in such a way that two vertices are adjacent if consecutive and no vertex is repeated in the sequence.
I'm having trouble solving questions that involve the application of path. Kindly guide me through the correct definition of 'path' and why the definition is different in a standard text such as Bondy and Murty ?

A: The word path is often used in two different contexts:

*

*A path graph is a graph consisting of a sequence of vertices such that two vertices are adjacent in the graph if and only if they are consecutive in the sequence. The notation $P_n$ is often used for a path graph of length $n$. This is what Bondy & Murty describe.

*A path in a graph is a subgraph of a given graph that is isomorphic to a path graph. In other words, one might say there is a path in $G$ of length $n$, and by this we mean $P_n$ is a subgraph of $G$.
The word 'path' is used in both ways, but it's usually clear from context what is meant.

A: Ahh, I think Bondy and Murty mean adjacent in the path if they are consecutive in the sequence, and non-adjacent otherwise.  It's just their way of saying no vertex is repeated; if no vertex is repeated, then two vertices are adjacent in the sequence iff they are consecutive in the sequence.  Conversely, if two vertices manage to be adjacent in a sequence without being consecutive in the sequence, that can only be because a vertex was repeated.  (E.g., in the sequence $(a, b, c, d, b, e)$, the second and fourth elements are adjacent, despite being non-consecutive, only because $b$ is repeated.)
Frankly, I find the no-vertex-repeated statement more intuitive, but the definitions are identical.


text: Q: Mathematics of Quantum Field Theory Edward Witten has stated that QFT is not mathematically rigorous, and that string theory helps us in unifying the forces much better. Can you give me a suitable example in which QFT lacks mathematical rigour?


text:
Q: Can I deploy Cloud Run using Deployment Manager? I'm trying to figure out if I can use Google Deployment Manager to deploy a service to Cloud Run. If not is this on the roadmap?
https://cloud.google.com/deployment-manager/docs/configuration/supported-resource-types


text:
Q: simple_form grouped_select group_method with filtered data Is it possible to filter data of the group_method in a grouped select in simple form??
<%= f.association :user,
                  collection:companies,
                  as: :grouped_select,
                  group_method: :users%>

I just want to be able to insert some of the users not all of them those who are linked to a project another model that i have.

A: It's not possible to filter using simple_form's group_method. Even if it was possible, I would be inefficient. What you need instead is to filter companies, which have only those users who is involved in the project.


text:
Q: How can I make elements on my web page be on opposite sides of their container instead of right next to each other? The words, and buttons are right next to each other to the left. How can I make the words stay on the left and the buttons stay on the right?
The picture of the page is below.
This is a page written in React.
The issue is somewhere in the Accordian.Header container. If you remove it, the elements stay on opposite sides of their container as desired.
    <MainScreen title='Welcome Back Anthony!'>
            <Button style={{ marginLeft: 10, marginBottom: 6 }} size='lg'>
                Create New Note
            </Button>
            {notes.map((note) => (
            <Accordion>
            <Accordion.Item>
                    <Card style={{ margin: 10 }} key={note._id}>
                    <Accordion.Header style={{ width: '100%'}}>
                        <Card.Header style={{ display: 'flex' }}>

                        {note.title}

                    <Button href={`/note/${note._id}`}>Edit</Button>
                    <Button
                    variant='danger'
                    className='mx-2'
                    onClick={() => deleteHandler(note._id)}
                    >
                    Delete
                    </Button>

                </Card.Header>
                </Accordion.Header>
                <Card.Body>
                <Accordion.Body>

                        <Badge variant='success'>
                            Category - {note.category}
                        </Badge>

                            {note.content}

                            Created on - date

                    </Accordion.Body>
                </Card.Body>
                </Card>
            </Accordion.Item>
            </Accordion>
            ))}

    </MainScreen>


text:
Q: Duplicate commits in history after fork I originally forked a repository from github and made many changes to it. In the meantime, the original repository changed and I wanted to merge the changes into my current fork.
I added the original repo as an upstream branch, and performed fetch. When I look at the git log, it seems that all the commits up to my fork (which I expected to be the mutual ancestor) are duplicated (same name but different commit ids).
What could cause this?
How can I merge?

A: The most probable cause is : on the original repo, someone ran a history rewriting command (for example git rebase -i ... or git filter-branch ...), which created commits with identical messages but distinct commit ids.
IMHO, the easiest way to fix this would be : rebase your own commits on top of the new commits.
With this suggestion however, you would rewrite the history of your branch, so you would need to push --force your branch to your fork afterwards.
I will guess that this is ok in your case, but if this is a blocker please add a comment.

Here is a diagram to name commits :
*--*--*--*--A--B--C--X <- fork/master   # the original commit from upstream,
          \           \                 # on which you started your branch
           \           *--*--*--*--Y <- yourbranch
            \
             A'--B'--C'--X'--*--*--Z <- upstream/master

By inspecting the history of your commits and upstream's commit, you should find out rather easily which commit are X and X' in the diagram above.
When you have spotted this commit, you can either :

*

*rebase your branch directly on top of Z

*first rebase your branch on top of X', then on top of Z
With the 2nd way : the first rebase should have much less conflicts, and you would have this intermediate state, where yourbranch is correctly integrated in the new history of upstream.

To rebase a sequence of commits on top of another point : use git rebase --onto :
# to rebase X..yourbranch on top of X' :
git rebase --onto X' X yourbranch

# to rebase X'..yourbranch on top of Z :
git rebase --onto Z X' yourbranch

# obviously, if you want to go with 1. :
git rebase --onto Z X yourbranch


text:
Q: Is `this == &x` the correct way to determine if a pointer (this) and a reference (x) point to the same object? I have a class, and inside this class, a function that takes as argument another instance of the same class. Inside this function I need to do some stuff, but only if the argument passed is not the same instance as the current one. Is the following code the correct way to do this?
class Foo
{
    void Foo::func(Foo &other)
    {
        if (this != &other)
            // do stuff
    }
}

A: Yes, (ptr == &ref) is the correct way of determining whether the pointer and reference are to the same object. (Technically it might fail, if operator& is overloaded, but that's a pretty unlikely situation, and one you'd obviously already be aware of, as the author of the class.)