问:
I want to get the result with multiple mysql db using spring
i want to get the result which are got two different DB using spring-boot but i got the error now Actually i can't find what is wrong..

VO.Dve code

```<code>package com.example.rest.VO;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;

@Entity
@Table(name = "MART")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Dve {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private String USER_ID;
    private Integer ID;

    public String getID() {
        return ID;
    }
}
</code>```

VO.LogVo

```<code>package com.example.rest.VO;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import java.io.Serializable;
import java.sql.Date;
import java.sql.Timestamp;

@Entity
@Table(name = "log")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LogVo {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private String put_date;
    private Integer SCNT;
    private Integer SENT_TOTAL;
    private Integer SCART;
    private Integer ST_TOTAL;
    private Integer Imby_tables_cnt;
    private Integer Alarm;
    private Integer Alert;
    private Integer Watch;
    private Integer TZ;
    private Integer Normal;
    private Integer Rating_sum;

    public Integer getSENT_TOTAL(){
        return SENT_TOTAL;
    }
}
</code>```

RestDbConfig

```<code>package com.example.rest;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement

@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactory",
        basePackages = {"com.example.rest.rec.repo"}
)

public class RestDbConfig {

    @Primary
    @Bean(name = "dataSource")
    @ConfigurationProperties(prefix = "db1.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean
    entityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @Qualifier("dataSource") DataSource dataSource
    )
    {
        return builder.dataSource(dataSource).packages("com.example.rest.rec.domain").persistenceUnit("resystem").build();
        }

        @Primary
        @Bean(name = "trasactionManager")
        public PlatformTransactionManager transactionManager(
            @Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory)
        {
        return new JpaTransactionManager(entityManagerFactory);
        }

}
</code>```

RidDbConfig

```<code>package com.example.rest;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "ridEntityManagerFactory",
        transactionManagerRef = "ridTransactionManager",
        basePackages = {"com.example.rest.rid.repository.repo"}
)

public class RidDbConfig {
    @Bean(name = "ridDataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "ridEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean ridEntityManagerFactory(
            EntityManagerFactoryBuilder builder,
             @Qualifier("ridDataSource") DataSource dataSource
    )
    {
        return builder.dataSource(dataSource).packages("com.example.rest.rid.repository.domain").persistenceUnit("rid").build();
    }

    @Bean(name="ridTransactionManager")
    public PlatformTransactionManager ridTransactionManager(
            @Qualifier("ridEntityManagerFactory")EntityManagerFactory ridEntityManagerFactory
            )
    {
        return new JpaTransactionManager(ridEntityManagerFactory);
    }
}
</code>```

EmpRepository1

```<code>package com.example.rest.rid.repository.repo;
import com.example.rest.VO.LogVo;
import com.example.rest.rid.repository.domain.R1pro;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface EmpRepository1 extends JpaRepository<LogVo, Integer> {

    @Query(value = "select * from dt.log order by put_date DESC limit 1",nativeQuery = true)
    public List<R1pro> findByLimit();
}
</code>```

R1pro

```<code>package com.example.rest.rid.repository.domain;

public interface R1pro {
    String getSENT_TOTAL();
}
</code>```

EmpRepository2

```<code>package com.example.rest.rec.repo;
import com.example.rest.VO.Dve;
import com.example.rest.rec.domain.R2pro;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface EmpRepository2 extends JpaRepository<Dve, String> {

    @Query(value = "SELECT user_id FROM MART limit 1",nativeQuery = true)
    public List<R2pro> findByLimit1();
}
</code>```

R2pro

```<code>package com.example.rest.rec.domain;

public interface R2pro {
    String getUSER_ID();
}
</code>```

EmpController1

```<code>package com.example.rest.controller;

import com.example.rest.rec.repo.EmpRepository2;
import com.example.rest.rid.repository.domain.R1pro;
import com.example.rest.rec.domain.R2pro;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.rest.rid.repository.repo.EmpRepository1;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/emp")

public class EmpController1 {
    @Autowired
    private EmpRepository1 empRepository1;
    private EmpRepository2 empRepository2;

    @Autowired
public EmpController1(EmpRepository1 empRepository, EmpRepository2 empRepository2) {
    this.empRepository1 = empRepository1;
    this.empRepository2 = empRepository2;
}

    @RequestMapping(value="/ee", method = RequestMethod.GET)
    @ResponseBody
    public String getCategoryList() {
        R1pro r1pro = empRepository1.findByLimit();

        return r1pro.getSENT_TOTAL();
    }

    @Autowired
    @RequestMapping(value = "/ef",method = RequestMethod.GET)
    @ResponseBody
    public String getgiem(){
        R2pro r2pro =empRepository2.findByLimit1();

        return r2pro.getUSER_ID();
    }
}
</code>```

Application

```<code>package com.example.rest;
import com.example.rest.rid.repository.repo.EmpRepository1;
import com.example.rest.rec.repo.EmpRepository2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

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

}
</code>```

So when i run the code i got the this error

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'empController1' defined in file [C:\Users\DS-18-D3-023\Desktop\data-migration-new-indicator\springboottutorial\target\classes\com\example\rest\controller\EmpController1.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'empRepository2': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.example.rest.VO.Dve
</code>```

What is wrong..it please teach me

Also the all of the VO is correct columns
when i run the code separate is working very well

all error

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'empController1' defined in file [C:\Users\DS-18-D3-023\Desktop\data-migration-new-indicator\springboottutorial\target\classes\com\example\rest\controller\EmpController1.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'empRepository1': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.example.rest.VO.LogVo
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:732) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:197) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1276) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1133) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:503) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at com.example.rest.Application.main(Application.java:12) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_231]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_231]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_231]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_231]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.0.3.RELEASE.jar:2.0.3.RELEASE] Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'empRepository1': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.example.rest.VO.LogVo
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1708) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:581) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:503) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:818) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:724) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
... 24 common frames omitted Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.example.rest.VO.LogVo
at org.hibernate.metamodel.internal.MetamodelImpl.managedType(MetamodelImpl.java:473) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:73) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:66) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:181) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:119) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:102) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:298) ~[spring-data-commons-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$3(RepositoryFactoryBeanSupport.java:287) ~[spring-data-commons-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.util.Lazy.getNullable(Lazy.java:141) ~[spring-data-commons-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.util.Lazy.get(Lazy.java:63) ~[spring-data-commons-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:290) ~[spring-data-commons-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:102) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1767) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1704) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
... 35 common frames omitted

Process finished with exit code 0
</code>```

答:
Ok, there are some major problems with your code:

1) @Autowired from controller both on fields and constructor - you either use it on fields, either on constructor (I suggest you to use it on the constructor since the controller isn't useful without the repositories) and you need one more parameter EmpRepository1 empRepository1

Solution:

```<code>private EmpRepository1 empRepository1;
private EmpRepository2 empRepository2;

@Autowired
public EmpController1(EmpRepository2 empRepository2, EmpRepository1 empRepository1) {
    this.empRepository1 = empRepository1;
    this.empRepository2 = empRepository2;
}
</code>```

2) @Autowired from public String getgiem() (This is not correct)

Solution: remove the annotation

3) Repository's method return type R2Pro or R1Pro . Once you're extending JpaRepository be aware that the generic interface is JpaRepository<T,ID> and every method expects either void, either T return type.

Solution: change the return type expected in your methods:

ORIGINAL:

```<code>@Query(value = "SELECT user_id FROM MART limit 1",nativeQuery = true)
public List<R2pro> findByLimit1();
</code>```

MODIFIED:

```<code>@Repository
public interface EmpRepository2 extends JpaRepository<Dve, String> {

@Query(value = "SELECT user_id FROM MART limit 1",nativeQuery = true)
public List<Dve> findByLimit1(); // List<Dve> return type.
}
</code>```

And the @Id annotated field type needs to be the same in EmpRepository1 (String)
    ORIGINAL:

```<code>@Query(value = "select * from dt.log order by put_date DESC limit 1",nativeQuery = true)
public List<R1pro> findByLimit();
</code>```

MODIFIED:

```<code>@Repository
public interface EmpRepository1 extends JpaRepository<LogVo, String> {

@Query(value = "select * from dt.log order by put_date DESC limit 1",nativeQuery = true)
public List<LogVo> findByLimit();
}
</code>```

P.S. : You can use non-primitive data types like Integer , Long etc. if your query looks like "SELECT user_id FROM MART limit 1" ( only in case that you don't need the entire object )

e.g. :

```<code>@Query(value = "SELECT user_id FROM MART limit 1",nativeQuery = true)
public List<String> findByLimit1(); // the user_id is of String type
}
</code>```

And once you use limit 1 in your query, it means that you're expecting only one result, not a list. So the List<> isn't necessary.

Body:
i want to get the result which are got two different DB using spring-boot but i got the error now Actually i can't find what is wrong..

VO.Dve code

package com.example.rest.VO;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;

@Entity
@Table(name = "MART")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Dve {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private String USER_ID;
    private Integer ID;

    public String getID() {
        return ID;
    }
}

VO.LogVo

package com.example.rest.VO;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import java.io.Serializable;
import java.sql.Date;
import java.sql.Timestamp;

@Entity
@Table(name = "log")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LogVo {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private String put_date;
    private Integer SCNT;
    private Integer SENT_TOTAL;
    private Integer SCART;
    private Integer ST_TOTAL;
    private Integer Imby_tables_cnt;
    private Integer Alarm;
    private Integer Alert;
    private Integer Watch;
    private Integer TZ;
    private Integer Normal;
    private Integer Rating_sum;

    public Integer getSENT_TOTAL(){
        return SENT_TOTAL;
    }
}

RestDbConfig

package com.example.rest;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement

@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactory",
        basePackages = {"com.example.rest.rec.repo"}
)

public class RestDbConfig {

    @Primary
    @Bean(name = "dataSource")
    @ConfigurationProperties(prefix = "db1.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean
    entityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @Qualifier("dataSource") DataSource dataSource
    )
    {
        return builder.dataSource(dataSource).packages("com.example.rest.rec.domain").persistenceUnit("resystem").build();
        }

        @Primary
        @Bean(name = "trasactionManager")
        public PlatformTransactionManager transactionManager(
            @Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory)
        {
        return new JpaTransactionManager(entityManagerFactory);
        }

}

RidDbConfig

package com.example.rest;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "ridEntityManagerFactory",
        transactionManagerRef = "ridTransactionManager",
        basePackages = {"com.example.rest.rid.repository.repo"}
)

public class RidDbConfig {
    @Bean(name = "ridDataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "ridEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean ridEntityManagerFactory(
            EntityManagerFactoryBuilder builder,
             @Qualifier("ridDataSource") DataSource dataSource
    )
    {
        return builder.dataSource(dataSource).packages("com.example.rest.rid.repository.domain").persistenceUnit("rid").build();
    }

    @Bean(name="ridTransactionManager")
    public PlatformTransactionManager ridTransactionManager(
            @Qualifier("ridEntityManagerFactory")EntityManagerFactory ridEntityManagerFactory
            )
    {
        return new JpaTransactionManager(ridEntityManagerFactory);
    }
}

EmpRepository1

package com.example.rest.rid.repository.repo;
import com.example.rest.VO.LogVo;
import com.example.rest.rid.repository.domain.R1pro;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface EmpRepository1 extends JpaRepository<LogVo, Integer> {

    @Query(value = "select * from dt.log order by put_date DESC limit 1",nativeQuery = true)
    public List<R1pro> findByLimit();
}

R1pro

package com.example.rest.rid.repository.domain;

public interface R1pro {
    String getSENT_TOTAL();
}

EmpRepository2

package com.example.rest.rec.repo;
import com.example.rest.VO.Dve;
import com.example.rest.rec.domain.R2pro;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface EmpRepository2 extends JpaRepository<Dve, String> {

    @Query(value = "SELECT user_id FROM MART limit 1",nativeQuery = true)
    public List<R2pro> findByLimit1();
}

R2pro

package com.example.rest.rec.domain;

public interface R2pro {
    String getUSER_ID();
}

EmpController1

package com.example.rest.controller;

import com.example.rest.rec.repo.EmpRepository2;
import com.example.rest.rid.repository.domain.R1pro;
import com.example.rest.rec.domain.R2pro;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.rest.rid.repository.repo.EmpRepository1;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/emp")

public class EmpController1 {
    @Autowired
    private EmpRepository1 empRepository1;
    private EmpRepository2 empRepository2;

    @Autowired
public EmpController1(EmpRepository1 empRepository, EmpRepository2 empRepository2) {
    this.empRepository1 = empRepository1;
    this.empRepository2 = empRepository2;
}

    @RequestMapping(value="/ee", method = RequestMethod.GET)
    @ResponseBody
    public String getCategoryList() {
        R1pro r1pro = empRepository1.findByLimit();

        return r1pro.getSENT_TOTAL();
    }

    @Autowired
    @RequestMapping(value = "/ef",method = RequestMethod.GET)
    @ResponseBody
    public String getgiem(){
        R2pro r2pro =empRepository2.findByLimit1();

        return r2pro.getUSER_ID();
    }
}

Application

package com.example.rest;
import com.example.rest.rid.repository.repo.EmpRepository1;
import com.example.rest.rec.repo.EmpRepository2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

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

}

So when i run the code i got the this error

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'empController1' defined in file [C:\Users\DS-18-D3-023\Desktop\data-migration-new-indicator\springboottutorial\target\classes\com\example\rest\controller\EmpController1.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'empRepository2': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.example.rest.VO.Dve

What is wrong..it please teach me

Also the all of the VO is correct columns
when i run the code separate is working very well

all error

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'empController1' defined in file [C:\Users\DS-18-D3-023\Desktop\data-migration-new-indicator\springboottutorial\target\classes\com\example\rest\controller\EmpController1.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'empRepository1': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.example.rest.VO.LogVo
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:732) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:197) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1276) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1133) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:503) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at com.example.rest.Application.main(Application.java:12) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_231]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_231]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_231]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_231]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.0.3.RELEASE.jar:2.0.3.RELEASE] Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'empRepository1': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.example.rest.VO.LogVo
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1708) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:581) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:503) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:818) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:724) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
... 24 common frames omitted Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.example.rest.VO.LogVo
at org.hibernate.metamodel.internal.MetamodelImpl.managedType(MetamodelImpl.java:473) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:73) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:66) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:181) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:119) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:102) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:298) ~[spring-data-commons-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$3(RepositoryFactoryBeanSupport.java:287) ~[spring-data-commons-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.util.Lazy.getNullable(Lazy.java:141) ~[spring-data-commons-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.util.Lazy.get(Lazy.java:63) ~[spring-data-commons-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:290) ~[spring-data-commons-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:102) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1767) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1704) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
... 35 common frames omitted

Process finished with exit code 0

Body:
Ok, there are some major problems with your code:

1) @Autowired from controller both on fields and constructor - you either use it on fields, either on constructor (I suggest you to use it on the constructor since the controller isn't useful without the repositories) and you need one more parameter EmpRepository1 empRepository1

Solution:

private EmpRepository1 empRepository1;
private EmpRepository2 empRepository2;

@Autowired
public EmpController1(EmpRepository2 empRepository2, EmpRepository1 empRepository1) {
    this.empRepository1 = empRepository1;
    this.empRepository2 = empRepository2;
}

2) @Autowired from public String getgiem() (This is not correct)

Solution: remove the annotation

3) Repository's method return type R2Pro or R1Pro . Once you're extending JpaRepository be aware that the generic interface is JpaRepository<T,ID> and every method expects either void, either T return type.

Solution: change the return type expected in your methods:

ORIGINAL:

@Query(value = "SELECT user_id FROM MART limit 1",nativeQuery = true)
public List<R2pro> findByLimit1();

MODIFIED:

@Repository
public interface EmpRepository2 extends JpaRepository<Dve, String> {

@Query(value = "SELECT user_id FROM MART limit 1",nativeQuery = true)
public List<Dve> findByLimit1(); // List<Dve> return type.
}

And the @Id annotated field type needs to be the same in EmpRepository1 (String)
    ORIGINAL:

@Query(value = "select * from dt.log order by put_date DESC limit 1",nativeQuery = true)
public List<R1pro> findByLimit();

MODIFIED:

@Repository
public interface EmpRepository1 extends JpaRepository<LogVo, String> {

@Query(value = "select * from dt.log order by put_date DESC limit 1",nativeQuery = true)
public List<LogVo> findByLimit();
}

P.S. : You can use non-primitive data types like Integer , Long etc. if your query looks like "SELECT user_id FROM MART limit 1" ( only in case that you don't need the entire object )

e.g. :

@Query(value = "SELECT user_id FROM MART limit 1",nativeQuery = true)
public List<String> findByLimit1(); // the user_id is of String type
}

And once you use limit 1 in your query, it means that you're expecting only one result, not a list. So the List<> isn't necessary.


来源: stackexchange

问:
How to use a PHP include to print HTML code based on URL filename
I'm trying to write a simple PHP script that uses PHP include to inject HTML based on the filename of the URL.

For example using a PHP include
- if the filename in the URL is dog.html print dog into the html document.
- if the filename in the URL is cat.html print cat into the html document.

This is to inject JSON-LD code for structured data.

I'm able to use PHP includes to print html code without issue, but its getting it to read the filename and print a specific portion of HTML that I can't seem to make work.

答: You can get the filename using __FILE__ constant. It is a pre-built constant in PHP. PHP has some other constant like __DIR__, __CLASS__ etc.

ContentLicense: CC BY-SA 4.0


问:
Refresh only a few lines on Bash Script
So this is my output...

```<code>00-
01-  Wallet : 123456789123465789
02-
03- --------------------
04- Server Stats Update:
05- --------------------
06-  Work Units : 0 (cancelled:0 | completed:0)
07-  Average Complete Time : 0
08-
09- -------------
10- Stats Update:
11- -------------
12-  Work Units : 0 (ondemand:0 | precache:0 | paid:0)
13-  Prize Pool : 0%    -    Earned : 0
14-
</code>```

I need the lines 06,07,12 and 13 to keep refreshing... the only method I found so far is by making a loop and clearing the output every two seconds...

Also I found that printf \033[A could be useful but I couldn't figure how to implement it here...

My code...

```<code>while true: do
  echo -e "\n Wallet : ${Address} \n"
  echo --------------------
  echo Server Stats Update:
  echo --------------------
  echo -e " Work Units : ${ServerOverallWU} (cancelled:${Cancelled} | completed:${Completed}) "
  echo -e " Average Complete Time : ${AvgCompTime} "
  echo
  echo -------------
  echo Stats Update:
  echo -------------
  echo -e " Work Units : ${SaveOverallWU} (ondemand:${SaveOnDemand} | precache:${SavePreCache} | paid:${SavePaidWU}) "
  echo -en " Prize Pool : ${SavePrizePool}%   -    Earned : ${SaveEarned} "
done
</code>```

Ps: Fixed... just put the clear on the right stop and now it runs smooth as butter

答: If you want complete control over your screen, you can probably clear it at the beginning of the script and then use direct cursor addressing to only repaint parts of the screen (i.e. move the cursor to position 1,13; repaint that line to replace it; then move to line 15 and repaint that) but this will be rather ugly and painful in pure Bash. Perhaps you should use a curses wrapper like whiptail to shield you from the details. Maybe see also https://unix.stackexchange.com/questions/155417/a-set-of-libraries-like-ncurses-in-a-shell-script

Title: Refresh only a few lines on Bash Script

Body:
So this is my output...

00-
01-  Wallet : 123456789123465789
02-
03- --------------------
04- Server Stats Update:
05- --------------------
06-  Work Units : 0 (cancelled:0 | completed:0)
07-  Average Complete Time : 0
08-
09- -------------
10- Stats Update:
11- -------------
12-  Work Units : 0 (ondemand:0 | precache:0 | paid:0)
13-  Prize Pool : 0%    -    Earned : 0
14-

I need the lines 06,07,12 and 13 to keep refreshing... the only method I found so far is by making a loop and clearing the output every two seconds...

Also I found that printf \033[A could be useful but I couldn't figure how to implement it here...

My code...

while true: do
  echo -e "\n Wallet : ${Address} \n"
  echo --------------------
  echo Server Stats Update:
  echo --------------------
  echo -e " Work Units : ${ServerOverallWU} (cancelled:${Cancelled} | completed:${Completed}) "
  echo -e " Average Complete Time : ${AvgCompTime} "
  echo
  echo -------------
  echo Stats Update:
  echo -------------
  echo -e " Work Units : ${SaveOverallWU} (ondemand:${SaveOnDemand} | precache:${SavePreCache} | paid:${SavePaidWU}) "
  echo -en " Prize Pool : ${SavePrizePool}%   -    Earned : ${SaveEarned} "
done

Ps: Fixed... just put the clear on the right stop and now it runs smooth as butter


问:
AlertDialog negative button is not handled
I have an alert dialog with 2 buttons, positive an negative.
Positive button's handler works as it should be, but negative button click doesn't invoke its handler.
Doee anybody know what's wrong here? Thank you. </p>

```<code>protected Dialog onCreateDialog(int id)
{
    switch (id)
    {
        case DOWNLOAD_DIALOG_ID:
            return new AlertDialog.Builder(this)
                .setIcon(R.drawable.alert_dialog_icon)
                .setTitle(R.string.download_videos_title_msg)
                .setMessage(R.string.download_videos_main_msg)
                .setPositiveButton(R.string.download_videos_download_btn,
                    _downloadVideoContent)
                .setNegativeButton(R.string.download_videos_ask_later_btn,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id)
                        {
                            Editor prefEditor = PreferenceManager.
                                getDefaultSharedPreferences(_context).edit();
                            prefEditor.putBoolean(DOWNLOAD_DECLINED_FLAG, true);
                            prefEditor.commit();
                        }
                })
                //.setNegativeButton(R.string.download_videos_ask_later_btn,
                //  _cancelDialogListener)
                .create();
    }
    return null;
}
</code>```

答: You probably need to dismiss or cancel dialog as well.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have an alert dialog with 2 buttons, positive an negative.
Positive button's handler works as it should be, but negative button click doesn't invoke its handler.
Doee anybody know what's wrong here? Thank you.

protected Dialog onCreateDialog(int id)
{
    switch (id)
    {
        case DOWNLOAD_DIALOG_ID:
            return new AlertDialog.Builder(this)
                .setIcon(R.drawable.alert_dialog_icon)
                .setTitle(R.string.download_videos_title_msg)
                .setMessage(R.string.download_videos_main_msg)
                .setPositiveButton(R.string.download_videos_download_btn,
                    _downloadVideoContent)
                .setNegativeButton(R.string.download_videos_ask_later_btn,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id)
                        {
                            Editor prefEditor = PreferenceManager.
                                getDefaultSharedPreferences(_context).edit();
                            prefEditor.putBoolean(DOWNLOAD_DECLINED_FLAG, true);
                            prefEditor.commit();
                        }
                })
                //.setNegativeButton(R.string.download_videos_ask_later_btn,
                //  _cancelDialogListener)
                .create();
    }
    return null;
}


问:
Unable to install PySide for python3
```<code>pi@raspberrypi:~/python_code/CANalyzat0r-master $ pip install PySide
Defaulting to user installation because normal site-packages is not writeable
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting PySide
  Using cached PySide-1.2.4.tar.gz (9.3 MB)
    ERROR: Command errored out with exit status 1:
     command: /usr/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-zvgnnffi/PySide/setup.py'"'"'; __file__='"'"'/tmp/pip-install-zvgnnffi/PySide/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-zvgnnffi/PySide/pip-egg-info
         cwd: /tmp/pip-install-zvgnnffi/PySide/
    Complete output (1 lines):
    only these python versions are supported: [(2, 6), (2, 7), (3, 2), (3, 3), (3, 4)]
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
</code>```

答: According to this, Seems that issue is with your python version, Pyside will not be updated for version of python 3.5+. Instead, install Pyside2</p>

Title: Unable to install PySide for python3


问:
How to solve the problem of type error in django?
I am trying to make newsletter working but whenever I enter an email it gives me the following error.

Following error

```<code>TypeError at /
NewsletterUser() got an unexpected keyword argument 'newsletteremail'

newsletteruser = NewsletterUser(newsletteremail=newsletteremail)
</code>```

views.py

```<code>def index(request):
    if request.method == 'POST':
        newsletteremail = request.POST.get('newsletteremail', '')

        newsletteruser = NewsletterUser(newsletteremail=newsletteremail)

        newsletteruser.save()
    return render(request, 'home/index.html')
</code>```

admin.py

```<code>admin.site.register(NewsletterUser)
</code>```

models.py

```<code>class NewsletterUser(models.Model):
    email = models.EmailField()
    date_added = models.DateTimeField(auto_now_add=True)

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

答:
In this line newsletteruser = NewsletterUser(newsletteremail=newsletteremail), you are assigninig request.POST.get('newsletteremail', '') to the db column newsletteremail but there is no column with name newsletteremail in your NewsletterUser model. In your model the field name is email. So the correct way to assigning value will be db_column = some_value. In this case, it will be:

```<code>def index(request):
    if request.method == 'POST':
        newsletteremail = request.POST.get('newsletteremail', '')

        newsletteruser = NewsletterUser(<b>email=newsletteremail</b>)

        newsletteruser.save()
    return render(request, 'home/index.html')
</code>```

Body:
I am trying to make newsletter working but whenever I enter an email it gives me the following error.

Following error

TypeError at /
NewsletterUser() got an unexpected keyword argument 'newsletteremail'

newsletteruser = NewsletterUser(newsletteremail=newsletteremail)

views.py

def index(request):
    if request.method == 'POST':
        newsletteremail = request.POST.get('newsletteremail', '')

        newsletteruser = NewsletterUser(newsletteremail=newsletteremail)

        newsletteruser.save()
    return render(request, 'home/index.html')

admin.py

admin.site.register(NewsletterUser)

models.py

class NewsletterUser(models.Model):
    email = models.EmailField()
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.email

Body:
In this line newsletteruser = NewsletterUser(newsletteremail=newsletteremail), you are assigninig request.POST.get('newsletteremail', '') to the db column newsletteremail but there is no column with name newsletteremail in your NewsletterUser model. In your model the field name is email. So the correct way to assigning value will be db_column = some_value. In this case, it will be:

def index(request):
    if request.method == 'POST':
        newsletteremail = request.POST.get('newsletteremail', '')

        newsletteruser = NewsletterUser(email=newsletteremail)

        newsletteruser.save()
    return render(request, 'home/index.html')


问:
jQuery Datepicker setDate - find next work day in Datepicker 2
In a gravity form I have been able to disable weekends and public holidays from Datepicker 1 (from date) and Datepicker 2 (to date).

In Datepicker 2 we want to select the first workday three days after the date selected in Datepicker 1.

See: http://returatrv.staging.wpengine.com/bestilling-container-borettslag/

If you select feb 17 in cal1, feb 20 is selected in DP2, which is correct.
The setDate is getDate +3 days.

When setDate ends up on a weekend or disabled date, it should jump to the next work-day.
If feb 19 is selected in DP1, feb 24 should be selected in DP2 (first workday).
How can I use the code already in place (line 9-15) to set setDate to the first non-disabled day in the array?

I have a feeling I could reuse the code in

```<code> optionsObj.beforeShowDay = function(date) { ...
</code>```

to change the setDate for DP2.

```<code> set_date.setDate(set_date.getDate() + 3); //check if the result is in disabled days / weekends
</code>```

I would really appreciate som help on this ;)
Although many other questions are similar (like Add days after date is selected excluding weekends and holidays), I have not been able to solve this.

```<code>  gform.addFilter('gform_datepicker_options_pre_init', function(optionsObj,
    formId, fieldId) {

    if (formId == <?php echo $skjemaID; ?> && fieldId == 7) {

     // Disable holidays and weekends from datapickers
     // Could I use this to find first work-day?
     optionsObj.beforeShowDay = function(date) {

     // array of holidays from external json-source
     currentDate = jQuery.datepicker.formatDate('yy-mm-dd', date),
     day = date.getDay();

      return [!(disabledDays.indexOf(currentDate) != -1 || day == 0 ||
        day == 6)];
    };

      optionsObj.minDate = 1;
      optionsObj.onClose = function(dateText, inst) {
        var min_date = $.datepicker.parseDate('dd/mm/yy', dateText),
            set_date = $.datepicker.parseDate('dd/mm/yy', dateText),
            end_date = $.datepicker.parseDate('dd/mm/yy', dateText);

            // set minDate in datepicker 1 to nest day
            min_date.setDate(min_date.getDate() + 1);

            // Find first workday after 3 days
            // Samples of expected behaviour:
            // Select feb 10 in dp1 - show feb 13 in dp2
            // Select feb 12 in dp1 - show feb 17 in dp2
            // Select feb 27 in dp1 - show mar in dp2

            set_date.setDate(set_date.getDate() +3);

            // Check if set_date is in disabledDays or weekend
            // if yes, add a day, check again
            // if not, select set_day in datepicker 2

        $('#input_<?php echo $skjemaID; ?>_8').datepicker('option',
          'minDate', min_date).datepicker('setDate', set_date);
      };
    }
    return optionsObj;
  });
</code>```

Please help me in the right direction; I have been struggling quite some time with this.

答: Yes, use the AddBusinessDays function from the linked "similar question" and replace the call to noWeekendsOrHolidays with your beforeShowDay function. You would also need to pass in the start date instead of using today.

Body:
In a gravity form I have been able to disable weekends and public holidays from Datepicker 1 (from date) and Datepicker 2 (to date).

In Datepicker 2 we want to select the first workday three days after the date selected in Datepicker 1.

See: http://returatrv.staging.wpengine.com/bestilling-container-borettslag/

If you select feb 17 in cal1, feb 20 is selected in DP2, which is correct.
The setDate is getDate +3 days.

When setDate ends up on a weekend or disabled date, it should jump to the next work-day.
If feb 19 is selected in DP1, feb 24 should be selected in DP2 (first workday).
How can I use the code already in place (line 9-15) to set setDate to the first non-disabled day in the array?

I have a feeling I could reuse the code in

 optionsObj.beforeShowDay = function(date) { ...

to change the setDate for DP2.

 set_date.setDate(set_date.getDate() + 3); //check if the result is in disabled days / weekends

I would really appreciate som help on this ;)
Although many other questions are similar (like Add days after date is selected excluding weekends and holidays), I have not been able to solve this.

  gform.addFilter('gform_datepicker_options_pre_init', function(optionsObj,
    formId, fieldId) {

    if (formId == <?php echo $skjemaID; ?> && fieldId == 7) {

     // Disable holidays and weekends from datapickers
     // Could I use this to find first work-day?
     optionsObj.beforeShowDay = function(date) {

     // array of holidays from external json-source
     currentDate = jQuery.datepicker.formatDate('yy-mm-dd', date),
     day = date.getDay();

      return [!(disabledDays.indexOf(currentDate) != -1 || day == 0 ||
        day == 6)];
    };

      optionsObj.minDate = 1;
      optionsObj.onClose = function(dateText, inst) {
        var min_date = $.datepicker.parseDate('dd/mm/yy', dateText),
            set_date = $.datepicker.parseDate('dd/mm/yy', dateText),
            end_date = $.datepicker.parseDate('dd/mm/yy', dateText);

            // set minDate in datepicker 1 to nest day
            min_date.setDate(min_date.getDate() + 1);

            // Find first workday after 3 days
            // Samples of expected behaviour:
            // Select feb 10 in dp1 - show feb 13 in dp2
            // Select feb 12 in dp1 - show feb 17 in dp2
            // Select feb 27 in dp1 - show mar in dp2

            set_date.setDate(set_date.getDate() +3);

            // Check if set_date is in disabledDays or weekend
            // if yes, add a day, check again
            // if not, select set_day in datepicker 2

        $('#input_<?php echo $skjemaID; ?>_8').datepicker('option',
          'minDate', min_date).datepicker('setDate', set_date);
      };
    }
    return optionsObj;
  });

Please help me in the right direction; I have been struggling quite some time with this.


问:
NodeJs is sending empty response
I am using NodeJS and MongoDb as a backend service.I am trying to retrieve distinct data based on condition like I want to get names where order status is pending:

```<code>const coll = client.db("My_db").collection("Orders");
            coll.distinct("name",{order_status:"pending"},(function(err,docs){

                  let output = docs.map(r => ({'name':r.name}));
                  res.send(output);

            }));
</code>```

But it is sending empty array like this:

```<code>[
 {},
 {},
 {},
 {},
 {},
 {}
]
</code>```

Someone please let me know what I am doing wrong.Any help would be appreciated.

THANKS

答:
Because you have specified field as name, you don't need to use r.name, just use r

You can refer to the link, hope this will help you :)

If your MongoDB is above 2.2 and you want to find multiple fields, you can use aggregate

```<code>collection = db.tb;
collection.aggregate([
  {"$group": { "_id": { name: "$name", email: "$email" } } }
]);
</code>```

Title: NodeJs is sending empty response

Body:
I am using NodeJS and MongoDb as a backend service.I am trying to retrieve distinct data based on condition like I want to get names where order status is pending:

const coll = client.db("My_db").collection("Orders");
            coll.distinct("name",{order_status:"pending"},(function(err,docs){

                  let output = docs.map(r => ({'name':r.name}));
                  res.send(output);

            }));

But it is sending empty array like this:

[
 {},
 {},
 {},
 {},
 {},
 {}
]

Someone please let me know what I am doing wrong.Any help would be appreciated.

THANKS

Body:
Because you have specified field as name, you don't need to use r.name, just use r

You can refer to the link, hope this will help you :)

If your MongoDB is above 2.2 and you want to find multiple fields, you can use aggregate

collection = db.tb;
collection.aggregate([
  {"$group": { "_id": { name: "$name", email: "$email" } } }
]);


问:
Select from ENUM in Django
The below is my model,

```<code>class Employee(models.Model):
    name = models.CharField(max_length=100)
    sex = models.PositiveIntegerField(choices=choices(Type))
</code>```

Enum class is

```<code>class Type(Enum):
    Male = 0
    Female = 1
</code>```

Now coming to our main model

```<code>class Tournament(models.Model):
    player_name = models.ForeignKey(Employee)
</code>```

My admin is

```<code>@admin.register(Tournament, site=admin.site)
class TournamentAdmin(admin.ModelAdmin):
    list_display = ('player_name')
</code>```

The requirement is I only want to get Male players in My admin page in the field player_name.

How to filter from ENUM class to get only male players name in Django admin field.
Please help me. Thank you!

答:
I have done it by overriding formfield_for_foreignkey method in admin. And if you have more fields where the filter needs to be applied, just add more if blocks and filter from related models(by importing the models).

And if there is a ForeignKey relationship, you need to go from child to parent class using __ between the fields of child to parent

```<code>@admin.register(Tournament, site=admin.site)
class TournamentAdmin(admin.ModelAdmin):
    list_display = ('player_name')

    def formfield_for_foreignkey(self,db_field,request,**kwargs):
        if db_field.name == 'player_name':
            kwargs['queryset'] = Employee.objects.filter(type=Type.Male.value)
        return super().formfield_for_foreignkey(db_field,request,**kwargs)
</code>```

Title: Select from ENUM in Django

Body:
The below is my model,

class Employee(models.Model):
    name = models.CharField(max_length=100)
    sex = models.PositiveIntegerField(choices=choices(Type))

Enum class is

class Type(Enum):
    Male = 0
    Female = 1

Now coming to our main model

class Tournament(models.Model):
    player_name = models.ForeignKey(Employee)

My admin is

@admin.register(Tournament, site=admin.site)
class TournamentAdmin(admin.ModelAdmin):
    list_display = ('player_name')

The requirement is I only want to get Male players in My admin page in the field player_name.

How to filter from ENUM class to get only male players name in Django admin field.
Please help me. Thank you!

Body:
I have done it by overriding formfield_for_foreignkey method in admin. And if you have more fields where the filter needs to be applied, just add more if blocks and filter from related models(by importing the models).

And if there is a ForeignKey relationship, you need to go from child to parent class using __ between the fields of child to parent

@admin.register(Tournament, site=admin.site)
class TournamentAdmin(admin.ModelAdmin):
    list_display = ('player_name')

    def formfield_for_foreignkey(self,db_field,request,**kwargs):
        if db_field.name == 'player_name':
            kwargs['queryset'] = Employee.objects.filter(type=Type.Male.value)
        return super().formfield_for_foreignkey(db_field,request,**kwargs)


问:
ImportError when use pycharm profile
The problem

I start a flask app, which works fine when I use "run" or "debug." However, I got the error when use "profile," here is the log message

```<code>In folder C:/Users/Myname/PycharmProjects/ProjectName
"C:\Users\Myname\Anaconda3\envs\ProjectName\python.exe" "C:\Program Files\JetBrains\PyCharm
Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\run_profiler.py" 127.0.0.1 12055 -m flask run
Starting cProfile profiler
Traceback (most recent call last):
Snapshot saved to C:\Users\Myname/.PyCharm2019.2/system\snapshots\ProjectName1.pstat
File "C:\Program Files\JetBrains\PyCharm Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\run_profiler.py", line 173, in <module>
profiler.run(file)
File "C:\Program Files\JetBrains\PyCharm Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\run_profiler.py", line 89, in run
execfile(file, globals, globals)  # execute the script
File "C:\Program Files\JetBrains\PyCharm Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\prof_util.py", line 30, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:\Users\Myname\Anaconda3\envs\ProjectName\lib\site-packages\flask\__init__.py", line 19, in <module>
from . import json
ImportError: attempted relative import with no known parent package
</code>```

What I have tried

I google it and found that it is an old problem.

Can't profile module using relative imports

Pycharm profile is not working

How to reproduce it

If you would like to reproduce it, you can create a flask app using pycharm, and then click "profile."

The default code for flask app is as follows. But I don't think it matters.

```<code>from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

</code>```

The error message can be different due to the change of the flask version or Pycharm version, but the reason is the same: File "xxx\lib\site-packages\flask\__init__.py", line 19, in <module> use relative import and cause the ImportError

My question

My question is, is there a way to make it work? Any hacks or tricks are also appreciated. I just want to use the profile now. Thank you

答:
[New solution]

Thanks to @Masklinn, use -m flask.cli instread of -m flask could solve this problem. However, the configuration in pycharm flask use -m flask by default and I cannot find out a way to modify it. Therefore, I suggest to use pycharm python. The script path should be set to your FLASK_APP, and add -m flask.cli in addtional options.

[Obsolete solution]

One solution is that directly modify the __init__.py to make it work. For example, change

```<code>from . import json
from .app import Flask
</code>```

to

```<code>from flask import json
from flask.app import Flask
</code>```

Title: ImportError when use pycharm profile

Body:
The problem

I start a flask app, which works fine when I use "run" or "debug." However, I got the error when use "profile," here is the log message

In folder C:/Users/Myname/PycharmProjects/ProjectName
"C:\Users\Myname\Anaconda3\envs\ProjectName\python.exe" "C:\Program Files\JetBrains\PyCharm
Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\run_profiler.py" 127.0.0.1 12055 -m flask run
Starting cProfile profiler
Traceback (most recent call last):
Snapshot saved to C:\Users\Myname/.PyCharm2019.2/system\snapshots\ProjectName1.pstat
File "C:\Program Files\JetBrains\PyCharm Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\run_profiler.py", line 173, in <module>
profiler.run(file)
File "C:\Program Files\JetBrains\PyCharm Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\run_profiler.py", line 89, in run
execfile(file, globals, globals)  # execute the script
File "C:\Program Files\JetBrains\PyCharm Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\prof_util.py", line 30, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:\Users\Myname\Anaconda3\envs\ProjectName\lib\site-packages\flask\__init__.py", line 19, in <module>
from . import json
ImportError: attempted relative import with no known parent package

What I have tried

I google it and found that it is an old problem.

Can't profile module using relative imports

Pycharm profile is not working

How to reproduce it

If you would like to reproduce it, you can create a flask app using pycharm, and then click "profile."

The default code for flask app is as follows. But I don't think it matters.

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

The error message can be different due to the change of the flask version or Pycharm version, but the reason is the same: File "xxx\lib\site-packages\flask\__init__.py", line 19, in <module> use relative import and cause the ImportError

My question

My question is, is there a way to make it work? Any hacks or tricks are also appreciated. I just want to use the profile now. Thank you

Body:
[New solution]

Thanks to @Masklinn, use -m flask.cli instread of -m flask could solve this problem. However, the configuration in pycharm flask use -m flask by default and I cannot find out a way to modify it. Therefore, I suggest to use pycharm python. The script path should be set to your FLASK_APP, and add -m flask.cli in addtional options.

[Obsolete solution]

One solution is that directly modify the __init__.py to make it work. For example, change

from . import json
from .app import Flask

to

from flask import json
from flask.app import Flask


问:
Check window for focus-Password Generator C#
For my end of year project I am creating a password generator where you generate a password, then you can choose whether or not you want to store it in a local compact DB(.sdf). I am working on the GUI at the moment. I am creating a strength bar for passwords but the problem is that I can't seem to have it update the strength bar without first moving the slider. Let me show you example of what I am talking about. I was wondering if I could do this with code or with action events. Tell me what you think. Below is some code for the GUI designer. Do you think this is a good idea or would there be a better way? The focus idea came from if the window has focus it would keep checking the options and see if anything has changed. Video: http://youtu.be/ihSeKbsL55M</p>

```<code>namespace PasswordGenerator
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void fileToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void quitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void quitToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void bcopy_Click(object sender, EventArgs e)
        {
            if (passwordGenBox.Text.Length != 0)
            {
                Clipboard.SetText(passwordGenBox.Text);
            }
            else
            {
                MessageBox.Show("No Password Generated.", "Copy Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void bclear_Click(object sender, EventArgs e)
        {
            passwordGenBox.Text = "";
        }

        private void lengthSlider_Scroll(object sender, EventArgs e)
        {
            sliderLength.Text = lengthSlider.Value.ToString();
            int str = lengthSlider.Value;
            bool scheck = symCheck.Checked;
            bool ncheck = numbersCheck.Checked;
            //1-10 no symbols or numbers
            if (str > 0 && str <= 10)
            {
                strLabel.Text = "Week";
            }
            //1-10 symbols no numbers
            if (str > 0 && str <= 10 && scheck == true && ncheck == false)
            {
                strLabel.Text = "Alright";
            }
            //1-10 no symbols but numbers
            if (str > 0 && str <= 10 && scheck == false && ncheck == true)
            {
                strLabel.Text = "Week";
            }
            //1-10 symbols & numbers
            if (str > 0 && str <= 10 && scheck == true && ncheck == true)
            {
                strLabel.Text = "Okay";
            }
        }

        private void bgen_Click(object sender, EventArgs e)
        {
            int pwlength = lengthSlider.Value;
            bool symbols = false;
            bool numbers = false;
            if (symCheck.Checked && numbersCheck.Checked)
            {
                symbols = true;
                numbers = true;
            }
            else if (symCheck.Checked && numbersCheck.Checked == false)
            {
                symbols = true;
                numbers = false;
            }
            else if (symCheck.Checked == false && numbersCheck.Checked)
            {
                symbols = false;
                numbers = true;
            }
            else
            {
                symbols = false;
                numbers = false;
            }
            Generator gen = new Generator(pwlength, symbols, numbers);
        }
    }
}
</code>```

答:
Well, it's quite difficult to understand what you're actually asking here but the reason your ProgressBar isn't updating is that you're not actually telling it to update unless you move the slider.

Notice how you have all your logic for whether the password is "alright, weak or okay" on the Slide event of your "lengthSlider" component. However, nowhere in that code do you set the value of the ProgressBar - that appears to be done on the "bgen_Click" event which I assume is the generate password button?

In order to update the GUI when you operate the individual controls you need to call the appropriate code. I would suggest you put all your logic into meaningful functions and call them as needed.

Personally I'd have something along these lines:

GetPasswordStrengthString(); - check for symbols and numbers checkbox.checked and the length to return an appropriate string for the "strLabel" label.

CalculateStrengthBarLength(); - all your logic to determine the length of the ProgressBar

These would then be called wherever you want them to take effect. For example, on the CheckedChanged event of the symbols and numbers checkboxes as when that changes you want to see it reflected in the ProgressBar.

Body:
For my end of year project I am creating a password generator where you generate a password, then you can choose whether or not you want to store it in a local compact DB(.sdf). I am working on the GUI at the moment. I am creating a strength bar for passwords but the problem is that I can't seem to have it update the strength bar without first moving the slider. Let me show you example of what I am talking about. I was wondering if I could do this with code or with action events. Tell me what you think. Below is some code for the GUI designer. Do you think this is a good idea or would there be a better way? The focus idea came from if the window has focus it would keep checking the options and see if anything has changed. Video: http://youtu.be/ihSeKbsL55M

namespace PasswordGenerator
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void fileToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void quitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void quitToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void bcopy_Click(object sender, EventArgs e)
        {
            if (passwordGenBox.Text.Length != 0)
            {
                Clipboard.SetText(passwordGenBox.Text);
            }
            else
            {
                MessageBox.Show("No Password Generated.", "Copy Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void bclear_Click(object sender, EventArgs e)
        {
            passwordGenBox.Text = "";
        }

        private void lengthSlider_Scroll(object sender, EventArgs e)
        {
            sliderLength.Text = lengthSlider.Value.ToString();
            int str = lengthSlider.Value;
            bool scheck = symCheck.Checked;
            bool ncheck = numbersCheck.Checked;
            //1-10 no symbols or numbers
            if (str > 0 && str <= 10)
            {
                strLabel.Text = "Week";
            }
            //1-10 symbols no numbers
            if (str > 0 && str <= 10 && scheck == true && ncheck == false)
            {
                strLabel.Text = "Alright";
            }
            //1-10 no symbols but numbers
            if (str > 0 && str <= 10 && scheck == false && ncheck == true)
            {
                strLabel.Text = "Week";
            }
            //1-10 symbols & numbers
            if (str > 0 && str <= 10 && scheck == true && ncheck == true)
            {
                strLabel.Text = "Okay";
            }
        }

        private void bgen_Click(object sender, EventArgs e)
        {
            int pwlength = lengthSlider.Value;
            bool symbols = false;
            bool numbers = false;
            if (symCheck.Checked && numbersCheck.Checked)
            {
                symbols = true;
                numbers = true;
            }
            else if (symCheck.Checked && numbersCheck.Checked == false)
            {
                symbols = true;
                numbers = false;
            }
            else if (symCheck.Checked == false && numbersCheck.Checked)
            {
                symbols = false;
                numbers = true;
            }
            else
            {
                symbols = false;
                numbers = false;
            }
            Generator gen = new Generator(pwlength, symbols, numbers);
        }
    }
}


问:
How to compare if source list does not contain any object which is present in destination list using Java 8?
```<code>List<EPosition> has S and P role.
</code>```

For some employee, P role exists but now S does not exists.

So Source will only provide P but not S row in list.

In Database, WE have both P as well as S.
We want to make all S row as NULL (do not delete). So how to compare two lists

```<code> List<EPosition> src; //Fetch from Soap
 List<EPosition> db;//Fetch from DB

 for (EPosition d: db){
   for (Eposition s: src){
     if (s.ID = d.ID){
           //Make it null
     }
   }
 }
 merge later
</code>```

答:
Problem statement: From the problem statement, what I understood is you have two lists (say A and B), where A contains some objects which are also present in B and you want to set this value to null in A using java streams.

Solution: So to do that you need to use the map on stream where each object is mapped to null if you find the object in B  else object itself. To find whether the object is present in B there are two ways :

a. use contains method of the list (this will use equals method of the object in your case Eposition)

```<code>   dbs = dbs.stream()
           .map(db -> return src.contains(db) ? null :db)
           .collect(Collectors.toList());
</code>```

b. simply iterate over second list using stream and find a match of the id using anyMatch function.

```<code>   dbs = dbs.stream()
           .map(db -> return src.stream().anyMatch(sid -> sid.ID.equals(did.ID) ? null :db)
           .collect(Collectors.toList());
</code>```

Body:
List<EPosition> has S and P role.

For some employee, P role exists but now S does not exists.

So Source will only provide P but not S row in list.

In Database, WE have both P as well as S.
We want to make all S row as NULL (do not delete). So how to compare two lists

 List<EPosition> src; //Fetch from Soap
 List<EPosition> db;//Fetch from DB

 for (EPosition d: db){
   for (Eposition s: src){
     if (s.ID = d.ID){
           //Make it null
     }
   }
 }
 merge later

Body:
Problem statement: From the problem statement, what I understood is you have two lists (say A and B), where A contains some objects which are also present in B and you want to set this value to null in A using java streams.

Solution: So to do that you need to use the map on stream where each object is mapped to null if you find the object in B  else object itself. To find whether the object is present in B there are two ways :

a. use contains method of the list (this will use equals method of the object in your case Eposition)

   dbs = dbs.stream()
           .map(db -> return src.contains(db) ? null :db)
           .collect(Collectors.toList());

b. simply iterate over second list using stream and find a match of the id using anyMatch function.

   dbs = dbs.stream()
           .map(db -> return src.stream().anyMatch(sid -> sid.ID.equals(did.ID) ? null :db)
           .collect(Collectors.toList());


问:
the server responded with a status of 403 (Forbidden) angular
When I try to call with this.http.get and @GetMapping I am able to send the call to spring controller,

When I try to change from this.http.get to this.http.post and from  @GetMapping to  @PostMapping I am not able to call the spring controller /api/v1/basicauth method.

As I am having username and password I want to use PostMapping only

My code as below:-

Angular

```<code>var formData: any = new FormData();
formData.append("userName", username);
formData.append("password", password);

let params = new HttpParams();
params = params.append('username', username);
params = params.append('password', password);
return this.http.post<any>('/api/v1/basicauth', { formData }).pipe(map((res) => {
    this.username = username;
    this.password = password;
}));
</code>```

Spring boot:-

```<code>@PostMapping(path = "/basicauth")
public AuthenticationBean helloWorldBean(@RequestBody UserDetails user) {
log.info("Start helloWorldBean method");
</code>```

UserDetails.java

```<code>    public class UserDetails {

        private int userId;
        private String userName;
        private String password;
   }
</code>```

答:
Do not use FormData (Angular) as your controller is accepting @RequestBody

your formData should be something like

```<code>var formData = {"username": username, "password": password};
</code>```

Rest will deserilize automatically it to UserDetails class

Body:
When I try to call with this.http.get and @GetMapping I am able to send the call to spring controller,

When I try to change from this.http.get to this.http.post and from  @GetMapping to  @PostMapping I am not able to call the spring controller /api/v1/basicauth method.

As I am having username and password I want to use PostMapping only

My code as below:-

Angular

var formData: any = new FormData();
formData.append("userName", username);
formData.append("password", password);

let params = new HttpParams();
params = params.append('username', username);
params = params.append('password', password);
return this.http.post<any>('/api/v1/basicauth', { formData }).pipe(map((res) => {
    this.username = username;
    this.password = password;
}));

Spring boot:-

@PostMapping(path = "/basicauth")
public AuthenticationBean helloWorldBean(@RequestBody UserDetails user) {
log.info("Start helloWorldBean method");

UserDetails.java

    public class UserDetails {

        private int userId;
        private String userName;
        private String password;
   }

Body:
Do not use FormData (Angular) as your controller is accepting @RequestBody

your formData should be something like

var formData = {"username": username, "password": password};

Rest will deserilize automatically it to UserDetails class


Title: Pyspark: how to create window over dates

Body:
I want to do calculation on only a specified subset of a dataframe by creating a window that can include a given Date:

df=df.orderBy('Date')
window_row = Window.partitionBy('I1','Id2')
df=df.withColumn('max_Date', when((col('Date')<=target_date),max('Date').over(window_row)))
df=df.withColumn('cum_sum', when((col('Date')==col('max_Date')),sum('Sale').over(window_row)))

When target_date= '2020-01-01', I get the following output:

|I1| Id2|         Date|  Sale|  max_Date|cum_sum|
+--+----+-------------+------+----------+------+
|AA|  B0|   2019-07-01|     1|2020-12-01|   null|
|AA|  B0|   2020-01-01|    23|2020-12-01|   null|
|AA|  B0|   2020-01-01|     2|2020-01-01|   null|
|AA|  B0|   2020-02-01|     0|      null|   null|
|AA|  B0|   2020-12-01|   116|      null|   null|
|BB|  C0|   2019-03-01|     1|2020-03-01|   null|
|BB|  C0|   2019-05-01|    26|2020-03-01|   null|
|BB|  C0|   2020-03-01|     1|      null|   null|
|CC|  B0|   2019-03-01|     8|2019-04-01|   null|
|CC|  B0|   2019-04-01|     1|2019-04-01|      1|

However, the desired output is:

|I1| Id2|         Date|  Sale|  max_Date|cum_sum|
+--+----+-------------+------+----------+------+
|AA|  B0|   2019-07-01|     1|2020-01-01|   null|
|AA|  B0|   2020-01-01|    23|2020-01-01|     25|
|AA|  B0|   2020-01-01|     2|2020-01-01|     25|
|AA|  B0|   2020-02-01|     0|      null|   null|
|AA|  B0|   2020-12-01|   116|      null|   null|
|BB|  C0|   2019-03-01|     1|2019-05-01|   null|
|BB|  C0|   2019-05-01|    26|2019-05-01|     26|
|BB|  C0|   2020-03-01|     1|      null|   null|
|CC|  B0|   2019-03-01|     8|2019-04-01|   null|
|CC|  B0|   2019-04-01|     1|2019-04-01|      1|

How do I implement this in an efficient way?

Body:
This might helpful

>>> w = Window.partitionBy("date")
>>> w_preceding = Window.partitionBy("I1","ID2").orderBy('DATE').rangeBetween(Window.unboundedPreceding, 0)
>>> df=df.withColumn('max_Date', when((col('Date')<=target_date),max('Date').over(w)))
>>> df=df.withColumn('cum_sum', when((col('Date')==col('max_Date')),sum('Sale').over(w_preceding)))
>>> df.show()
+----------+---+---+----+----------+-------+
|      Date| I1|Id2|Sale|  max_Date|cum_sum|
+----------+---+---+----+----------+-------+
|2019-05-01| BB| C0|  26|2019-05-01|   26.0|
|2020-03-01| BB| C0|   1|2020-03-01|   27.0|
|2019-07-01| AA| B0|   1|2019-07-01|    2.0|
|2019-07-01| AA| B0|   1|2019-07-01|    2.0|
|2020-02-01| AA| B0|   0|2020-02-01|    2.0|
|2020-09-01| AA| B0|   0|      null|   null|
|2019-04-01| CC| B0|   1|2019-04-01|    1.0|
+----------+---+---+----+----------+-------+


答:
If you can split the sequence by the elements so you get sth like this:

```<code>lst = ['ATG','ATG','ATG','ATG','ATG','asd','ATG']
</code>```

You can use:

```<code>from itertools import groupby
for a, g in groupby(lst):
    print(a, len(list(g)))

ATG 5
asd 1
ATG 1
</code>```

Title: Largest consecutive number of words

Body:
Consider the following Lavender DNA Sequence:

GCTAAATTTGTTCAGCCAGATGTAGGCTTACAAATCAAGCTGTCCGCTCGGCACGGCCTACACACGTCGTGTAACTACAACAGCTAGTTAATCTGGATATCACCATGACCGAATCATAGATTTCGCCTTAAGGAGCTTTACCATGGCTTGGGATCCAATACTAAGGGCTCGACCTAGGCGAATGAGTTTCAGGTTGGCAATCAGCAACGCTCGCCATCCGGACGACGGCTTACAGTTAGTAGCATAGTACGCGATTTTCGGGAAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCCCGTCAACTCATTCACACCGCATCCTTTCCTGCCACTGTAACTAGTCGACTGGGGAACCTCATCATCCATACTCTCCCACATTATGCCTCCCAACCTTGTTAAGCGTGGCATGCTTGGGATTGCATTGATGCTTCTTGGAGAGGACGCTTTCGTTTTGGAGATTACAGGGATCCAATTTTATCATCGGTTCGACTCCCGTAACGACTTAGCAGTAAGGGTGCTAGTTCCTGGTTAGAATCTTAATAAATCACGTCGCTTGGAGCAAGACAAAGATCGTCGTAATGCCAAGTGCACGACCACCTTCAGACTTGCAGGACCCGTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTCGATAGCTATGCGGTTCAATACAATCTTAACGCAATGCAGCGATGTGGTTTCGTACACTTAGCATAAAACCCCCCACATTAAATCGATGTACCCGCCCTCTTAGACGCCAATTTCAATGCCGAACCTCCGGCGGGTATCTCTGCACTAGGAGAAGTAGCACGTCGCTGTAGCGAACTCCTATCGTGAGATAATTTGTAGAGCTGCTCTTATAATACAATAGCTCAGATGGATTATTCCATGGACATCCCCGTGCGTTGTTTCGAGGATGGTAGGTGGAAATTTTGCCAGACCTCTAGTCTTAAACATGGTTGACGTTATAGGCGCTATCTCTTGCGTCTGGAAGTGTTAATCCGTGAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAACACGCAACTCTGGAGGAGGGCACTGCACTGCAAACTTGCGTAATATCCTTCACCCACACTTGCCTGGCCTCCTTGCTTAAAGCTCTGGCGATGCGATTTTTCGGCCCAGTAGCTGAATAGGTCATGAAATGGGCACCGAACTGGAAAGACCCATATATTCGATACTCACAACTTAATGATAGCGCGATTAAGAGCGACACCAAAAACCAAATTACGTTCACGAACCTTTGAGAGTCAAGGAGACTTAGACCGAATTGAATGATCACTGATGCGCCCGCTGATACTGAGCCTCACCATTAATCGCCGACCAATACGGCGTGTACCGGGCGCGGCCTTGCCGCATAACGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATAGATATCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTACACAGCCCCGTCCTCATTGCTAAGTGCACTGGCAACTGGACCTAAAGATTTTTCGAGTATGGCCCTCGAATCAAGCGCCCACCCAGAAACCTACGAGCCAGTAACCCCAGTAAACAAGCATTAGTGCTATATGCTTGCTGCCCACTAGGACCCTTATGGTTCATACCAGGGTGACGTGTCTTGCGGGCCAAGGATGAACCAGAAGCAAGATCCTTAGATGGACGACTGTCTCATTGCTTAAACTCCACATACCAAAGGGCGCGGTAAACGATAGTTTTAGGTAATGTTAGTCGGATGGTTGTCTGCAGCTACCAATACAGCCTGGCACCCAGGGTCTGAACAATAACGCGTGAGAGCAGCTCTCCCGCGTGTGGTGGATTTGCCGTCTATGAAATTGAGGCTCTTGCAACTATTCGCACTCGGAATGCCCTCATATCTGGTGCCTAGCGGCCTTTGCCCCGTGCCGGTAGGACTAAACTCTACGGATCGTTGACGGATCTCGATGTGGAAGATGGTTATGAAAGATAACAACGCGTGTGCTAATTGATTTAGACAAGTATTGCGGCAGTAAAAGATAATCGGCTGCAGAGTTACGAAAGACTTCCATGCATGGATTCCATTCCTTCTAGTATAGGACCCACTCTGAATACACGTCTTGCGGGCCGATCATCTCCACCGCTGCGGAAGAAAGCAATTAAGAATCTATGCTCATTAAGAGTGCGACTATAATGCGGATCTTACAGTGCTAATGATCAGGACGTCGTCCAAGCAGGCTGCATGCCGAATTTAGCTTACGTCAGGATCAGGCGTTATAGCCTGGGAATCGGACTATGAGGACGCCACGACCTCTGGGAGAAAGCTATATACATTGAGGATCGCGCCATCTTTATGAGACTCAAATGAATCTAGATAGGTAGCATTGCGGACTTGAGTTAGCACATCGGTATTGGAAGGTGAGGGTCCTGCCGCTCGTTCTATGTTCGGTTTATAGTATACAAATAGGTCATCCCGAACGTTGAAGTTAAACTCATGACACGTTGTCGTAATGAAACGGGCCTGTTATTAGGGATACAGACAAAAGGCACAAGCTGGCTTGCACATTAAGGCGCACTAGAGATCCTCACAACCGTTGCCCGCACGGAGGTCGTGTCTAACAGACAGTGAACCAGCCGTATTGGGGTGGATGACCTGAGCTTCTTGGGGCCTGTTGTACACCGCGTGTGGTTCAACTGGTACACATACTACGAATATTCGAAATCATTGTACTGTGCTCTTCGGTGCTACTGACTGTGAGCGAATGCATCCCAATCCCAAACAATGCTTGTGGTAGGAGAATTGAAACTCTCGAAGCCTGGCCCAATGTCATCTACTTTTAACATGTCGGGCCAGGAGTTACGGGCATTGCTTACTTACTTTGCCCCCTTACACCACAGCAGCGCGATTCTTGTTGTAGTAGATTTTATACGACTCGCGAATTAAATGGAACTTGTCTGTCCCATATCGATCGTGTCCATCGTAAGATGAGATTGTAGGAGCATTCGGAAGTCTATGCGGCCCAGGGACTACTACGTTAAATCTGGTCAGACGTGGTTTACAAGGCGTCCCGATCTTCTCAGAACATATGGGAAAGCACTACCGTTCCTTCACGCATACAGTTGTTCGTGCCGAACGAGTAAGCTTGCGACCAGCCCACCCGCTAGGGCTATGCAGCGGGTCATGGCTGGCGCCATACTGTGCGGACAACCCACGCTCTGGCAGAAAGCGTCTTGTGTTTTGTAGTAGCTCCAACGGTTAGACCTTCGATATCTATTCAGAGCGCGAGCGACCACTATTAGACGGCATGTAAACAATGTGTATTTGTTCGGCCCAACCGGTATATGGGTAAGACCGCGAAGGGCCTGCGCGAATACCAGCGTCCAAAAATTCCTCACCCGAGATATGCGGTTAGTACCCCTTGGGTAACGGTCCGCTACGGGTAGCGACGCGAGCCGGCCGCATCGGTTGGAGCCGAGTTGTCGGGCAGGCGAGTAACGTGTGCAATTTGATGGGCCCAAGCCTCCGGCACTATCCACCTCATACATCGACAAAAGCACCAAATATGGGGAAAAGCTGAGCGTCGATATGTACATCTACCCAGGAACCGGCCCGAACATTAGGCGGACGTGAATTTCCGACCTAGGTTCGGCTACATTTCTACGATCCAAGCACACGTGAAGGAGGAGGGGTGTTCCGACCGTAAATGAACGAGGTGCGCAGTGACCCGATGGCGTTTAGCGGATAGCCTTCCTATGCCGGCCTATGCTGTATGGTAGTTGGTTGGTGCCTCCAGAGCCACTGCACCCAATCATAGGGTCTACAGCAGCGTACTTATAAAATTGTACGGGTGACCCATATCCATTACGGGTTGCGACCAGTATAGGAGAGTATAACTGCGTGAACTAATGCGTTATGACGCTTCAGAGTTTGCTCGGGCCCGAGTTCTAGGGCTATAATGTGTTAGGGCGCAAGTATGCCAAGCTAAGATGTGGCGTGCACACTAGGAGTTGTGTTCCTCTGCAAGCAGACACGAGCACTCTGGCAGTAGTTTGACCACACCCGGGTATCACTGCTACTCCATTTCGAACAAGCTATTGGAGCGGACAAAATATGCTACTCAAGAGCATTAGTTATAGGTCTACGAGACAGAAGCAGTTACTGAGTCTGAATATTCGATATAAGTAGGCATGGAGGCGGAGCAAAACAACGTCTGCGATCAATCGTGTTGATGACGTATGGCGACTGGAAGGTAAGGACTATGGCCGGACGGAATGATTCATGTTCTGTTCAAAGCTATATTTCGAAGGGGTATATTAGCGGTCCTACACTTGGTTAGCACCCTCCCCCCTCTGGATCCTGCACTAATTCGAGCTGGCCTCCATCGGTATCAGTCCGGAAGCTCCACTCTCTATCGTAGTCCTAATCAACAGGGTGCCAGTTTGCTCACGTGGAAGTTTGAGGCCCTTTGTGCTCCATAGCCAATCACTAACCATGCACGCGCGACCCACTCTACGTCCAGATCGGCTATAATAGTTGCGCCCGGGACTGGCAGAGTAGACATGTAAGCTAGATAGAGCCCCGACATCGGCCAAGAGATCCTACGCTGCTTCCAGATAATGAGAGACATTCTAGCATTAGACATGCAAGTCGGCAGGGACTCCCCTTATCTAGTAATTTCGATGAATTGGTTTTTCGGCTAGCATCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGACCATGCCGACCTCATCATAGAAGGAATGCTCTAAACTTAGAGTGCTACTAGGAAAACTATTAATCAATGATCGTCCTGCTTACATAGCTGGACGGCGAAAGTTCTTATACTGCGGAGGTTGCTGACGTAGAGTGCGCTGGGTACAGCGGATAAGTTGATCAGGGTGGGGATAGGGTGGCTCACCGTTTATACTCATATAGATTCCTGGCGTCGACGCTGTGACAGGGTCGAGATCGAGGGGGAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGCGGAGCGGAGGGAAAATTATCACCAGAGGGTAGGGGCTCGCGACATTCTATTCAATGCATTTCAAGCTACTTACGTATTTCGGCACAGTGACTACTGCCTGCGCGGCAGCCGTAAGGTTTCCCGTCAATAGGTGGCACGTATCATTGATGAAAGTGTCAGCTAATCATTCAGGCCTTA

and this dictionary

sqc_large_dictionary = ["AGATC","TTTTTTCT","AATG","TCTAG","GATA","TATC","GAAA","TCTG"]

That are the words we have to look for in Lavender's DNA sequence.

The problem is that, for example, I have managed with re and collections to create an algorithm that detects all AATG's (66). But the spec tells me that I should only count the longest consecutive sequence, in this case 43, since the others are watered, but there are 43 AATGs that are one behind the other and that is the number I should take. How could I implement this?

Body:
If you can split the sequence by the elements so you get sth like this:

lst = ['ATG','ATG','ATG','ATG','ATG','asd','ATG']

You can use:

from itertools import groupby
for a, g in groupby(lst):
    print(a, len(list(g)))

ATG 5
asd 1
ATG 1


问:
Decrypting AES GCM with Python without Authentication Tag
I will start with a disclaimer that I am out of my depth here.  A colleague was showing me a decryption routine he wrote with pycryptodomex.  He had an encrypted file, a key, and a nonce (extracted from the file).  He was able to decrypt the file contents in a very straight forward way.

```<code>c = Crypto.Cipher.AES.new(key, AES.MODE_GCM, nonce)
c.decrypt(encrypted_data)
</code>```

You can see a similar implementation in the pycryptodome test for GCM:

```<code>cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)

pt = get_tag_random("plaintext", 16 * 100)
ct = cipher.encrypt(pt)

cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
pt2 = cipher.decrypt(ct)
</code>```

Unfortunately, pycryptdomex is an additional dependency that I would need to carry around and I am looking to avoid this.  I have a base installation of Anaconda, which brings with it the pyCrypto and pyCA/cryptography packages.  It appears that pycryptodomex is a fork of pyCrytpo, which didn't have a stable GCM implementation to begin with.  When I look at the implementation for PyCA/cryptography, it looks straight forward:

```<code>cipher = Cipher(algorithms.AES(key), modes.GCM(nonce), backend=default_backend())
d = cipher.decryptor()
</code>```

But when we want to decrypt content we have to call finalize_with_tag and produce an authentication tag:

```<code>d.update(encrypted_data) + d.finalize_with_tag(tag)
</code>```

Unfortunately, I don't have an authentication tag nor do I know where to find it.  I can't set the value to None as there is a minimum length requirement.  I'm also not sure why I need to produce an authentication tag in the first place for AES GCM decryption with PyCA/Cryptography but I do not need to produce a tag when decrypting with the pycryptodomex.  I'm ultimately looking for clarity on the following:

Is it possible to implement AES/GCM decryption with the Anaconda PyCA/cryptography package if I only have access to the key, nonce, and encrypted data?

Why do I need to provide an authentication tag for decryption with one implementation and not the other?

Is pycryptodomex doing something under the hood to determine the tag?

答:
Apologies as I can't reply to comments.  Is it possible to derive the tag from the decrypted data after decryption?  This PR associated with PyCA/cryptography seems to imply the exact scenario considered here.

According to the GCM spec (section 7.2: “Algorithm for the
  Authenticated Decryption Function”), the tag itself is not needed
  until the ciphertext has been decrypted.

Does calling d.update(encrypted_data) decrypt data successfully and d.finalize() is only needed to verify the integrity of the data?

OwnerDisplayName: kitokys

Body:
I will start with a disclaimer that I am out of my depth here.  A colleague was showing me a decryption routine he wrote with pycryptodomex.  He had an encrypted file, a key, and a nonce (extracted from the file).  He was able to decrypt the file contents in a very straight forward way.

c = Crypto.Cipher.AES.new(key, AES.MODE_GCM, nonce)
c.decrypt(encrypted_data)

You can see a similar implementation in the pycryptodome test for GCM:

cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)

pt = get_tag_random("plaintext", 16 * 100)
ct = cipher.encrypt(pt)

cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
pt2 = cipher.decrypt(ct)

Unfortunately, pycryptdomex is an additional dependency that I would need to carry around and I am looking to avoid this.  I have a base installation of Anaconda, which brings with it the pyCrypto and pyCA/cryptography packages.  It appears that pycryptodomex is a fork of pyCrytpo, which didn't have a stable GCM implementation to begin with.  When I look at the implementation for PyCA/cryptography, it looks straight forward:

cipher = Cipher(algorithms.AES(key), modes.GCM(nonce), backend=default_backend())
d = cipher.decryptor()

But when we want to decrypt content we have to call finalize_with_tag and produce an authentication tag:

d.update(encrypted_data) + d.finalize_with_tag(tag)

Unfortunately, I don't have an authentication tag nor do I know where to find it.  I can't set the value to None as there is a minimum length requirement.  I'm also not sure why I need to produce an authentication tag in the first place for AES GCM decryption with PyCA/Cryptography but I do not need to produce a tag when decrypting with the pycryptodomex.  I'm ultimately looking for clarity on the following:

Is it possible to implement AES/GCM decryption with the Anaconda PyCA/cryptography package if I only have access to the key, nonce, and encrypted data?

Why do I need to provide an authentication tag for decryption with one implementation and not the other?

Is pycryptodomex doing something under the hood to determine the tag?