问:
Golang X509 certificate how to marshal target information extension
I want to add to X509 certificate id-ce-targetingInformation extension with several strings identifying cert targets. This strings represents targets IDs.
I've found OID of extension {2, 5, 29, 55}
According to spec it have format below:

```<code>    targetingInformation EXTENSION ::= {
SYNTAX SEQUENCE SIZE (1..MAX) OF Targets
IDENTIFIED BY id-ce-targetingInformation }
Targets ::= SEQUENCE SIZE (1..MAX) OF Target
Target ::= CHOICE {
targetName [0] GeneralName,
targetGroup [1] GeneralName,
targetCert [2] TargetCert,
}

</code>```

I add extension in such way

```<code>targets := []string{"targetID1", "targetID2"}
asn1Bytes, err := asn1.Marshal(targets)
extraExtensions:=[]pkix.Extension{
            pkix.Extension{
                Id:       asn1.ObjectIdentifier{2, 5, 29, 55},
                Critical: true,
                Value:    asn1Bytes,
            },
        }
</code>```

But I feel that Value field should be marshaled in another way.
How properly (according to spec) generate value field of extension?

答:
I don't see a lot of documentation about this. But this should help.

```<code>    oidExtensionExtendedKeyUsage      := []int{2, 5, 29, 37}
    oidExtKeyUsageClientAuth                    := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
    usages := []asn1.ObjectIdentifier{oidExtKeyUsageClientAuth}
    marshalledUsages, err := asn1.Marshal(usages)
    if err != nil {
        fmt.Printf("%v", err)
        return
    }
    template := x509.CertificateRequest{
        Subject:            subj,
        Version:            3,
        SignatureAlgorithm: x509.SHA256WithRSA,
        ExtraExtensions: []pkix.Extension{
            {
                Id: oidExtensionExtendedKeyUsage,
                Critical: false,
                Value:  marshalledUsages,
            },
        },
        IPAddresses: []net.IP {
            net.IPv4(8,8,8,8),
        },
    }

    csrBytes, _ := x509.CreateCertificateRequest(rand.Reader, &template, keyBytes)
    pem.Encode(os.Stdout, &pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrBytes})
</code>```

The output

```<code>Certificate Request:
    Data:
        Version: 0 (0x0)
        Subject: C=AU, ST=Some-State, L=MyCity1, O=Company Ltd, OU=IT, CN=example.com/emailAddress=test@example.com
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (1024 bit)
                Modulus:
                    00:e5:12:aa:05:91:bf:3a:cf:84:33:f1:88:65:85:
                    09:32:b7:8c:ef:47:1e:71:c7:12:2e:d8:02:62:39:
                    01:b7:90:db:66:fd:12:22:55:32:26:fc:4f:a2:e0:
                    10:70:ec:46:51:62:aa:2c:e5:a7:87:61:94:3d:5a:
                    5b:cc:08:b8:0c:c1:ab:98:d9:9b:91:f0:ba:b9:65:
                    57:49:58:8b:25:77:71:3b:5a:53:4e:0f:0e:4a:bc:
                    77:71:6f:82:20:ee:19:25:7a:31:b3:91:aa:32:c7:
                    b8:78:cd:95:8b:d0:0e:32:9e:89:a1:8d:6c:d9:2e:
                    8a:ed:12:d4:c3:2b:25:0b:73
                Exponent: 65537 (0x10001)
        Attributes:
        Requested Extensions:
            X509v3 Subject Alternative Name:
                IP Address:8.8.8.8
            X509v3 Extended Key Usage:
                TLS Web Client Authentication
    Signature Algorithm: sha256WithRSAEncryption
         81:0d:48:4c:e1:d1:59:27:76:53:46:18:93:11:c7:e1:27:0b:
         65:83:72:f5:f4:b6:e0:05:13:6a:80:08:4e:aa:cf:2b:57:69:
         85:73:c6:3f:d5:2a:47:06:16:2d:23:2b:64:2f:b5:7f:87:15:
         9b:23:3a:79:5a:38:98:97:49:a8:38:82:ab:57:e6:69:f0:c8:
         09:49:a0:2e:7a:f6:d7:21:6c:9c:20:f9:8d:88:8e:5c:30:62:
         9b:1b:a2:33:eb:a9:01:a7:de:b0:f0:1d:1a:cb:6b:99:93:4b:
         dd:31:66:61:87:aa:07:4a:88:fa:f3:04:36:33:ec:0e:1c:7a:
         41:99
</code>```

Body:
I want to add to X509 certificate id-ce-targetingInformation extension with several strings identifying cert targets. This strings represents targets IDs.
I've found OID of extension {2, 5, 29, 55}
According to spec it have format below:

    targetingInformation EXTENSION ::= {
SYNTAX SEQUENCE SIZE (1..MAX) OF Targets
IDENTIFIED BY id-ce-targetingInformation }
Targets ::= SEQUENCE SIZE (1..MAX) OF Target
Target ::= CHOICE {
targetName [0] GeneralName,
targetGroup [1] GeneralName,
targetCert [2] TargetCert,
}

I add extension in such way

targets := []string{"targetID1", "targetID2"}
asn1Bytes, err := asn1.Marshal(targets)
extraExtensions:=[]pkix.Extension{
            pkix.Extension{
                Id:       asn1.ObjectIdentifier{2, 5, 29, 55},
                Critical: true,
                Value:    asn1Bytes,
            },
        }

But I feel that Value field should be marshaled in another way.
How properly (according to spec) generate value field of extension?

Body:
I don't see a lot of documentation about this. But this should help.

    oidExtensionExtendedKeyUsage      := []int{2, 5, 29, 37}
    oidExtKeyUsageClientAuth                    := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
    usages := []asn1.ObjectIdentifier{oidExtKeyUsageClientAuth}
    marshalledUsages, err := asn1.Marshal(usages)
    if err != nil {
        fmt.Printf("%v", err)
        return
    }
    template := x509.CertificateRequest{
        Subject:            subj,
        Version:            3,
        SignatureAlgorithm: x509.SHA256WithRSA,
        ExtraExtensions: []pkix.Extension{
            {
                Id: oidExtensionExtendedKeyUsage,
                Critical: false,
                Value:  marshalledUsages,
            },
        },
        IPAddresses: []net.IP {
            net.IPv4(8,8,8,8),
        },
    }

    csrBytes, _ := x509.CreateCertificateRequest(rand.Reader, &template, keyBytes)
    pem.Encode(os.Stdout, &pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrBytes})

The output

Certificate Request:
    Data:
        Version: 0 (0x0)
        Subject: C=AU, ST=Some-State, L=MyCity1, O=Company Ltd, OU=IT, CN=example.com/emailAddress=test@example.com
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (1024 bit)
                Modulus:
                    00:e5:12:aa:05:91:bf:3a:cf:84:33:f1:88:65:85:
                    09:32:b7:8c:ef:47:1e:71:c7:12:2e:d8:02:62:39:
                    01:b7:90:db:66:fd:12:22:55:32:26:fc:4f:a2:e0:
                    10:70:ec:46:51:62:aa:2c:e5:a7:87:61:94:3d:5a:
                    5b:cc:08:b8:0c:c1:ab:98:d9:9b:91:f0:ba:b9:65:
                    57:49:58:8b:25:77:71:3b:5a:53:4e:0f:0e:4a:bc:
                    77:71:6f:82:20:ee:19:25:7a:31:b3:91:aa:32:c7:
                    b8:78:cd:95:8b:d0:0e:32:9e:89:a1:8d:6c:d9:2e:
                    8a:ed:12:d4:c3:2b:25:0b:73
                Exponent: 65537 (0x10001)
        Attributes:
        Requested Extensions:
            X509v3 Subject Alternative Name:
                IP Address:8.8.8.8
            X509v3 Extended Key Usage:
                TLS Web Client Authentication
    Signature Algorithm: sha256WithRSAEncryption
         81:0d:48:4c:e1:d1:59:27:76:53:46:18:93:11:c7:e1:27:0b:
         65:83:72:f5:f4:b6:e0:05:13:6a:80:08:4e:aa:cf:2b:57:69:
         85:73:c6:3f:d5:2a:47:06:16:2d:23:2b:64:2f:b5:7f:87:15:
         9b:23:3a:79:5a:38:98:97:49:a8:38:82:ab:57:e6:69:f0:c8:
         09:49:a0:2e:7a:f6:d7:21:6c:9c:20:f9:8d:88:8e:5c:30:62:
         9b:1b:a2:33:eb:a9:01:a7:de:b0:f0:1d:1a:cb:6b:99:93:4b:
         dd:31:66:61:87:aa:07:4a:88:fa:f3:04:36:33:ec:0e:1c:7a:
         41:99


来源: stackexchange

问:
How to revert Status Bar to its default values after using AnnotatedRegion?
On initial screens, I am using AnnotatedRegion to change color of Status Bar to white.

AnnotatedRegion<SystemUiOverlayStyle>(
  value: SystemUiOverlayStyle.light.copyWith(statusBarColor: Colors.white),
  child: ...
)
```

<p>The above code changes status bar color to white but it also affects other screens in the app where I am not using <code>AnnotatedRegion</code>, now the status bar of all of them is white so how do I revert it back the default values on those specific screens.</p>

<p>Saw something like below on some other stack overflow answers but they don't work in my case:</p>

<pre class="lang-dart prettyprint-override"><code>SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values);
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
</code>```

So how I can bring the status bar back with default behavior, i.e it automatically has a bit of dark color than whatever color the app bar is?

答:
Wrap every screen in AnnotatedRegion<SystemUiOverlayStyle>

If you already has AppBar on every screen you should configure it's brightness

AppBar itself wraps content in AnnotatedRegion and sets it's value: overlayStyle this way

```<code>final Brightness brightness = widget.brightness
  ?? appBarTheme.brightness
  ?? theme.primaryColorBrightness;
final SystemUiOverlayStyle overlayStyle = brightness == Brightness.dark
  ? SystemUiOverlayStyle.light
  : SystemUiOverlayStyle.dark;
</code>```

For first attemp to solve your problem set all your screens AppBar brightness to desired value as in example

Page1:

```<code>Scaffold(appBar: AppBar(brightness: Brightness.dark))
</code>```

Page2:

```<code>Scaffold(appBar: AppBar(brightness: Brightness.light))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
On initial screens, I am using AnnotatedRegion to change color of Status Bar to white.

AnnotatedRegion<SystemUiOverlayStyle>(
  value: SystemUiOverlayStyle.light.copyWith(statusBarColor: Colors.white),
  child: ...
)

The above code changes status bar color to white but it also affects other screens in the app where I am not using AnnotatedRegion, now the status bar of all of them is white so how do I revert it back the default values on those specific screens.

Saw something like below on some other stack overflow answers but they don't work in my case:

SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values);
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);

So how I can bring the status bar back with default behavior, i.e it automatically has a bit of dark color than whatever color the app bar is?

Body:
Wrap every screen in AnnotatedRegion<SystemUiOverlayStyle>

If you already has AppBar on every screen you should configure it's brightness

AppBar itself wraps content in AnnotatedRegion and sets it's value: overlayStyle this way

final Brightness brightness = widget.brightness
  ?? appBarTheme.brightness
  ?? theme.primaryColorBrightness;
final SystemUiOverlayStyle overlayStyle = brightness == Brightness.dark
  ? SystemUiOverlayStyle.light
  : SystemUiOverlayStyle.dark;

For first attemp to solve your problem set all your screens AppBar brightness to desired value as in example

Page1:

Scaffold(appBar: AppBar(brightness: Brightness.dark))

Page2:

Scaffold(appBar: AppBar(brightness: Brightness.light))


问:
Spring boot application with Office 365 authentication
I'm developing an application (spring boot for backend and react for frontend)  with authentication with Office 365. But I want to use my own group and permissions for Users. For instance, when a User access to /api/auth for the first time, I want to retrieve informations from microsoft graph and save it to my DB and then protect my endpoint with my own roles/permissions.

So far I managed to do this :

When i go to localhost:8080 (back) i'm redirect to Azure portal to authenticate. Then, I can access to my endpoints

I can protect my endpoints with my own roles

When i go to localhost:3000 (react app) I have a button that redirect me to the portal and give me an azure access token (thanks to MSAL.js)

So my problem is that I can't validate this azure token in my backend and send a new token from the back to the front to send request (like GET /api/users or POST /api/todos). I think my backend configuration and implementation is wrong but I didn't find a way to validate tokens and return a token for my backend...

I hope I was clear, english isn't my native language

Here is my WebSecurityConfig

```<code>@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests().antMatchers("/**")
                .authenticated()
                .and()
                .csrf().csrfTokenRepository(csrfTokenRepository()).and()
                .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
                .oauth2Login();

    }

    private Filter csrfHeaderFilter() {
        return new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
                CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
                if (csrf != null) {
                    Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                    String token = csrf.getToken();
                    if (cookie == null || token != null && !token.equals(cookie.getValue())) {
                        cookie = new Cookie("XSRF-TOKEN", token);
                        cookie.setPath("/");
                        response.addCookie(cookie);
                    }
                }
                filterChain.doFilter(request, response);
            }
        };
    }

    @Bean
    public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
        StrictHttpFirewall firewall = new StrictHttpFirewall();
        firewall.setAllowUrlEncodedSlash(true);
        return firewall;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
        web.httpFirewall(allowUrlEncodedSlashHttpFirewall());
    }

    private CsrfTokenRepository csrfTokenRepository() {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setHeaderName("X-XSRF-TOKEN");
        return repository;
    }
}
</code>```

And here's how I protect my endpoints :

```<code>@PreAuthorize("hasPermission(#foo, 'write')")
</code>```

The conf :

```<code>@Configuration
public class AclPermissionEvaluator implements PermissionEvaluator {
    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private SecurityService securityService;

    @Override
    public boolean hasPermission(final Authentication authentication, final Object privilegeName, final Object privilegeType) {
        DefaultOidcUser principal = (DefaultOidcUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Map<String, Object> userAttributes = principal.getAttributes();
        UserInfo userInfo = securityService.getUserInfoByLogin((String) userAttributes.get("unique_name"));
        if (userInfo == null || StringUtils.isBlank((CharSequence) privilegeName) || StringUtils.isBlank((CharSequence) privilegeType)) {
            return false;
        }

        for (Permission permission : roleRepository.getByName(userInfo.getRoleName()).getPermissions()) {
            if (permission.getPermission().startsWith((String) privilegeName) || permission.getPermission().equals("*")) {
                return true;
            }
        }

        return false;
    }

    //We don't need an implementation of this function for now
    @Override
    public boolean hasPermission(final Authentication authentication, final Serializable serializable, final String s, final Object o) {
        return false;
    }

}
</code>```

Security Service :

```<code>@Service
@Transactional
public class SecurityServiceImpl implements SecurityService {
  @Autowired private UserRepository userRepo;

  @Autowired
  private RoleRepository roleRepository;

  @Override
  public UserInfo getUserInfoByLogin(String username) {
    User user = userRepo.getUserByUsername(username);
    ModelMapper modelMapper = new ModelMapper();
    return modelMapper.map(user, UserInfo.class);
  }
}
</code>```

RoleRepository :

```<code>@Repository
public interface RoleRepository extends JpaRepository<Role, Long> {
    public Role getByName(String name);
}
</code>```

And on my application.yml :

```<code>spring:
  security:
    oauth2:
      client:
        registration:
          azure:
            clientId: <my-clientId>
            clientSecret: <my-secret>

azure:
  activedirectory:
    tenant-id: <my-tenant-id>
    user-group:
      allowed-groups: all
    active-directory-groups: all
</code>```

答:
you can use similar to the below code

```<code>@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Import(SecurityProblemSupport.class)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final CorsFilter corsFilter;
    private final SecurityProblemSupport problemSupport;
    private final OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService;

    public SecurityConfiguration(CorsFilter corsFilter, SecurityProblemSupport problemSupport, OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService) {
        this.corsFilter = corsFilter;
        this.problemSupport = problemSupport;
        this.oidcUserService = oidcUserService;
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring()
            .antMatchers(HttpMethod.OPTIONS, "/**")
            .antMatchers("/app/**/*.{js,html}")
            .antMatchers("/i18n/**")
            .antMatchers("/content/**")
            .antMatchers("/swagger-ui/index.html")
            .antMatchers("/test/**");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .csrf()
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            .and()
            .addFilterBefore(corsFilter, CsrfFilter.class)
            .exceptionHandling()
            .accessDeniedHandler(problemSupport)
            .and()
            .headers()
            .contentSecurityPolicy("default-src 'self'; frame-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://storage.googleapis.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:")
            .and()
            .referrerPolicy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN)
            .and()
            .featurePolicy("geolocation 'none'; midi 'none'; sync-xhr 'none'; microphone 'none'; camera 'none'; magnetometer 'none'; gyroscope 'none'; speaker 'none'; fullscreen 'self'; payment 'none'")
            .and()
            .frameOptions()
            .deny()
            .and()
            .authorizeRequests()
            .antMatchers("/api/auth-info").permitAll()
            .antMatchers("/api/**").authenticated()
            .antMatchers("/management/health").permitAll()
            .antMatchers("/management/info").permitAll()
            .antMatchers("/management/prometheus").permitAll()
            .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
            .and()
            .oauth2Login()
            .userInfoEndpoint()
            .oidcUserService(oidcUserService);
        // @formatter:on
    }

    /**
     * Map authorities from "groups" or "roles" claim in ID Token.
     *
     * @return a {@link GrantedAuthoritiesMapper} that maps groups from
     * the IdP to Spring Security Authorities.
     */
    @Bean
    public GrantedAuthoritiesMapper userAuthoritiesMapper() {
        return (authorities) -> {
            Set<GrantedAuthority> mappedAuthorities = new HashSet<>();

            authorities.forEach(authority -> {
                mappedAuthorities.addAll(authorities);
            });
            return mappedAuthorities;
        };
    }

}
</code>```

you need to change the userAuthoritiesMapper method to achieve what you looking for

extra configuration

spring security config

```<code>spring:
  security:
    oauth2:
      client:
        registration:
          azure:
            client-id: <<CLIENT_ID>>
            client-secret: <<CLIENT_SECRET>>
</code>```

Azur Active directory config

```<code>azure:
  activedirectory:
    tenant-id: <<YOUR_TENANT_ID>>
    active-directory-groups: Users
  b2c:
    reply-url: http://localhost:9000 # should be absolute url.
    logout-success-url: http://localhost:9000
</code>```

I'll give a secret whenever you stuck in any of the spring boot configurations go and find how jhipster make it

you can find more information by visiting this article posted by jhipster creator

NOTE: SecurityProblemSupport is a library implemented by zalando
finally the code posted copied from this repo

Body:
I'm developing an application (spring boot for backend and react for frontend)  with authentication with Office 365. But I want to use my own group and permissions for Users. For instance, when a User access to /api/auth for the first time, I want to retrieve informations from microsoft graph and save it to my DB and then protect my endpoint with my own roles/permissions.

So far I managed to do this :

When i go to localhost:8080 (back) i'm redirect to Azure portal to authenticate. Then, I can access to my endpoints

I can protect my endpoints with my own roles

When i go to localhost:3000 (react app) I have a button that redirect me to the portal and give me an azure access token (thanks to MSAL.js)

So my problem is that I can't validate this azure token in my backend and send a new token from the back to the front to send request (like GET /api/users or POST /api/todos). I think my backend configuration and implementation is wrong but I didn't find a way to validate tokens and return a token for my backend...

I hope I was clear, english isn't my native language

Here is my WebSecurityConfig

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests().antMatchers("/**")
                .authenticated()
                .and()
                .csrf().csrfTokenRepository(csrfTokenRepository()).and()
                .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
                .oauth2Login();

    }

    private Filter csrfHeaderFilter() {
        return new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
                CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
                if (csrf != null) {
                    Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                    String token = csrf.getToken();
                    if (cookie == null || token != null && !token.equals(cookie.getValue())) {
                        cookie = new Cookie("XSRF-TOKEN", token);
                        cookie.setPath("/");
                        response.addCookie(cookie);
                    }
                }
                filterChain.doFilter(request, response);
            }
        };
    }

    @Bean
    public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
        StrictHttpFirewall firewall = new StrictHttpFirewall();
        firewall.setAllowUrlEncodedSlash(true);
        return firewall;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
        web.httpFirewall(allowUrlEncodedSlashHttpFirewall());
    }

    private CsrfTokenRepository csrfTokenRepository() {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setHeaderName("X-XSRF-TOKEN");
        return repository;
    }
}

And here's how I protect my endpoints :

@PreAuthorize("hasPermission(#foo, 'write')")

The conf :

@Configuration
public class AclPermissionEvaluator implements PermissionEvaluator {
    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private SecurityService securityService;

    @Override
    public boolean hasPermission(final Authentication authentication, final Object privilegeName, final Object privilegeType) {
        DefaultOidcUser principal = (DefaultOidcUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Map<String, Object> userAttributes = principal.getAttributes();
        UserInfo userInfo = securityService.getUserInfoByLogin((String) userAttributes.get("unique_name"));
        if (userInfo == null || StringUtils.isBlank((CharSequence) privilegeName) || StringUtils.isBlank((CharSequence) privilegeType)) {
            return false;
        }

        for (Permission permission : roleRepository.getByName(userInfo.getRoleName()).getPermissions()) {
            if (permission.getPermission().startsWith((String) privilegeName) || permission.getPermission().equals("*")) {
                return true;
            }
        }

        return false;
    }

    //We don't need an implementation of this function for now
    @Override
    public boolean hasPermission(final Authentication authentication, final Serializable serializable, final String s, final Object o) {
        return false;
    }

}

Security Service :

@Service
@Transactional
public class SecurityServiceImpl implements SecurityService {
  @Autowired private UserRepository userRepo;

  @Autowired
  private RoleRepository roleRepository;

  @Override
  public UserInfo getUserInfoByLogin(String username) {
    User user = userRepo.getUserByUsername(username);
    ModelMapper modelMapper = new ModelMapper();
    return modelMapper.map(user, UserInfo.class);
  }
}

RoleRepository :

@Repository
public interface RoleRepository extends JpaRepository<Role, Long> {
    public Role getByName(String name);
}

And on my application.yml :

spring:
  security:
    oauth2:
      client:
        registration:
          azure:
            clientId: <my-clientId>
            clientSecret: <my-secret>

azure:
  activedirectory:
    tenant-id: <my-tenant-id>
    user-group:
      allowed-groups: all
    active-directory-groups: all

Body:
you can use similar to the below code

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Import(SecurityProblemSupport.class)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final CorsFilter corsFilter;
    private final SecurityProblemSupport problemSupport;
    private final OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService;

    public SecurityConfiguration(CorsFilter corsFilter, SecurityProblemSupport problemSupport, OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService) {
        this.corsFilter = corsFilter;
        this.problemSupport = problemSupport;
        this.oidcUserService = oidcUserService;
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring()
            .antMatchers(HttpMethod.OPTIONS, "/**")
            .antMatchers("/app/**/*.{js,html}")
            .antMatchers("/i18n/**")
            .antMatchers("/content/**")
            .antMatchers("/swagger-ui/index.html")
            .antMatchers("/test/**");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .csrf()
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            .and()
            .addFilterBefore(corsFilter, CsrfFilter.class)
            .exceptionHandling()
            .accessDeniedHandler(problemSupport)
            .and()
            .headers()
            .contentSecurityPolicy("default-src 'self'; frame-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://storage.googleapis.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:")
            .and()
            .referrerPolicy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN)
            .and()
            .featurePolicy("geolocation 'none'; midi 'none'; sync-xhr 'none'; microphone 'none'; camera 'none'; magnetometer 'none'; gyroscope 'none'; speaker 'none'; fullscreen 'self'; payment 'none'")
            .and()
            .frameOptions()
            .deny()
            .and()
            .authorizeRequests()
            .antMatchers("/api/auth-info").permitAll()
            .antMatchers("/api/**").authenticated()
            .antMatchers("/management/health").permitAll()
            .antMatchers("/management/info").permitAll()
            .antMatchers("/management/prometheus").permitAll()
            .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
            .and()
            .oauth2Login()
            .userInfoEndpoint()
            .oidcUserService(oidcUserService);
        // @formatter:on
    }

    /**
     * Map authorities from "groups" or "roles" claim in ID Token.
     *
     * @return a {@link GrantedAuthoritiesMapper} that maps groups from
     * the IdP to Spring Security Authorities.
     */
    @Bean
    public GrantedAuthoritiesMapper userAuthoritiesMapper() {
        return (authorities) -> {
            Set<GrantedAuthority> mappedAuthorities = new HashSet<>();

            authorities.forEach(authority -> {
                mappedAuthorities.addAll(authorities);
            });
            return mappedAuthorities;
        };
    }

}

you need to change the userAuthoritiesMapper method to achieve what you looking for

extra configuration

spring security config

spring:
  security:
    oauth2:
      client:
        registration:
          azure:
            client-id: <<CLIENT_ID>>
            client-secret: <<CLIENT_SECRET>>

Azur Active directory config

azure:
  activedirectory:
    tenant-id: <<YOUR_TENANT_ID>>
    active-directory-groups: Users
  b2c:
    reply-url: http://localhost:9000 # should be absolute url.
    logout-success-url: http://localhost:9000

I'll give a secret whenever you stuck in any of the spring boot configurations go and find how jhipster make it

you can find more information by visiting this article posted by jhipster creator

NOTE: SecurityProblemSupport is a library implemented by zalando
finally the code posted copied from this repo


问:
How to save multiple spreadsheets based on all possible values for a cell?
For concreteness, say, a user should enter a value from 1 to 99 in A1 cell of sheet1. Then sheet2 gets recalculated.

How can I generate, ex ante, a collection of all different sheet2 that may arise (with values, don't want the formulas to show)?

答:
If you put (say) 99 in Sheet1 "A1" then Sheet2 will be saved as Sheet2_99.xlsx on desktop (change the path as suitable) with the procedure below in VBA Sheet1 object</p>

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
Application.DisplayAlerts = True
If Not Intersect(Range("A1"), Target) Is Nothing Then
    Sheets("Sheet2").Copy
    ActiveWorkbook.SaveAs Filename:="C:\Users\naresh\Desktop\Sheet2_" & Target.Value & ".xlsx" _
        , FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

    With ActiveSheet.UsedRange
    .Value = .Value
    End With

ActiveWorkbook.Close True
End If

End Sub
</code>```

Body:
If you put (say) 99 in Sheet1 "A1" then Sheet2 will be saved as Sheet2_99.xlsx on desktop (change the path as suitable) with the procedure below in VBA Sheet1 object

Private Sub Worksheet_Change(ByVal Target As Range)
Application.DisplayAlerts = True
If Not Intersect(Range("A1"), Target) Is Nothing Then
    Sheets("Sheet2").Copy
    ActiveWorkbook.SaveAs Filename:="C:\Users\naresh\Desktop\Sheet2_" & Target.Value & ".xlsx" _
        , FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

    With ActiveSheet.UsedRange
    .Value = .Value
    End With

ActiveWorkbook.Close True
End If

End Sub


问:
Use variable holding type as a generic type parameter
Is there any way to use a variable as a generics parameter?

```<code>static triple<T>(x): T[] {
    return [x, x, x]
}

class A {}
let a = A; // variable type is `typeof A`

const instance = new A();

triple<A>(instance); // works
triple<a>(instance); // ERROR: 'a' refers to a value, but is being used as a type here.
</code>```

答: You can't pass to generic real value but you can use typeof a in this case

Body:
Is there any way to use a variable as a generics parameter?

static triple<T>(x): T[] {
    return [x, x, x]
}

class A {}
let a = A; // variable type is `typeof A`

const instance = new A();

triple(instance); // works
triple(instance); // ERROR: 'a' refers to a value, but is being used as a type here.


问:
Usage of DataKeyNames in an ASP.NET GridView?
In which cases should I use a GridView's property DataKeyNames?

Why are multiple columns/fields allowed here?

答:
It keeps the primary key fields or id field of data table, which gridview shows.

According to MSDN

Gets or sets an array that contains
  the names of the primary key fields
  for the items displayed in a GridView
  control.

ContentLicense: CC BY-SA 3.0


问:
HTTP method POST is not supported by this URL Java servlet
Can someone please tell me why i am getting error:HTTP Status 405 – Method Not Allowed ?
I am trying accomplish that after method doPost() ,user will be redirected to "/logout" controller ,where is invalidate session.
It's funny because method is called ,do everything what should do(update user in database), but after send to user error 405.Another  where i use doPost() (for example: LoginController)  working well ,but when i try compere and find bug ,i dont see any :<

```<code><div class="container">
    <div class="col-md-8 col-md-offset-2">
        <form method="post" action="account">
            <div class="form-group">
                <label for="email">Email address</label>
                <input name="email" type="email" class="form-control" id="email"
                       value="${sessionScope.loggedUser.email}" required aria-describedby="emailHelp"
                       placeholder="Enter email">
            </div>
            <div class="form-group">
                <label for="password">Password</label>
                <input name="password" type="password" minlength="5" maxlength="40" required class="form-control"
                       id="password" placeholder="Password">
            </div>
            <div class="form-group">
                <label for="repeatPassword">Repeat Password</label>
                <input name="repeatPassword" type="password" minlength="5" maxlength="40" required class="form-control"
                       id="repeatPassword" placeholder="Password">
            </div>
            <input class="btn btn-lg btn-primary btn-block" type="submit" value="Save changes"/>
        </form>
    </div>
</div>

@WebServlet("/account")
public class AccountController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        String repeatPassword = req.getParameter("repeatPassword");

        if (email == null || password == null || repeatPassword == null) {
            doGet(req, resp);
            return;
        }

        if (password.equals(repeatPassword)) {
            HttpSession session = req.getSession();
            User user = (User) session.getAttribute("loggedUser");
            user.setEmail(email);
            String sha1hexPassword = DigestUtils.sha1Hex(password);
            user.setPassword(sha1hexPassword);
            UserService service = new UserService();

            try {
                service.update(user);
            } catch (UpdateObjectException e) {
                e.printStackTrace();
            }
            req.getRequestDispatcher("/logout").forward(req, resp);
        } else {
            req.setAttribute("errorMessage", "Passwords not the same");
            req.setAttribute("fragment", "account");
            req.getRequestDispatcher("WEB-INF/index.jsp").forward(req, resp);
        }
    }
}
</code>```

Thanks for any hint.

答:
Problem solved. Here:

```<code>req.getRequestDispatcher("/logout").forward(req, resp);
</code>```

i should do

```<code>resp.sendRedirect(req.getContextPath()+"/logout");
</code>```

because in "/logout" i have only doGet() method ,and if i use "getRequestDispatcher()" its try to find doPost() method.

Body:
Can someone please tell me why i am getting error:HTTP Status 405 – Method Not Allowed ?
I am trying accomplish that after method doPost() ,user will be redirected to "/logout" controller ,where is invalidate session.
It's funny because method is called ,do everything what should do(update user in database), but after send to user error 405.Another  where i use doPost() (for example: LoginController)  working well ,but when i try compere and find bug ,i dont see any :<

        <form method="post" action="account">

                Email address
                <input name="email" type="email" class="form-control" id="email"
                       value="${sessionScope.loggedUser.email}" required aria-describedby="emailHelp"
                       placeholder="Enter email">

                Password
                <input name="password" type="password" minlength="5" maxlength="40" required class="form-control"
                       id="password" placeholder="Password">

                Repeat Password
                <input name="repeatPassword" type="password" minlength="5" maxlength="40" required class="form-control"
                       id="repeatPassword" placeholder="Password">

            <input class="btn btn-lg btn-primary btn-block" type="submit" value="Save changes"/>
        </form>

@WebServlet("/account")
public class AccountController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        String repeatPassword = req.getParameter("repeatPassword");

        if (email == null || password == null || repeatPassword == null) {
            doGet(req, resp);
            return;
        }

        if (password.equals(repeatPassword)) {
            HttpSession session = req.getSession();
            User user = (User) session.getAttribute("loggedUser");
            user.setEmail(email);
            String sha1hexPassword = DigestUtils.sha1Hex(password);
            user.setPassword(sha1hexPassword);
            UserService service = new UserService();

            try {
                service.update(user);
            } catch (UpdateObjectException e) {
                e.printStackTrace();
            }
            req.getRequestDispatcher("/logout").forward(req, resp);
        } else {
            req.setAttribute("errorMessage", "Passwords not the same");
            req.setAttribute("fragment", "account");
            req.getRequestDispatcher("WEB-INF/index.jsp").forward(req, resp);
        }
    }
}

Thanks for any hint.

Body:
Problem solved. Here:

req.getRequestDispatcher("/logout").forward(req, resp);

i should do

resp.sendRedirect(req.getContextPath()+"/logout");

because in "/logout" i have only doGet() method ,and if i use "getRequestDispatcher()" its try to find doPost() method.


问:
How can I merge keys with the same value into a single object?
I use the Parsehub API to scrape the data below in a json format and when I want to print information on a certain country I'm able to get only the first set of data: 'name', 'pop','area','growth','worldPer', and 'rank' but I'm unable to get 'image'.

When I print the entire json file, the data is all there, but when I try to print a countries data with the image value, I get a key error.

Is there a way I can merge the two objects by matching country name?

main.py

```<code>class Data:
    def __init__(self, api_key, project_token):
        self.api_key = api_key
        self.project_token = project_token
        self.params = {"api_key":api_key}
        self.data = self.get_data()

    def get_data(self):
        r = requests.get(f'https://www.parsehub.com/api/v2/projects/xxxx/last_ready_run/data', params={"api_key": DATA_API_KEY})
        data = json.loads(r.text)
        print(r.text)
        return data

    def data_by_name(self,country):
        data = self.data['country']
        for content in data:
            if content['name'].lower() == country.lower():
                print(content)
                name = content['name']
                pop = content['pop']
                popRank = content['rank']
                growth = content['growth']
                per = content['worldPer']
                area = content['area']
                image = content['image'] #<----- KeyError: 'image'
        return(name,pop,popRank,growth,per,area)

data = Data(DATA_API_KEY,DATA_PROJECT_TOKEN)
data.data_by_name('china')

</code>```

country.json

```<code>{
 "country": [
  {
   "name": "China",
   "pop": "1,438,862,614",
   "area": "9,706,961 km²",
   "growth": "0.39%",
   "worldPer": "18.47%",
   "rank": "1"
  },
  {
   "name": "China",
   "image": "https://s3.amazonaws.com/images.wpr.com/flag-pages/png250/cn.png"
  }
 ]
}
</code>```

答:
Pandas could handle this for you

```<code>import pandas as pd

d = {
 "country": [
  {
   "name": "China",
   "pop": "1,438,862,614",
   "area": "9,706,961 km²",
   "growth": "0.39%",
   "worldPer": "18.47%",
   "rank": "1"
  },
  {
   "name": "China",
   "image": "https://s3.amazonaws.com/images.wpr.com/flag-pages/png250/cn.png"
  }
 ]
}

df = pd.DataFrame.from_dict(d['country']).groupby('name').first()
</code>```

Output

```<code>                 pop           area growth worldPer rank                                              image
name
China  1,438,862,614  9,706,961 km²  0.39%   18.47%    1  https://s3.amazonaws.com/images.wpr.com/flag-p...
</code>```

Body:
I use the Parsehub API to scrape the data below in a json format and when I want to print information on a certain country I'm able to get only the first set of data: 'name', 'pop','area','growth','worldPer', and 'rank' but I'm unable to get 'image'.

When I print the entire json file, the data is all there, but when I try to print a countries data with the image value, I get a key error.

Is there a way I can merge the two objects by matching country name?

main.py

class Data:
    def __init__(self, api_key, project_token):
        self.api_key = api_key
        self.project_token = project_token
        self.params = {"api_key":api_key}
        self.data = self.get_data()

    def get_data(self):
        r = requests.get(f'https://www.parsehub.com/api/v2/projects/xxxx/last_ready_run/data', params={"api_key": DATA_API_KEY})
        data = json.loads(r.text)
        print(r.text)
        return data

    def data_by_name(self,country):
        data = self.data['country']
        for content in data:
            if content['name'].lower() == country.lower():
                print(content)
                name = content['name']
                pop = content['pop']
                popRank = content['rank']
                growth = content['growth']
                per = content['worldPer']
                area = content['area']
                image = content['image'] #<----- KeyError: 'image'
        return(name,pop,popRank,growth,per,area)

data = Data(DATA_API_KEY,DATA_PROJECT_TOKEN)
data.data_by_name('china')

country.json

{
 "country": [
  {
   "name": "China",
   "pop": "1,438,862,614",
   "area": "9,706,961 km²",
   "growth": "0.39%",
   "worldPer": "18.47%",
   "rank": "1"
  },
  {
   "name": "China",
   "image": "https://s3.amazonaws.com/images.wpr.com/flag-pages/png250/cn.png"
  }
 ]
}

Body:
Pandas could handle this for you

import pandas as pd

d = {
 "country": [
  {
   "name": "China",
   "pop": "1,438,862,614",
   "area": "9,706,961 km²",
   "growth": "0.39%",
   "worldPer": "18.47%",
   "rank": "1"
  },
  {
   "name": "China",
   "image": "https://s3.amazonaws.com/images.wpr.com/flag-pages/png250/cn.png"
  }
 ]
}

df = pd.DataFrame.from_dict(d['country']).groupby('name').first()

Output

                 pop           area growth worldPer rank                                              image
name
China  1,438,862,614  9,706,961 km²  0.39%   18.47%    1  https://s3.amazonaws.com/images.wpr.com/flag-p...


问:
Nth order difference and Nth difference
In  ARIMA/SARIMA  one parameter id "d", which specifies difference. For differencing when d>1, I have heard two expressions: "n differencing", "n-order differencing". Are these two expressions referring to the same thing?

For example, for 2nd order difference, I have seen the following formula:

```<code>  yt − 2yt−1 + yt−2
</code>```

What would be the 2nd difference formula (d=2)? Is this the same as previous formula? Any help is appreciated.

答:
The regression model of ARIMA has the following formula:

The formula of SARIMA is the ARIMA's formula with extra:

As you see there are no d and D in these formulas. But why do we need them?

ARMA models work a lot better when the time series is stationary. And to make a time series stationary we can differentiate them. If D or d is more than 1, then we subtract its shifted version from the series.

So, if d = 1:

y = y - y.shift(1)
```

<p>If <em>d = 2</em>:</p>

<pre class="lang-py prettyprint-override"><code>y = y - y.shift(1)
y = y - y.shift(1)
</code>```

If D = 1:

y = y - y.shift(S)
```

... and so on, where y is your time series and S is your seasonality period.

P.S. shift function is a function of pandas.Series, if you don't use pandas you can shift it in your way.

Title: Nth order difference and Nth difference

Body:
In  ARIMA/SARIMA  one parameter id "d", which specifies difference. For differencing when d>1, I have heard two expressions: "n differencing", "n-order differencing". Are these two expressions referring to the same thing?

For example, for 2nd order difference, I have seen the following formula:

  yt − 2yt−1 + yt−2

What would be the 2nd difference formula (d=2)? Is this the same as previous formula? Any help is appreciated.

Body:
The regression model of ARIMA has the following formula:

The formula of SARIMA is the ARIMA's formula with extra:

As you see there are no d and D in these formulas. But why do we need them?

ARMA models work a lot better when the time series is stationary. And to make a time series stationary we can differentiate them. If D or d is more than 1, then we subtract its shifted version from the series.

So, if d = 1:

y = y - y.shift(1)

If d = 2:

y = y - y.shift(1)
y = y - y.shift(1)

If D = 1:

y = y - y.shift(S)

... and so on, where y is your time series and S is your seasonality period.

P.S. shift function is a function of pandas.Series, if you don't use pandas you can shift it in your way.


问:
How to declare a global variable in React?
I initialized i18n translation object once in a component (a first component that loads in the app ). That same object is required In all other components. I don't want to re-initialize it in every component. What's the way around? Making it available to window scope doesn't help as I need to use it in the render() method.

Please suggest a generic solution for these problems and not i18n specific solution.

答:
Here is a modern approach, using globalThis,  we took for our React Native app.

globalThis is now included in...

Modern browsers - MDN documentation

Typescript 3.4 - Handbook documentation

ESLint v7 - Release notes

appGlobals.ts

// define our parent property accessible via globalThis. Also apply the TypeScript type.
var app: globalAppVariables;

// define the child properties and their types.
type globalAppVariables = {
  messageLimit: number;
  // more can go here.
};

// set the values.
globalThis.app = {
  messageLimit: 10,
  // more can go here.
};

// Freeze so these can only be defined in this file.
Object.freeze(globalThis.app);
```

<p><br />
<sub>App.tsx (<em>our main entry point file</em>)</sub></p>

<pre class="lang-js prettyprint-override"><code>import './appGlobals'

// other code
</code>```

anyWhereElseInTheApp.tsx

const chatGroupQuery = useQuery(GET_CHAT_GROUP_WITH_MESSAGES_BY_ID, {
  variables: {
    chatGroupId,
    currentUserId: me.id,
    messageLimit: globalThis.app.messageLimit, //  used here.
  },
});
```

Body:
Here is a modern approach, using globalThis,  we took for our React Native app.

globalThis is now included in...

Modern browsers - MDN documentation

Typescript 3.4 - Handbook documentation

ESLint v7 - Release notes

appGlobals.ts

// define our parent property accessible via globalThis. Also apply the TypeScript type.
var app: globalAppVariables;

// define the child properties and their types.
type globalAppVariables = {
  messageLimit: number;
  // more can go here.
};

// set the values.
globalThis.app = {
  messageLimit: 10,
  // more can go here.
};

// Freeze so these can only be defined in this file.
Object.freeze(globalThis.app);

App.tsx (our main entry point file)

import './appGlobals'

// other code

anyWhereElseInTheApp.tsx

const chatGroupQuery = useQuery(GET_CHAT_GROUP_WITH_MESSAGES_BY_ID, {
  variables: {
    chatGroupId,
    currentUserId: me.id,
    messageLimit: globalThis.app.messageLimit, //  used here.
  },
});


问:
How to get html-tags autocomplete in sublimetext3 on react (js) files?
How can i get back the function
of autocomplete html tags in react files (.js)

example :
type li + press tab to get

```<code>   <li></li>
</code>```

i already installed the plugin reactjs
what gave me some advanced autocomplete features,
but not for simple html.

答:
press Ctrl + Shift + p

type Install package
A dialogue box will open,

Type emmet and run it by double click on emmet or press enter

once emmet install just type any html tag and press tab,

for creating

 just type li and press tab,

for creating a UL with 5 li, type ul>li*5

for creating 5 li in ul with anchor type... ul>li*5>a

there are lots of shortcuts for such things...

and if you want to get JSX support thenm go to Preferences > Key Bindings — User and paste this code

```<code>{
"keys": ["tab"],
"command": "expand_abbreviation_by_tab",
"context": [
    {
        "operand": "source.js.jsx",
        "operator": "equal",
        "match_all": true,
        "key": "selector"
    },
    {
        "key": "selection_empty",
        "operator": "equal",
        "operand": true,
        "match_all": true
    }
]
}
</code>```

Enjoy

Body:
How can i get back the function
of autocomplete html tags in react files (.js)

example :
type li + press tab to get

i already installed the plugin reactjs
what gave me some advanced autocomplete features,
but not for simple html.

Body:
press Ctrl + Shift + p

type Install package
A dialogue box will open,

Type emmet and run it by double click on emmet or press enter

once emmet install just type any html tag and press tab,

for creating <li></li> just type li and press tab,

for creating a UL with 5 li, type ul>li*5

for creating 5 li in ul with anchor type... ul>li*5>a

there are lots of shortcuts for such things...

and if you want to get JSX support thenm go to Preferences > Key Bindings — User and paste this code

{
"keys": ["tab"],
"command": "expand_abbreviation_by_tab",
"context": [
    {
        "operand": "source.js.jsx",
        "operator": "equal",
        "match_all": true,
        "key": "selector"
    },
    {
        "key": "selection_empty",
        "operator": "equal",
        "operand": true,
        "match_all": true
    }
]
}

Enjoy


问:
Need to replace string with variable in specific Pandas dataframe slice
I have a Pandas dataframe where some rows have NaN in some columns. I have a specific column wherein I need to replace the NaN with a given integer.

My starting df:

```<code>   Column1  Column2  Column3
0  10       20       30
1  11       NaN      NaN
2  12       NaN      NaN
</code>```

My goal df:

```<code>   Column1  Column2  Column3
0  10       20       30
1  11       5        NaN
2  12       5        NaN
</code>```

I'm trying to remove anything hardcoded in the script. (Someone else with much more experience than I wrote the initial code and I need to update it).

I've set the variables:

```<code>column_name = 'Column2'
new_integer = 5
</code>```

So far I have:

```<code>df.loc[df.Column2.isna(), column_name] = new_integer
</code>```

I can't figure out how to replace the remaining Column2 string with the variable column_name.
Thanks in advance!

答:
You could do something like,</p>

```<code>import pandas as pd
import numpy as np

d = {'Column1': [10, 11, 12],
     'Column2': [20, np.nan, np.nan],
     'Column3': [30, np.nan, np.nan]}

df = pd.DataFrame(data=d)
column_name = 'Column2'
new_integer = 5

df[column_name] = df[column_name].fillna(new_integer)
</code>```

Body:
I have a Pandas dataframe where some rows have NaN in some columns. I have a specific column wherein I need to replace the NaN with a given integer.

My starting df:

   Column1  Column2  Column3
0  10       20       30
1  11       NaN      NaN
2  12       NaN      NaN

My goal df:

   Column1  Column2  Column3
0  10       20       30
1  11       5        NaN
2  12       5        NaN

I'm trying to remove anything hardcoded in the script. (Someone else with much more experience than I wrote the initial code and I need to update it).

I've set the variables:

column_name = 'Column2'
new_integer = 5

So far I have:

df.loc[df.Column2.isna(), column_name] = new_integer

I can't figure out how to replace the remaining Column2 string with the variable column_name.
Thanks in advance!

Body:
You could do something like,

import pandas as pd
import numpy as np

d = {'Column1': [10, 11, 12],
     'Column2': [20, np.nan, np.nan],
     'Column3': [30, np.nan, np.nan]}

df = pd.DataFrame(data=d)
column_name = 'Column2'
new_integer = 5

df[column_name] = df[column_name].fillna(new_integer)


问:
Autoindent on Sublime Text
Are there any command/shortcut to auto-indent all my code on the page at once on Sublime Text 3?

e.g: On NetBeans I can do this with Alt+Shift+F.

答:
This should work as at sublime text version 3 :

```<code>{"keys": ["alt+shift+f"], "command": "reindent", "args": {"single_line": false}}
</code>```

just copy and paste to your preferences->keybindings->User file.
Now select the entire code and press alt shift f to see the results.

For intending purpose you can use Ctrl plus ] and to unintend use Ctrl plus [

Title: Autoindent on Sublime Text

Body:
This should work as at sublime text version 3 :

{"keys": ["alt+shift+f"], "command": "reindent", "args": {"single_line": false}}

just copy and paste to your preferences->keybindings->User file.
Now select the entire code and press alt shift f to see the results.

For intending purpose you can use Ctrl plus ] and to unintend use Ctrl plus [


问:
How to test member-wise equality operator?
I have a structure of three members { xx, xy, yy } and an overloaded == operator that member-wise tests if corresponding members of left-hand and right-hand expressions are either equal within some precision, or are both NaNs. Quite trivial.

For my test case, I wanted to target a typo situation, where I mistakingly compare wrong members. Maybe, I compare xx from left-hand expression with xy from right-hand expression. Maybe, I forgot to compare yy at all.

Since I'm using C++20, I don't know if it's even possible to construct a compile-time proof of correctness of == operator (and if I even should). Trying to solve this in usual manner, I find myself enumerating all possible permutations:

```<code>EXPECT_EQ(C{1, 2, 3}, C{1, 2, 3});
EXPECT_NE(C{1, 2, 3}, C{1, 3, 2});
EXPECT_NE(C{1, 2, 3}, C{2, 1, 3});
EXPECT_NE(C{1, 2, 3}, C{2, 3, 1});
EXPECT_NE(C{1, 2, 3}, C{3, 1, 2});
EXPECT_NE(C{1, 2, 3}, C{3, 2, 1});
EXPECT_NE(C{1, 2, 3}, C{1, 2, nan});
EXPECT_NE(C{1, 2, 3}, C{1, nan, 3});
EXPECT_NE(C{1, 2, 3}, C{nan, 2, 3});
// ...

EXPECT_NE(C{1, 3, 2}, C{1, 2, 3});
EXPECT_EQ(C{1, 3, 2}, C{1, 3, 2});
// ...
</code>```

Such code is quite ugly, and if I replicate the same with nested loops:

```<code>for (T lxx = 1; lxx <= 3; lxx += 1) {
  for (T rxx = 1; rxx <= 3; rxx += 1) {
    for (T lxy = 1; lxy <= 3; lxy += 1) {
      for (T rxy = 1; rxy <= 3; rxy += 1) {
        // ...
</code>```

it just seems that I am reimplementing equality operator in test, which misses the point of testing.

How do I do this correctly? Am I missing some edge cases maybe that would simplify it? How to scale such test if I have four members in a structure and don't want for test case code to explode?

答:
Unit-testing is not about having proof of correctness, it's about having confidence in the code's behavior.

Let's say your operator is defined like this:

```<code>bool operator==(T const& lhs, T const& rhs) {
    return (lhs.xx - rhs.xx) <= epsilon && (lhs.xy - rhs.xy) <= epsilon && (lhs.yy - rhs.yy) <= epsilon;
}
</code>```

There is no point in testing as many inputs as you can. The function is quite trivial, and you should focus on what could go wrong.

For example, you say you want to make sure there is no typo that could make the function compare the wrong members. Well, a test of equality like the first one you wrote, EXPECT_EQ(C{1, 2, 3}, C{1, 2, 3}), is all you need. If each member has a value different from each other by at least epsilon, then there is little chance for the test to pass while your function is comparing the wrong members.

By the way, you mention your equality operator checks if corresponding members are either within some precision or both NaNs. I don't think you want NaNs to compare equal. By definition, they aren't numbers, so equality is not defined for them. That's why IEEE 754 NaNs never compare equal, even when their binary representation is identical.

If you don't, then testing with NaNs is kind of useless here, since NaNs propagate and, again, don't compare to anything. If you do, then you wrote some special case for them which you want to test, but one or two equality tests are sufficient for that.

Something you might want to check is whether the epsilon (if that's what you actually use) has a reasonable value in different situations. That also comes with the matter of transitivity (or lack thereof), but that's a behavior that you must decide on.

Body:
I have a structure of three members { xx, xy, yy } and an overloaded == operator that member-wise tests if corresponding members of left-hand and right-hand expressions are either equal within some precision, or are both NaNs. Quite trivial.

For my test case, I wanted to target a typo situation, where I mistakingly compare wrong members. Maybe, I compare xx from left-hand expression with xy from right-hand expression. Maybe, I forgot to compare yy at all.

Since I'm using C++20, I don't know if it's even possible to construct a compile-time proof of correctness of == operator (and if I even should). Trying to solve this in usual manner, I find myself enumerating all possible permutations:

EXPECT_EQ(C{1, 2, 3}, C{1, 2, 3});
EXPECT_NE(C{1, 2, 3}, C{1, 3, 2});
EXPECT_NE(C{1, 2, 3}, C{2, 1, 3});
EXPECT_NE(C{1, 2, 3}, C{2, 3, 1});
EXPECT_NE(C{1, 2, 3}, C{3, 1, 2});
EXPECT_NE(C{1, 2, 3}, C{3, 2, 1});
EXPECT_NE(C{1, 2, 3}, C{1, 2, nan});
EXPECT_NE(C{1, 2, 3}, C{1, nan, 3});
EXPECT_NE(C{1, 2, 3}, C{nan, 2, 3});
// ...

EXPECT_NE(C{1, 3, 2}, C{1, 2, 3});
EXPECT_EQ(C{1, 3, 2}, C{1, 3, 2});
// ...

Such code is quite ugly, and if I replicate the same with nested loops:

for (T lxx = 1; lxx <= 3; lxx += 1) {
  for (T rxx = 1; rxx <= 3; rxx += 1) {
    for (T lxy = 1; lxy <= 3; lxy += 1) {
      for (T rxy = 1; rxy <= 3; rxy += 1) {
        // ...

it just seems that I am reimplementing equality operator in test, which misses the point of testing.

How do I do this correctly? Am I missing some edge cases maybe that would simplify it? How to scale such test if I have four members in a structure and don't want for test case code to explode?

Body:
Unit-testing is not about having proof of correctness, it's about having confidence in the code's behavior.

Let's say your operator is defined like this:

bool operator==(T const& lhs, T const& rhs) {
    return (lhs.xx - rhs.xx) <= epsilon && (lhs.xy - rhs.xy) <= epsilon && (lhs.yy - rhs.yy) <= epsilon;
}

There is no point in testing as many inputs as you can. The function is quite trivial, and you should focus on what could go wrong.

For example, you say you want to make sure there is no typo that could make the function compare the wrong members. Well, a test of equality like the first one you wrote, EXPECT_EQ(C{1, 2, 3}, C{1, 2, 3}), is all you need. If each member has a value different from each other by at least epsilon, then there is little chance for the test to pass while your function is comparing the wrong members.

By the way, you mention your equality operator checks if corresponding members are either within some precision or both NaNs. I don't think you want NaNs to compare equal. By definition, they aren't numbers, so equality is not defined for them. That's why IEEE 754 NaNs never compare equal, even when their binary representation is identical.

If you don't, then testing with NaNs is kind of useless here, since NaNs propagate and, again, don't compare to anything. If you do, then you wrote some special case for them which you want to test, but one or two equality tests are sufficient for that.

Something you might want to check is whether the epsilon (if that's what you actually use) has a reasonable value in different situations. That also comes with the matter of transitivity (or lack thereof), but that's a behavior that you must decide on.


问:
How to filter out all the sesions I found using get function
This is the list of session I am getting, Now I want delete all the sessions except where active is true

```<code>const token = 'xxxx-xxx-xxxxx-xxxx-xxxxx';

const session_list = [
{
  "id": "45345345-4534-5435-d1cc1bdb6153410",
  "device": "browser",
  "ip": "xx.xx.xxx.xxx",
  "city": null,
  "country": null,
  "browser_name": "Opera",
  "browser_version": "67.0.3575.115",
  "os_name": "Mac OS"
},
{
  "id": "23213-34234-324234-4234324o",
  "device": "browser",
  "ip": "xx.xx.xxx.xxx",
  "city": null,
  "country": null,
  "browser_name": "Mozila",
  "browser_version": "67.0.3575.115",
  "os_name": "Windows"
},
{
  "id": "324234-sadasd34-sdsda343-3434234234",
  "device": "browser",
  "ip": "xx.xx.xxx.xxx",
  "city": null,
  "country": null,
  "browser_name": "Opera",
  "browser_version": "67.0.3575.115",
  "os_name": "android",
  "active": true
}
]
</code>```

Now I want to call an API to delete the session, Now it takes 3 things in it, token which is static, and ip, session_id which i find in array of the session_list
Now the API delete session one by one by passing the required arguments.

```<code>  const delete_session_api = async (data) => {
    // delete the session
    try {

        const config = {
            data: querystring.stringify(data),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        };

        const { data: api_res } =
            await axios.delete('/sessions/delete', config);

        return api_res;

    } catch (error) {

        throw error;

    }

    };
</code>```

All I want to delete the sessions from the session_list except the active true one which is the same list.
Can any one help me with the efficient way to do this?

答:
You can do this in vanilla JavaScript with this short function

const filterActiveSessions = payload => ({
  meta: payload.meta,
  data: (payload.data || []).filter(session => session.active),
})
```

<p>You can also write a single function to delete non-active sessions using my <strong>functional</strong> programming library, rubico. I'm able to get it into a single function because I compose many small functions with the library.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const { pipe, fork, filter, get } = rubico

const payload = {
  "meta": {
    "message": "Sessions retrieved successfully."
  },
  "data": [
    {
      "id": "45345345-4534-5435-d1cc1bdb6153410",
      "device": "browser",
      "ip": "xx.xx.xxx.xxx",
      "city": null,
      "country": null,
      "browser_name": "Opera",
      "browser_version": "67.0.3575.115",
      "os_name": "Mac OS"
    },
    {
      "id": "23213-34234-324234-4234324o",
      "device": "browser",
      "ip": "xx.xx.xxx.xxx",
      "city": null,
      "country": null,
      "browser_name": "Mozila",
      "browser_version": "67.0.3575.115",
      "os_name": "Windows"
    },
    {
      "id": "324234-sadasd34-sdsda343-3434234234",
      "device": "browser",
      "ip": "xx.xx.xxx.xxx",
      "city": null,
      "country": null,
      "browser_name": "Opera",
      "browser_version": "67.0.3575.115",
      "os_name": "android",
      "active": true
    }
  ],
}

// payload => payload_with_active_sessions_only
const filterActiveSessions = fork({
  meta: get('meta'),
  data: pipe([
    get('data'),
    filter(session => session.active),
  ]),
})

console.log(
  filterActiveSessions(payload)
)</code>```

```

Body:
This is the list of session I am getting, Now I want delete all the sessions except where active is true

const token = 'xxxx-xxx-xxxxx-xxxx-xxxxx';

const session_list = [
{
  "id": "45345345-4534-5435-d1cc1bdb6153410",
  "device": "browser",
  "ip": "xx.xx.xxx.xxx",
  "city": null,
  "country": null,
  "browser_name": "Opera",
  "browser_version": "67.0.3575.115",
  "os_name": "Mac OS"
},
{
  "id": "23213-34234-324234-4234324o",
  "device": "browser",
  "ip": "xx.xx.xxx.xxx",
  "city": null,
  "country": null,
  "browser_name": "Mozila",
  "browser_version": "67.0.3575.115",
  "os_name": "Windows"
},
{
  "id": "324234-sadasd34-sdsda343-3434234234",
  "device": "browser",
  "ip": "xx.xx.xxx.xxx",
  "city": null,
  "country": null,
  "browser_name": "Opera",
  "browser_version": "67.0.3575.115",
  "os_name": "android",
  "active": true
}
]

Now I want to call an API to delete the session, Now it takes 3 things in it, token which is static, and ip, session_id which i find in array of the session_list
Now the API delete session one by one by passing the required arguments.

  const delete_session_api = async (data) => {
    // delete the session
    try {

        const config = {
            data: querystring.stringify(data),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        };

        const { data: api_res } =
            await axios.delete('/sessions/delete', config);

        return api_res;

    } catch (error) {

        throw error;

    }

    };

All I want to delete the sessions from the session_list except the active true one which is the same list.
Can any one help me with the efficient way to do this?

Body:
You can do this in vanilla JavaScript with this short function

const filterActiveSessions = payload => ({
  meta: payload.meta,
  data: (payload.data || []).filter(session => session.active),
})

You can also write a single function to delete non-active sessions using my functional programming library, rubico. I'm able to get it into a single function because I compose many small functions with the library.

const { pipe, fork, filter, get } = rubico

const payload = {
  "meta": {
    "message": "Sessions retrieved successfully."
  },
  "data": [
    {
      "id": "45345345-4534-5435-d1cc1bdb6153410",
      "device": "browser",
      "ip": "xx.xx.xxx.xxx",
      "city": null,
      "country": null,
      "browser_name": "Opera",
      "browser_version": "67.0.3575.115",
      "os_name": "Mac OS"
    },
    {
      "id": "23213-34234-324234-4234324o",
      "device": "browser",
      "ip": "xx.xx.xxx.xxx",
      "city": null,
      "country": null,
      "browser_name": "Mozila",
      "browser_version": "67.0.3575.115",
      "os_name": "Windows"
    },
    {
      "id": "324234-sadasd34-sdsda343-3434234234",
      "device": "browser",
      "ip": "xx.xx.xxx.xxx",
      "city": null,
      "country": null,
      "browser_name": "Opera",
      "browser_version": "67.0.3575.115",
      "os_name": "android",
      "active": true
    }
  ],
}

// payload => payload_with_active_sessions_only
const filterActiveSessions = fork({
  meta: get('meta'),
  data: pipe([
    get('data'),
    filter(session => session.active),
  ]),
})

console.log(
  filterActiveSessions(payload)
)

<script src="https://unpkg.com/rubico/index.js" crossorigin></script>


答:
It would be better to store the data of each country in a dictionary so you don't iterate over all the data each time. You could do like this:

def __init__(self, api_key, project_token):
    ...
    self.countries_data = self.get_countries_data()

...

def get_countries_data(self):
    countries_data = {}
    for content in self.data["country"]:
        name = content["name"]
        countries_data[name] = {**countries_data.get(name, {}), **content}
    return countries_data

def data_by_name(self, country):
    conuntry_data = self.countries_data[country]
    return country_data["name"], country_data["pop"]...
```

Title: How can I merge keys with the same value into a single object?


问:
SQL query to sum separate columns with separate Where conditions
SQL noob here. I want to sum two columns separately, using 2 separate where conditions.

```<code>ID  NAME    VALUE1   VALUE2
--- ------- -------  -------
1   Orange  5        30
2   Orange  11       30
3   Orange  7        15
4   Pear    12       12
5   Pear    13       25
6   Pear    4        25
</code>```

Sum of VALUE1 column where values are > 10

Sum of VALUE2 column where values are > 20

Grouped by NAME

Desired output:

```<code>NAME    VALUE1   VALUE2
------- -------  -------
Orange  11       60
Pear    25       50
</code>```

Thanks!

答:
I know this approach is bit tricky and lengthy as well,however this might be helpful in debugging ,if you can try this :</p>

```<code>select
value1.name,value1.a,value2.b
from
(select sum(value1)a,name from test where value1 >10 group by name) as value1
join (select sum(value2)b,name from test where value2 >20 group by name) as value2
on value1.name = value2.name
</code>```

Body:
SQL noob here. I want to sum two columns separately, using 2 separate where conditions.

ID  NAME    VALUE1   VALUE2
--- ------- -------  -------
1   Orange  5        30
2   Orange  11       30
3   Orange  7        15
4   Pear    12       12
5   Pear    13       25
6   Pear    4        25

Sum of VALUE1 column where values are > 10

Sum of VALUE2 column where values are > 20

Grouped by NAME

Desired output:

NAME    VALUE1   VALUE2
------- -------  -------
Orange  11       60
Pear    25       50

Thanks!

Body:
I know this approach is bit tricky and lengthy as well,however this might be helpful in debugging ,if you can try this :

select
value1.name,value1.a,value2.b
from
(select sum(value1)a,name from test where value1 >10 group by name) as value1
join (select sum(value2)b,name from test where value2 >20 group by name) as value2
on value1.name = value2.name


问:
SQL for finding a value having rows of closest to half of all unique occurrences of another value?
Table rows I'm using:

```<code>`factid` int(11) NOT NULL,
`segid` int(11) NOT NULL,
PRIMARY KEY (`factid`,`segid`)
</code>```

Here's the steps of what I'm trying to accomplish:

I need the total number of unique segid values in the table.

I need a single factid value.

This factid value needs to have rows with many unique segid values.

'Many' being closest to half the above total unique segid values.

I hope this explains what I'm trying to accomplish.  Help appreciated.

答:
```<code>SELECT TOP 1
    facts.factid
  , facts.segids
  , segs.total_segids
FROM (
    SELECT factid
      , count(distinct segid) as segids
    FROM my_table
    GROUP BY factid
  ) facts,
  (
    SELECT count(distinct segid) as total_segids
    FROM my_table
  ) segs
ORDER BY abs(facts.segids - (segs.total_segids / 2))
</code>```

Body:
Table rows I'm using:

`factid` int(11) NOT NULL,
`segid` int(11) NOT NULL,
PRIMARY KEY (`factid`,`segid`)

Here's the steps of what I'm trying to accomplish:

I need the total number of unique segid values in the table.

I need a single factid value.

This factid value needs to have rows with many unique segid values.

'Many' being closest to half the above total unique segid values.

I hope this explains what I'm trying to accomplish.  Help appreciated.


问:
How to make controllable virus simulation using turtle python
Uh I was tasked to make a controllable Covid-19 simulation using python turtle for a school project. So what I made was a bunch of moving randomly turtles and random picked "posessed" and random picked "infected" turtles. I was trying to make the "posessed" ones controllable with arrow keys, and also picks another "healthy" turtle if the previous one got infected. The problem is, I dont know how to separate the controls as they were all tagged under the class "Person". I also don't know how to make it choose another healthy turtle when one is infected. Here is the messy code. Sorry for bad english.

```<code>from turtle import Screen, Turtle
"""
This imports the screen and turtle from the turtle module
"""
from random import randint, choice
"""
This is to use the random integer function and the random choosing of the infected
"""
from time import sleep
posessed = 0
class Person(Turtle):
    population = []

    def __init__(self):
        super().__init__(shape='circle')

        self.shapesize(0.4)
        self.penup()
        self.setpos(randint(-250, 250), randint(-250, 250))

        Person.population.append(self)

    @classmethod
    def all_infected(cls):
        return [person for person in cls.population if person.infected()]

    def infect(self):
        self.color('red')

    def infected(self):
        return self.pencolor() == 'red'
    def all_infected(cls):
        return [person for person in cls.population if person.posessed()]

    def posess(self):
        self.color('yellow')

    def posessed(self):
        return self.pencolor() == 'yellow'

    def random_move(self):
        self.right(randint(-180,180))
        self.forward(randint(0,10))
        if not (-250 < self.xcor() <250 and -250 < self.ycor() < 250):
            self.undo() # this will undo forward()

def make_population(amount):

    for _ in range(amount):
        Person()

def posess_random():
    person = choice(Person.population)
    person.posess()
    posessed+1

def infect_random():
    person = choice(Person.population)
    person.infect()

def simulation():
    """ This will simulate the virus outbreak scenarios (quarantine, or not quarantine) """
    amount=int(input("Enter amount of people within the area: " ))
    moves=int(input("Enter the amount of moves these people will do: "))
    print("Entered amount of people: ", amount)
    print("Entered amount of movements: ", moves)
    make_population(amount)

    infect_random()
    posess_random()

    screen.update()
    for _ in range(moves):
        for person.infected in Person.population:
            person.random_move()

            if not person.infected():
                for infected in Person.all_infected():
                    if person.distance(infected) < 30:
                        person.infect()
                        #this is used to set distance to get infected. In this case I did 30

        screen.update()
        sleep(0.1)

screen = Screen()
screen.setup(500,500)
screen.tracer(0)
screen.bgcolor(str(input("Enter desired background color: ")))
simulation()

screen.exitonclick()
               #this should do it
</code>```

Tysm before hand

答:
So what I made was a bunch of moving randomly turtles

First, this code doesn't run as posted -- I had to fix at least three errors to get it to run.  Surprisingly since it is only has minor changes to my rework, of @LST_2020's code, the former of which runs fine.  And there's no credit/link back to that code!  Moving on:

Below is my rework of our code to fix your introduced bugs, and make the possessed person manually movable.  (Fixing the spelling of "possessed" along the way.)  And if the possessed person comes into contact with an infected person, either by their own motion or the infected person's motion, the possessed becomes infected and a random healthy person, if available, becomes possessed and manually moveable:

```<code>from turtle import Screen, Turtle
from random import randint, choice
from functools import partial
from time import sleep

INFECTION_DISTANCE = 30
PERSON_RADIUS = 8
WIDTH, HEIGHT = 500, 500
CURSOR_SIZE = 20

possessed = 0

class Person(Turtle):
    population = []

    def __init__(self):
        super().__init__(shape='circle')

        self.shapesize(PERSON_RADIUS / CURSOR_SIZE)
        self.penup()
        self.setpos(randint(-WIDTH/2, WIDTH/2), randint(-HEIGHT/2, HEIGHT/2))

        Person.population.append(self)

    @classmethod
    def all_infected(cls):
        return [person for person in cls.population if person.infected()]

    def infect(self):
        self.color('red')

    def infected(self):
        return self.pencolor() == 'red'

    @classmethod
    def all_healthy(cls):
        return [person for person in cls.population if not person.infected()]

    def possess(self):
        self.color('green')

    def possessed(self):
        return self.pencolor() == 'green'

    def random_move(self):
        self.right(randint(-90, 90))
        self.forward(randint(0, 10))

        x, y = self.position()

        if not (PERSON_RADIUS - WIDTH/2 < x < WIDTH/2 - PERSON_RADIUS and PERSON_RADIUS - HEIGHT/2 < y < HEIGHT/2 - PERSON_RADIUS):
            self.undo()  # this will undo forward()

def make_population(amount):
    for _ in range(amount):
        Person()

def possess_random():
    possessed = None

    healthy = Person.all_healthy()

    if healthy:
        possessed = choice(healthy)
        possessed.possess()

        screen.onkey(partial(move_up, possessed), 'Up')
        screen.onkey(partial(move_down, possessed), 'Down')
        screen.onkey(partial(move_right, possessed), 'Right')
        screen.onkey(partial(move_left, possessed), 'Left')

    return possessed

def infect_random():
    person = None

    healthy = Person.all_healthy()

    if healthy:
        person = choice(healthy)
        person.infect()

    return person

def check_infection(person):
    for infected in Person.all_infected():
        if person.distance(infected) < INFECTION_DISTANCE:
            is_possessed = person.possessed()

            person.infect()

            if is_possessed:
                possess_random()

def simulation(amount, moves):
    """ This will simulate the virus outbreak scenarios (quarantine, or not quarantine) """
    make_population(amount)

    infect_random()
    possess_random()
    screen.update()

    for _ in range(moves):
        for person in Person.population:
            if not person.possessed():
                person.random_move()

            if not person.infected():
                check_infection(person)

        screen.update()
        sleep(0.1)

def move_up(possessed):
    y = possessed.ycor() + 10

    if y < HEIGHT/2 - PERSON_RADIUS:
        possessed.sety(y)
        check_infection(possessed)

def move_down(possessed):
    y = possessed.ycor() - 10

    if y > PERSON_RADIUS - HEIGHT/2:
        possessed.sety(y)
        check_infection(possessed)

def move_right(possessed):
    x = possessed.xcor() + 10

    if x < WIDTH/2 - PERSON_RADIUS:
        possessed.setx(x)
        check_infection(possessed)

def move_left(possessed):
    x = possessed.xcor() - 10

    if x > PERSON_RADIUS - WIDTH/2:
        possessed.setx(x)
        check_infection(possessed)

amount = int(input("Enter amount of people within the area: "))
moves = int(input("Enter the amount of moves these people will do: "))

screen = Screen()
screen.setup(WIDTH, HEIGHT)

screen.listen()
screen.tracer(False)

simulation(amount, moves)

screen.tracer(True)
screen.exitonclick()
</code>```

I changed the possessed color to green as I couldn't see the yellow dot easily against the default turtle background color.  And I moved the input questions ahead of the first turtle call so that the user doesn't have to click back to the console to answer them.

As I noted on my original, you should consider using turtle timer events to make the people more autonomous, instead of the for _ in range(moves): loop which also blocks some turtle events.

Body:
Uh I was tasked to make a controllable Covid-19 simulation using python turtle for a school project. So what I made was a bunch of moving randomly turtles and random picked "posessed" and random picked "infected" turtles. I was trying to make the "posessed" ones controllable with arrow keys, and also picks another "healthy" turtle if the previous one got infected. The problem is, I dont know how to separate the controls as they were all tagged under the class "Person". I also don't know how to make it choose another healthy turtle when one is infected. Here is the messy code. Sorry for bad english.

from turtle import Screen, Turtle
"""
This imports the screen and turtle from the turtle module
"""
from random import randint, choice
"""
This is to use the random integer function and the random choosing of the infected
"""
from time import sleep
posessed = 0
class Person(Turtle):
    population = []

    def __init__(self):
        super().__init__(shape='circle')

        self.shapesize(0.4)
        self.penup()
        self.setpos(randint(-250, 250), randint(-250, 250))

        Person.population.append(self)

    @classmethod
    def all_infected(cls):
        return [person for person in cls.population if person.infected()]

    def infect(self):
        self.color('red')

    def infected(self):
        return self.pencolor() == 'red'
    def all_infected(cls):
        return [person for person in cls.population if person.posessed()]

    def posess(self):
        self.color('yellow')

    def posessed(self):
        return self.pencolor() == 'yellow'

    def random_move(self):
        self.right(randint(-180,180))
        self.forward(randint(0,10))
        if not (-250 < self.xcor() <250 and -250 < self.ycor() < 250):
            self.undo() # this will undo forward()

def make_population(amount):

    for _ in range(amount):
        Person()

def posess_random():
    person = choice(Person.population)
    person.posess()
    posessed+1

def infect_random():
    person = choice(Person.population)
    person.infect()

def simulation():
    """ This will simulate the virus outbreak scenarios (quarantine, or not quarantine) """
    amount=int(input("Enter amount of people within the area: " ))
    moves=int(input("Enter the amount of moves these people will do: "))
    print("Entered amount of people: ", amount)
    print("Entered amount of movements: ", moves)
    make_population(amount)

    infect_random()
    posess_random()

    screen.update()
    for _ in range(moves):
        for person.infected in Person.population:
            person.random_move()

            if not person.infected():
                for infected in Person.all_infected():
                    if person.distance(infected) < 30:
                        person.infect()
                        #this is used to set distance to get infected. In this case I did 30

        screen.update()
        sleep(0.1)

screen = Screen()
screen.setup(500,500)
screen.tracer(0)
screen.bgcolor(str(input("Enter desired background color: ")))
simulation()

screen.exitonclick()
               #this should do it

Tysm before hand

Body:
So what I made was a bunch of moving randomly turtles

First, this code doesn't run as posted -- I had to fix at least three errors to get it to run.  Surprisingly since it is only has minor changes to my rework, of @LST_2020's code, the former of which runs fine.  And there's no credit/link back to that code!  Moving on:

Below is my rework of our code to fix your introduced bugs, and make the possessed person manually movable.  (Fixing the spelling of "possessed" along the way.)  And if the possessed person comes into contact with an infected person, either by their own motion or the infected person's motion, the possessed becomes infected and a random healthy person, if available, becomes possessed and manually moveable:

from turtle import Screen, Turtle
from random import randint, choice
from functools import partial
from time import sleep

INFECTION_DISTANCE = 30
PERSON_RADIUS = 8
WIDTH, HEIGHT = 500, 500
CURSOR_SIZE = 20

possessed = 0

class Person(Turtle):
    population = []

    def __init__(self):
        super().__init__(shape='circle')

        self.shapesize(PERSON_RADIUS / CURSOR_SIZE)
        self.penup()
        self.setpos(randint(-WIDTH/2, WIDTH/2), randint(-HEIGHT/2, HEIGHT/2))

        Person.population.append(self)

    @classmethod
    def all_infected(cls):
        return [person for person in cls.population if person.infected()]

    def infect(self):
        self.color('red')

    def infected(self):
        return self.pencolor() == 'red'

    @classmethod
    def all_healthy(cls):
        return [person for person in cls.population if not person.infected()]

    def possess(self):
        self.color('green')

    def possessed(self):
        return self.pencolor() == 'green'

    def random_move(self):
        self.right(randint(-90, 90))
        self.forward(randint(0, 10))

        x, y = self.position()

        if not (PERSON_RADIUS - WIDTH/2 < x < WIDTH/2 - PERSON_RADIUS and PERSON_RADIUS - HEIGHT/2 < y < HEIGHT/2 - PERSON_RADIUS):
            self.undo()  # this will undo forward()

def make_population(amount):
    for _ in range(amount):
        Person()

def possess_random():
    possessed = None

    healthy = Person.all_healthy()

    if healthy:
        possessed = choice(healthy)
        possessed.possess()

        screen.onkey(partial(move_up, possessed), 'Up')
        screen.onkey(partial(move_down, possessed), 'Down')
        screen.onkey(partial(move_right, possessed), 'Right')
        screen.onkey(partial(move_left, possessed), 'Left')

    return possessed

def infect_random():
    person = None

    healthy = Person.all_healthy()

    if healthy:
        person = choice(healthy)
        person.infect()

    return person

def check_infection(person):
    for infected in Person.all_infected():
        if person.distance(infected) < INFECTION_DISTANCE:
            is_possessed = person.possessed()

            person.infect()

            if is_possessed:
                possess_random()

def simulation(amount, moves):
    """ This will simulate the virus outbreak scenarios (quarantine, or not quarantine) """
    make_population(amount)

    infect_random()
    possess_random()
    screen.update()

    for _ in range(moves):
        for person in Person.population:
            if not person.possessed():
                person.random_move()

            if not person.infected():
                check_infection(person)

        screen.update()
        sleep(0.1)

def move_up(possessed):
    y = possessed.ycor() + 10

    if y < HEIGHT/2 - PERSON_RADIUS:
        possessed.sety(y)
        check_infection(possessed)

def move_down(possessed):
    y = possessed.ycor() - 10

    if y > PERSON_RADIUS - HEIGHT/2:
        possessed.sety(y)
        check_infection(possessed)

def move_right(possessed):
    x = possessed.xcor() + 10

    if x < WIDTH/2 - PERSON_RADIUS:
        possessed.setx(x)
        check_infection(possessed)

def move_left(possessed):
    x = possessed.xcor() - 10

    if x > PERSON_RADIUS - WIDTH/2:
        possessed.setx(x)
        check_infection(possessed)

amount = int(input("Enter amount of people within the area: "))
moves = int(input("Enter the amount of moves these people will do: "))

screen = Screen()
screen.setup(WIDTH, HEIGHT)

screen.listen()
screen.tracer(False)

simulation(amount, moves)

screen.tracer(True)
screen.exitonclick()

I changed the possessed color to green as I couldn't see the yellow dot easily against the default turtle background color.  And I moved the input questions ahead of the first turtle call so that the user doesn't have to click back to the console to answer them.

As I noted on my original, you should consider using turtle timer events to make the people more autonomous, instead of the for _ in range(moves): loop which also blocks some turtle events.


问:
how to access the value of blob column(image) in controller laravel
I make live search in laravel  by ajax jquery
i send html code from controller to view but i can't display the value of blob column </p>

```<code>function search (Request $request) {

        if($request->ajax())
        {    $output='';
             $data=Club::all();
            foreach($data as $record)
               {
               $output.='
                  <tr>
                  <td > '.$record->name.'</td>
                  <td > '.$record->country.'</td>
                  <td ><img src="data:image/png;charset=utf8;base64,{{base64_encode('.$record-
                   >logo.')}}" ></img></td> //this is uncorrect what is the correct syntax here???
                  </tr>
                  ';
               }
         echo json_encode($output);
         }
}
</code>```

答:
```<code>    if($request->ajax())
        {
           $output='';
           $data=Club::all();

           $path = $record->logo;
           $type = pathinfo($path, PATHINFO_EXTENSION);
           $data = file_get_contents($path);
           $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

            foreach($data as $record)
               {
               $output.='
                  <tr>
                  <td > '.$record->name.'</td>
                  <td > '.$record->country.'</td>
                  <td ><img src="'.$base64.'" ></img></td> //this is uncorrect what is the correct syntax here???
                  </tr>
                  ';
               }
         echo json_encode($output);
         }
</code>```

Body:
I make live search in laravel  by ajax jquery
i send html code from controller to view but i can't display the value of blob column

function search (Request $request) {

        if($request->ajax())
        {    $output='';
             $data=Club::all();
            foreach($data as $record)
               {
               $output.='

                   '.$record->name.'
                   '.$record->country.'
                  logo.')}}" >	 //this is uncorrect what is the correct syntax here???

                  ';
               }
         echo json_encode($output);
         }
}


答:
Try to return the data rather than display them using echo

json_encode() shall receive object or array, not HTML, return data from your API then format it in front-end.

```<code>if($request->ajax())
{    $output='';
     $data=Club::all();
     return json_encode($data);  \\ return rather than display
}
</code>```

Title: how to access the value of blob column(image) in controller laravel

Body:
Try to return the data rather than display them using echo

json_encode() shall receive object or array, not HTML, return data from your API then format it in front-end.

if($request->ajax())
{    $output='';
     $data=Club::all();
     return json_encode($data);  \\ return rather than display
}


问:
Python Networkx with_pandas_edgelist: edges not taking proper color, while specifying node positions
I am pretty new to Python and started learning networkx to plot a graph for a road network. I have to specify, the node positions. The edge color should be dependent on the weights of the edges. I tried using pandas dataframe to generate edges. The edge colors work fine when position is not specified. The code is attached.

```<code>import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt

# Necessary file-paths
l1 = 'file1.xlsx'
l2 = "file2.xlsx"

n1 = pd.read_excel(l1)
n1.head(10)
</code>```

```<code>n2 = pd.read_excel(l2)
n2.head(2)
</code>```

```<code># Building graph
G = nx.from_pandas_edgelist(n1, 'Start Node', 'End Node', create_using=nx.Graph())

# Defining positions
pos = {}
for n in G.nodes():
    i = n2[n2["Nodes"] == n].index[0]
    pos[n] = (n2.loc[i, "x"], n2.loc[i, "y"])

# Plot the Graph
nx.draw(G, pos, with_labels=True, node_color='pink', node_size=30, alpha=0.8, font_size=2,
        edge_color=n1['Capacity'], width=1.0, figsize = (18,18), style="solid", edge_cmap=plt.cm.jet)

# Save the Figure
plt.savefig('Network.png', dpi=1000, facecolor='w', edgecolor='w',orientation='portrait',
            papertype=None, format=None,transparent=False, bbox_inches=None, pad_inches=0.1)
</code>```

However, the colors do not follow the capacity values. I will share an example.
Here is the case where it unnecessarily changes color

Another example - Here the colors should change, but it does not

The excel files are here for reference

Also, if you can suggest how to add a color-bar to this, it would be great.

答:
```<code>import networkx as nx

# dummy data, Graph and positions
df = pd.DataFrame({
    'node1': np.random.choice([*'ABCDEFGHIJKL'], 10, replace=True),
    'node2': np.random.choice([*'ABCDEFGHIJKL'], 10, replace=True),
    'Capacity': np.random.rand(10)
})
G = nx.from_pandas_edgelist(df, source='node1', target='node2', edge_attr='Capacity')
pos = nx.spring_layout(G)

# extract the edge weight
edge_colors = [a['Capacity'] for u,v,a in G.edges(data=True)]

# draw nodes and edges separately. allows using colormap for edges.
nx.draw_networkx_nodes(G, pos=pos)
nx.draw_networkx_edges(G, pos=pos, edge_color=edge_colors, edge_cmap=plt.cm.viridis, edge_vmin=0, edge_vmax=np.max(edge_colors), width=5)
nx.draw_networkx_labels(G, pos=pos);
</code>```

Body:
I am pretty new to Python and started learning networkx to plot a graph for a road network. I have to specify, the node positions. The edge color should be dependent on the weights of the edges. I tried using pandas dataframe to generate edges. The edge colors work fine when position is not specified. The code is attached.

import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt

# Necessary file-paths
l1 = 'file1.xlsx'
l2 = "file2.xlsx"

n1 = pd.read_excel(l1)
n1.head(10)

n2 = pd.read_excel(l2)
n2.head(2)

# Building graph
G = nx.from_pandas_edgelist(n1, 'Start Node', 'End Node', create_using=nx.Graph())

# Defining positions
pos = {}
for n in G.nodes():
    i = n2[n2["Nodes"] == n].index[0]
    pos[n] = (n2.loc[i, "x"], n2.loc[i, "y"])

# Plot the Graph
nx.draw(G, pos, with_labels=True, node_color='pink', node_size=30, alpha=0.8, font_size=2,
        edge_color=n1['Capacity'], width=1.0, figsize = (18,18), style="solid", edge_cmap=plt.cm.jet)

# Save the Figure
plt.savefig('Network.png', dpi=1000, facecolor='w', edgecolor='w',orientation='portrait',
            papertype=None, format=None,transparent=False, bbox_inches=None, pad_inches=0.1)

However, the colors do not follow the capacity values. I will share an example.
Here is the case where it unnecessarily changes color

Another example - Here the colors should change, but it does not

The excel files are here for reference

Also, if you can suggest how to add a color-bar to this, it would be great.


问:
OpenGraph data won't show up on linkedin share
When sharing the URL on LinkedIn, the OpenGraph data won't show up. I did validate the data. Is this maybe a domain issue?

The url i tried to share was:
https://overons.kpn/en/news/2017/kpn-and-major-suppliers-aim-for-circular-operation-by-2025

edit: following error was thrown on just the domain: i18n_url_preview_error

答:
Works perfectly fine for me.  As usual, make sure you are URL-encoding your parameters...

```<code>https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fwww.overons.kpn%2Fen%2Fnews%2F2017%2Fkpn-and-major-suppliers-aim-for-circular-operation-by-2025
</code>```

See:

Maybe it was rejecting .kpn domains previously, but it seems to be good and working now!

Body:
Works perfectly fine for me.  As usual, make sure you are URL-encoding your parameters...

https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fwww.overons.kpn%2Fen%2Fnews%2F2017%2Fkpn-and-major-suppliers-aim-for-circular-operation-by-2025

See:

Maybe it was rejecting .kpn domains previously, but it seems to be good and working now!