问:
Spring API doesn't login and send infos (get&set) to React with JWT with same code
The title is self explanatory, I have this API made in Spring, and after JWT implementation I can login, but the gets doesn't work anymore.

But if I comment the the CorsConfigurationSource corsConfigurationSource() and the Lombok annotation @RequiredArgsConstructor in SecurityConfig, the login stop to work, but all the gets work beautifully.

I'll post the class SecurityConfig, AuthorizationFilter and the AuthenticationFilter respectively for you guys try to see whats going wrong.

```<code>import org.alterdata.shopback.app.security.AuthenticationFilter;
import org.alterdata.shopback.app.security.AuthorizationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import lombok.RequiredArgsConstructor;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        AuthenticationFilter authenticationFilter = new AuthenticationFilter(authenticationManagerBean());
        http.cors().and().csrf().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.authorizeRequests().antMatchers("/login").permitAll()
        .antMatchers("/cadastrar/**").hasAnyAuthority("ADMIN")
        .antMatchers("/cadastro/**").hasAnyAuthority("ADMIN")
        .anyRequest().authenticated();
        http.addFilter(authenticationFilter);
        http.addFilterBefore(new AuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }

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

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE","OPTIONS", "HEAD"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
            return source;
        }
}

</code>```
```<code>import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.auth0.jwt.exceptions.JWTVerificationException;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.fasterxml.jackson.databind.ObjectMapper;

import net.bytebuddy.implementation.bind.annotation.IgnoreForBinding.Verifier;

import static org.springframework.util.MimeTypeUtils.APPLICATION_JSON_VALUE;

@Slf4j
public class AuthorizationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        if(request.getServletPath().equals("/login")) {
            filterChain.doFilter(request, response);
        }else {
            String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
            if(authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
                try {
                String token = authorizationHeader.substring("Bearer ".length());
                Algorithm algorithm = Algorithm.HMAC256("segredinho".getBytes());
                JWTVerifier jwtVerifier = JWT.require(algorithm).build();
                DecodedJWT decodedJWT = jwtVerifier.verify(token);
                String user = decodedJWT.getSubject();
                String [] roles = decodedJWT.getClaim("roles").asArray(String.class);
                Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
                Arrays.stream(roles).forEach(role ->{
                    authorities.add(new SimpleGrantedAuthority(role));
                });
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user,null, authorities);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                filterChain.doFilter(request, response);

            }catch(Exception e){
                    log.error("erro ao realizar o login! {}", e.getMessage());
                    response.setHeader("erro", e.getMessage());
                    response.setStatus(401);
                    Map<String, String> error = new HashMap<>();
                    error.put("mensagem de erro", e.getMessage());
                    response.setContentType(APPLICATION_JSON_VALUE);
                    new ObjectMapper().writeValue(response.getOutputStream(), error);
                }
            }else {
                filterChain.doFilter(request, response);
            }
            }
        }
    }

</code>```
```<code>import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.web.bind.annotation.CrossOrigin;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

@CrossOrigin(origins = {"*"})
public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private final AuthenticationManager authenticationManager;

    public AuthenticationFilter (AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        try{
            String nome = request.getParameter("nome");
            String senha = request.getParameter("senha");
            UsernamePasswordAuthenticationToken uspsToken = new UsernamePasswordAuthenticationToken(nome, senha);
            //response.setHeader("teste", String.valueOf(uspsToken));
            return authenticationManager.authenticate(uspsToken);
        }catch (Exception e){
            throw new  RuntimeException();
        }

    }

//  @Override
//  public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
//          throws AuthenticationException {
//      try{
//  UserPasswordAuthRequest userPasswordAuthRequest = new ObjectMapper()
//              .readValue(request.getInputStream(), UserPasswordAuthRequest.class);
//
//          Authentication authentication = new UsernamePasswordAuthenticationToken(
//                  userPasswordAuthRequest.getNome(),
//                  userPasswordAuthRequest.getSenha()
//          );
//          return authenticationManager.authenticate(authentication);
//      }catch (IOException e){
//          throw new  RuntimeException();
//      }
//  }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
            Authentication authResult) throws IOException, ServletException {
        User user = (User) authResult.getPrincipal();
        Algorithm algorithm = Algorithm.HMAC256("segredinho".getBytes());
        String tokenAcesso = JWT.create().withSubject(user.getUsername())
                .withExpiresAt(new Date(System.currentTimeMillis() + 10*60*1000*60))
                .withIssuer(request.getRequestURL()
                        .toString()).withClaim("roles", user.getAuthorities()
                                .stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()))
                .sign(algorithm);
        String tokenRefresh = JWT.create().withSubject(user.getUsername())
                .withExpiresAt(new Date(System.currentTimeMillis() + 10*60*1000*60))
                .withIssuer(request.getRequestURL()
                        .toString()).withClaim("roles", user.getAuthorities()
                                .stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()))
                .sign(algorithm);
        Map<String, String> tokens = new HashMap<>();
        tokens.put("tokenacesso", tokenAcesso);
        tokens.put("tokenrefresh", tokenRefresh);
        response.setContentType(APPLICATION_JSON_VALUE);
        new ObjectMapper().writeValue(response.getOutputStream(),tokens);
    }

}

</code>```

答:
First try to call your api with Postman, else i think you need to add authorization jwt header to every api request after you login.

```<code>    export default function authHeader() {
  const user = JSON.parse(localStorage.getItem('user'));
  if (user && user.accessToken) {
    return { Authorization: 'Bearer ' + user.accessToken };
  } else {
    return {};
  }
}
</code>```

and then call your api like this:

```<code>return axios.get(API_URL + 'user', { headers: authHeader() });
</code>```

for more informations try to visit: https://www.bezkoder.com/react-jwt-auth/

Body:
The title is self explanatory, I have this API made in Spring, and after JWT implementation I can login, but the gets doesn't work anymore.

But if I comment the the CorsConfigurationSource corsConfigurationSource() and the Lombok annotation @RequiredArgsConstructor in SecurityConfig, the login stop to work, but all the gets work beautifully.

I'll post the class SecurityConfig, AuthorizationFilter and the AuthenticationFilter respectively for you guys try to see whats going wrong.

import org.alterdata.shopback.app.security.AuthenticationFilter;
import org.alterdata.shopback.app.security.AuthorizationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import lombok.RequiredArgsConstructor;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        AuthenticationFilter authenticationFilter = new AuthenticationFilter(authenticationManagerBean());
        http.cors().and().csrf().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.authorizeRequests().antMatchers("/login").permitAll()
        .antMatchers("/cadastrar/**").hasAnyAuthority("ADMIN")
        .antMatchers("/cadastro/**").hasAnyAuthority("ADMIN")
        .anyRequest().authenticated();
        http.addFilter(authenticationFilter);
        http.addFilterBefore(new AuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }

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

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE","OPTIONS", "HEAD"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
            return source;
        }
}

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.auth0.jwt.exceptions.JWTVerificationException;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.fasterxml.jackson.databind.ObjectMapper;

import net.bytebuddy.implementation.bind.annotation.IgnoreForBinding.Verifier;

import static org.springframework.util.MimeTypeUtils.APPLICATION_JSON_VALUE;

@Slf4j
public class AuthorizationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        if(request.getServletPath().equals("/login")) {
            filterChain.doFilter(request, response);
        }else {
            String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
            if(authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
                try {
                String token = authorizationHeader.substring("Bearer ".length());
                Algorithm algorithm = Algorithm.HMAC256("segredinho".getBytes());
                JWTVerifier jwtVerifier = JWT.require(algorithm).build();
                DecodedJWT decodedJWT = jwtVerifier.verify(token);
                String user = decodedJWT.getSubject();
                String [] roles = decodedJWT.getClaim("roles").asArray(String.class);
                Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
                Arrays.stream(roles).forEach(role ->{
                    authorities.add(new SimpleGrantedAuthority(role));
                });
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user,null, authorities);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                filterChain.doFilter(request, response);

            }catch(Exception e){
                    log.error("erro ao realizar o login! {}", e.getMessage());
                    response.setHeader("erro", e.getMessage());
                    response.setStatus(401);
                    Map<String, String> error = new HashMap<>();
                    error.put("mensagem de erro", e.getMessage());
                    response.setContentType(APPLICATION_JSON_VALUE);
                    new ObjectMapper().writeValue(response.getOutputStream(), error);
                }
            }else {
                filterChain.doFilter(request, response);
            }
            }
        }
    }

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.web.bind.annotation.CrossOrigin;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

@CrossOrigin(origins = {"*"})
public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private final AuthenticationManager authenticationManager;

    public AuthenticationFilter (AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        try{
            String nome = request.getParameter("nome");
            String senha = request.getParameter("senha");
            UsernamePasswordAuthenticationToken uspsToken = new UsernamePasswordAuthenticationToken(nome, senha);
            //response.setHeader("teste", String.valueOf(uspsToken));
            return authenticationManager.authenticate(uspsToken);
        }catch (Exception e){
            throw new  RuntimeException();
        }

    }

//  @Override
//  public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
//          throws AuthenticationException {
//      try{
//  UserPasswordAuthRequest userPasswordAuthRequest = new ObjectMapper()
//              .readValue(request.getInputStream(), UserPasswordAuthRequest.class);
//
//          Authentication authentication = new UsernamePasswordAuthenticationToken(
//                  userPasswordAuthRequest.getNome(),
//                  userPasswordAuthRequest.getSenha()
//          );
//          return authenticationManager.authenticate(authentication);
//      }catch (IOException e){
//          throw new  RuntimeException();
//      }
//  }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
            Authentication authResult) throws IOException, ServletException {
        User user = (User) authResult.getPrincipal();
        Algorithm algorithm = Algorithm.HMAC256("segredinho".getBytes());
        String tokenAcesso = JWT.create().withSubject(user.getUsername())
                .withExpiresAt(new Date(System.currentTimeMillis() + 10*60*1000*60))
                .withIssuer(request.getRequestURL()
                        .toString()).withClaim("roles", user.getAuthorities()
                                .stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()))
                .sign(algorithm);
        String tokenRefresh = JWT.create().withSubject(user.getUsername())
                .withExpiresAt(new Date(System.currentTimeMillis() + 10*60*1000*60))
                .withIssuer(request.getRequestURL()
                        .toString()).withClaim("roles", user.getAuthorities()
                                .stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()))
                .sign(algorithm);
        Map<String, String> tokens = new HashMap<>();
        tokens.put("tokenacesso", tokenAcesso);
        tokens.put("tokenrefresh", tokenRefresh);
        response.setContentType(APPLICATION_JSON_VALUE);
        new ObjectMapper().writeValue(response.getOutputStream(),tokens);
    }

}

Body:
First try to call your api with Postman, else i think you need to add authorization jwt header to every api request after you login.

    export default function authHeader() {
  const user = JSON.parse(localStorage.getItem('user'));
  if (user && user.accessToken) {
    return { Authorization: 'Bearer ' + user.accessToken };
  } else {
    return {};
  }
}

and then call your api like this:

return axios.get(API_URL + 'user', { headers: authHeader() });

for more informations try to visit: https://www.bezkoder.com/react-jwt-auth/


来源: stackexchange

问:
it is showing "listarr.forEach" is not a function
I am getting this error
it is showing listarr.forEach is not a function.

```<code>let newLiTag='';

listArr.forEach((element, index) =>{
  newLiTag+= `<li> ${element} <span class="check" onclick="check(${index})"> <i class="fas fa-check"></i></span>

 <span onclick = "modify(${index})"><i class="fas fa-edit"></i></span>

 <span onclick = "deleteTask(${index})"><i class="fas fa-trash"></i></span> </li>`;
});
</code>```

答:
Please check if you have declared the variable listArr.
Example:</p>
```<code>let newLiTag='';
const listArr = []; // Add variable listArr here

listArr.forEach((element, index) =>{
    // Do things here
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am getting this error
it is showing listarr.forEach is not a function.

let newLiTag='';

listArr.forEach((element, index) =>{
  newLiTag+= `
 ${element}

`;
});

Body:
Please check if you have declared the variable listArr.
Example:

let newLiTag='';
const listArr = []; // Add variable listArr here

listArr.forEach((element, index) =>{
    // Do things here
});


问:
Metal MTLGetWarningMode + 218 SIGABRT ABORT
I have this error, catched by Crashlytics, Flutter, iOS:
Crashed: io.flutter.1.io
SIGABRT ABORT 0x00000001b624d414

the full error text is:

```<code>Crashed: io.flutter.1.io
0  libsystem_kernel.dylib         0x1b624d414 __pthread_kill + 8
1  libsystem_pthread.dylib        0x1d3da8b50 pthread_kill + 272
2  libsystem_c.dylib              0x19172bb74 abort + 104
3  Metal                          0x19eb219d4 MTLGetWarningMode + 218
4  IOGPU                          0x1c5828490 -[IOGPUMetalCommandBuffer pushDebugGroup:] + 242
5  Metal                          0x19eb11990 -[_MTLCommandEncoder initWithCommandBuffer:] + 884
6  IOGPU                          0x1c582a140 -[IOGPUMetalCommandEncoder initWithCommandBuffer:] + 56
7  AGXMetalA13                    0x1d54462b4 (Missing)
8  AGXMetalA13                    0x1d5189770 (Missing)
9  Flutter                        0x101c39b00 (Missing)
10 Flutter                        0x101c3c9bc (Missing)
11 Flutter                        0x101b42d84 (Missing)
12 Flutter                        0x101b5596c (Missing)
13 Flutter                        0x101b4ec70 (Missing)
14 Flutter                        0x101b6c7b8 (Missing)
15 Flutter                        0x101b4e830 (Missing)
16 Flutter                        0x101b27458 (Missing)
17 Flutter                        0x101becedc (Missing)
18 Flutter                        0x101dbfc10 (Missing)
19 Flutter                        0x101c9dfc4 (Missing)
20 Flutter                        0x101c9fe24 (Missing)
21 CoreFoundation                 0x188279fa0 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 32
22 CoreFoundation                 0x188279ba0 __CFRunLoopDoTimer + 1064
23 CoreFoundation                 0x188278ffc __CFRunLoopDoTimers + 328
24 CoreFoundation                 0x188272ee4 __CFRunLoopRun + 1936
25 CoreFoundation                 0x18827221c CFRunLoopRunSpecific + 600
26 Flutter                        0x101c9fd00 (Missing)
27 Flutter                        0x101c9f704 (Missing)
28 libsystem_pthread.dylib        0x1d3da7cb0 _pthread_start + 320
29 libsystem_pthread.dylib        0x1d3db0778 thread_start + 8

crash_info_entry_0
abort() called
</code>```

This error occurs, when i use background location updates (package background_location: ^0.4.3), to determine the users location and show the location on a flutter map (flutter_map: ^0.12.0).
HAve anybody an idea, what this error means, and how to resolve/avoid it? Thanks for any help!

答:
Also the same is happening to me, IDK exactly what happended. It just crash one time on an iPhone XR</p>
```<code>Crashed: io.flutter.1.raster
0  libsystem_kernel.dylib         0x7964 __pthread_kill + 8
1  libsystem_pthread.dylib        0x7378 pthread_kill + 268
2  libsystem_c.dylib              0x1ff50 abort + 164
3  Metal                          0xbe390 MTLGetWarningMode + 218
4  IOGPU                          0x3ba8 IOGPUResourceGetClientShared + 242
5  Metal                          0x146b0 -[_MTLCommandEncoder initWithCommandBuffer:] + 884
6  IOGPU                          0x5824 -[IOGPUMetalCommandEncoder initWithCommandBuffer:] + 56
7  AGXMetalA12                    0xe24ac (Falta UUID a2eac9f81f443d8aa0602263579fe05e)
8  AGXMetalA12                    0x32d5c (Falta UUID a2eac9f81f443d8aa0602263579fe05e)
9  Flutter                        0x287de8 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
10 Flutter                        0x28e4a8 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
11 Flutter                        0x28b584 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
12 Flutter                        0x19cfd0 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
13 Flutter                        0x1920c4 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
14 Flutter                        0x1924b0 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
15 Flutter                        0x58c34 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
16 Flutter                        0x4f63f0 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
17 Flutter                        0x409fc4 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
18 Flutter                        0x341d3c (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
19 Flutter                        0x349bd4 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
20 Flutter                        0x2ee068 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
21 Flutter                        0x2f1098 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
22 CoreFoundation                 0xae268 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 32
23 CoreFoundation                 0x32c40 __CFRunLoopDoTimer + 1076
24 CoreFoundation                 0x2d43c __CFRunLoopDoTimers + 328
25 CoreFoundation                 0xbc58 __CFRunLoopRun + 1944
26 CoreFoundation                 0x1f3b8 CFRunLoopRunSpecific + 600
27 Flutter                        0x2f0f74 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
28 Flutter                        0x2f0788 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
29 libsystem_pthread.dylib        0x19a4 _pthread_start + 148
30 libsystem_pthread.dylib        0xea0 thread_start + 8
</code>```

Body:
I have this error, catched by Crashlytics, Flutter, iOS:
Crashed: io.flutter.1.io
SIGABRT ABORT 0x00000001b624d414

the full error text is:

Crashed: io.flutter.1.io
0  libsystem_kernel.dylib         0x1b624d414 __pthread_kill + 8
1  libsystem_pthread.dylib        0x1d3da8b50 pthread_kill + 272
2  libsystem_c.dylib              0x19172bb74 abort + 104
3  Metal                          0x19eb219d4 MTLGetWarningMode + 218
4  IOGPU                          0x1c5828490 -[IOGPUMetalCommandBuffer pushDebugGroup:] + 242
5  Metal                          0x19eb11990 -[_MTLCommandEncoder initWithCommandBuffer:] + 884
6  IOGPU                          0x1c582a140 -[IOGPUMetalCommandEncoder initWithCommandBuffer:] + 56
7  AGXMetalA13                    0x1d54462b4 (Missing)
8  AGXMetalA13                    0x1d5189770 (Missing)
9  Flutter                        0x101c39b00 (Missing)
10 Flutter                        0x101c3c9bc (Missing)
11 Flutter                        0x101b42d84 (Missing)
12 Flutter                        0x101b5596c (Missing)
13 Flutter                        0x101b4ec70 (Missing)
14 Flutter                        0x101b6c7b8 (Missing)
15 Flutter                        0x101b4e830 (Missing)
16 Flutter                        0x101b27458 (Missing)
17 Flutter                        0x101becedc (Missing)
18 Flutter                        0x101dbfc10 (Missing)
19 Flutter                        0x101c9dfc4 (Missing)
20 Flutter                        0x101c9fe24 (Missing)
21 CoreFoundation                 0x188279fa0 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 32
22 CoreFoundation                 0x188279ba0 __CFRunLoopDoTimer + 1064
23 CoreFoundation                 0x188278ffc __CFRunLoopDoTimers + 328
24 CoreFoundation                 0x188272ee4 __CFRunLoopRun + 1936
25 CoreFoundation                 0x18827221c CFRunLoopRunSpecific + 600
26 Flutter                        0x101c9fd00 (Missing)
27 Flutter                        0x101c9f704 (Missing)
28 libsystem_pthread.dylib        0x1d3da7cb0 _pthread_start + 320
29 libsystem_pthread.dylib        0x1d3db0778 thread_start + 8

crash_info_entry_0
abort() called

This error occurs, when i use background location updates (package background_location: ^0.4.3), to determine the users location and show the location on a flutter map (flutter_map: ^0.12.0).
HAve anybody an idea, what this error means, and how to resolve/avoid it? Thanks for any help!

Body:
Also the same is happening to me, IDK exactly what happended. It just crash one time on an iPhone XR

Crashed: io.flutter.1.raster
0  libsystem_kernel.dylib         0x7964 __pthread_kill + 8
1  libsystem_pthread.dylib        0x7378 pthread_kill + 268
2  libsystem_c.dylib              0x1ff50 abort + 164
3  Metal                          0xbe390 MTLGetWarningMode + 218
4  IOGPU                          0x3ba8 IOGPUResourceGetClientShared + 242
5  Metal                          0x146b0 -[_MTLCommandEncoder initWithCommandBuffer:] + 884
6  IOGPU                          0x5824 -[IOGPUMetalCommandEncoder initWithCommandBuffer:] + 56
7  AGXMetalA12                    0xe24ac (Falta UUID a2eac9f81f443d8aa0602263579fe05e)
8  AGXMetalA12                    0x32d5c (Falta UUID a2eac9f81f443d8aa0602263579fe05e)
9  Flutter                        0x287de8 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
10 Flutter                        0x28e4a8 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
11 Flutter                        0x28b584 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
12 Flutter                        0x19cfd0 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
13 Flutter                        0x1920c4 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
14 Flutter                        0x1924b0 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
15 Flutter                        0x58c34 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
16 Flutter                        0x4f63f0 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
17 Flutter                        0x409fc4 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
18 Flutter                        0x341d3c (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
19 Flutter                        0x349bd4 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
20 Flutter                        0x2ee068 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
21 Flutter                        0x2f1098 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
22 CoreFoundation                 0xae268 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 32
23 CoreFoundation                 0x32c40 __CFRunLoopDoTimer + 1076
24 CoreFoundation                 0x2d43c __CFRunLoopDoTimers + 328
25 CoreFoundation                 0xbc58 __CFRunLoopRun + 1944
26 CoreFoundation                 0x1f3b8 CFRunLoopRunSpecific + 600
27 Flutter                        0x2f0f74 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
28 Flutter                        0x2f0788 (Falta UUID e01ae2d7b4293d2bad99555f1db36746)
29 libsystem_pthread.dylib        0x19a4 _pthread_start + 148
30 libsystem_pthread.dylib        0xea0 thread_start + 8


问:
Linux - Open socket for specific network adapter
The problem

I have a computer that is supposed to connect to two machines (or rather sets of individual devices) via TCP. To make things tricky, these two machines share the same IP address range and also have partially identical addresses, only one is connected via one ethernet adapter and the other one via a second ethernet adapter.

Note: The address ranges were not defined by me, but by the manufacturers of these machines. I unfortunately have to live with them, as they are.

The program that should do that job is written in C/C++. The connections are outgoing from the program's point of view, so I can't just bind incoming connections and keep their id.

Possible solution

After some research (e.g. here: Problems with SO_BINDTODEVICE Linux socket option), I tried to bind the socket to a device using

```<code>setsockopt(socket, SOL_SOCKET, SO_BINDTODEVICE, "adapter name", strlen("adapter name");
</code>```

As it turns out, this would only work, if the program was run with superuser privileges, which I would try to avoid. Otherwise, the function returns an error code, which translates to permission denied (I forgot the exact phrase).

Other solutions?

Is there any other way, how I could achieve that?

答:
Just pinning the sockets to a specific interface wouldn't do the job, since there are much more things going on... If you connect say to 192.168.0.3, the kernel looks into the routing table to find the right interface to send the packet over. You cannot have two entries in the routing table with the same subnet specification (192.168.0.0/24) if you want to use IP communication. There are two solutions that come into my mind:

setup prerouting NATs for the adapters to map the addresses. For example you can map all source addesses from packages recieved by eth0 into the 192.168.0.0\24 range and all those recieved by eth1 to 192.168.1.0\24. If you add this address translation in the prerouting filter chain, the kernel won't even notice that the subnets internally use the same ip address range.

If there are no duplicated ip addresses (like e.g. 192.168.0.2 in both the networks), you can setup a bridge interface. The bridge behaves like one interface, that is connected to both the networks. A bridge behaves just like a software switch. To the kernel (and to your program) it looks, as if there was only one adapter, where all the devices are plugged into.

Both solutions require superuser priviledges to setup, but after you have setup them once, your program won't need them.

Body:
The problem

I have a computer that is supposed to connect to two machines (or rather sets of individual devices) via TCP. To make things tricky, these two machines share the same IP address range and also have partially identical addresses, only one is connected via one ethernet adapter and the other one via a second ethernet adapter.

Note: The address ranges were not defined by me, but by the manufacturers of these machines. I unfortunately have to live with them, as they are.

The program that should do that job is written in C/C++. The connections are outgoing from the program's point of view, so I can't just bind incoming connections and keep their id.

Possible solution

After some research (e.g. here: Problems with SO_BINDTODEVICE Linux socket option), I tried to bind the socket to a device using

setsockopt(socket, SOL_SOCKET, SO_BINDTODEVICE, "adapter name", strlen("adapter name");

As it turns out, this would only work, if the program was run with superuser privileges, which I would try to avoid. Otherwise, the function returns an error code, which translates to permission denied (I forgot the exact phrase).

Other solutions?

Is there any other way, how I could achieve that?


问:
Duplicate Loader's content multiple times via addChild()?
I have small problem. I'm dynamically loading JPG file using Loader class. Everything works except if I want to tile the image few more times using addChild(loader.content) it just doesn't work. It always removes previous instance and leaves only the last one. I've tried everything but with no luck. Here's my code:

```<code>var loaderContext:LoaderContext = new LoaderContext(true);
var imageLoader:Loader = new Loader();
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaderDone);
var fileRequest:URLRequest = new URLRequest('http://127.0.0.1/blah/blah.jpg');
imageLoader.load(fileRequest, loaderContext);

var imageLoaderDone:Function = function(e){
    var k:int = landHolder.numChildren;
    while(k--) {
        landHolder.removeChildAt(k);
    }
    var howManyTimes:int = Math.ceil(1000 / e.content.width);

    var i:int = 0;
    while(i < howManyTimes) {
        var zombie:Sprite = new Sprite();
        zombie.addChild(e.content);
        zombie.x = i*zombie.width;
        landHolder.addChild(zombie); //here's the problem, it does not duplicate
        //landHolder is empty MovieClip placed on the stage
        i++;
    }

    landHolder.alpha = 1

}
</code>```

Thanks.

答:
In case of a loaded image, you could simply clone its bitmap data.

```<code>var loadedBitmap : Bitmap = e.content as Bitmap;
var clonedBitmap : Bitmap;
for(var i:Number = 0; i<100; i++) {
    clonedBitmap = new Bitmap(loadedBitmap.bitmapData.clone());
    clonedBitmap.x = i*clonedBitmap.width;
    landHolder.addChild(clonedBitmap);
}
</code>```

The other suggested solutions are good alternatives when you need to clone more than a simple image.

ContentLicense: CC BY-SA 3.0

Body:
I have small problem. I'm dynamically loading JPG file using Loader class. Everything works except if I want to tile the image few more times using addChild(loader.content) it just doesn't work. It always removes previous instance and leaves only the last one. I've tried everything but with no luck. Here's my code:

var loaderContext:LoaderContext = new LoaderContext(true);
var imageLoader:Loader = new Loader();
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaderDone);
var fileRequest:URLRequest = new URLRequest('http://127.0.0.1/blah/blah.jpg');
imageLoader.load(fileRequest, loaderContext);

var imageLoaderDone:Function = function(e){
    var k:int = landHolder.numChildren;
    while(k--) {
        landHolder.removeChildAt(k);
    }
    var howManyTimes:int = Math.ceil(1000 / e.content.width);

    var i:int = 0;
    while(i < howManyTimes) {
        var zombie:Sprite = new Sprite();
        zombie.addChild(e.content);
        zombie.x = i*zombie.width;
        landHolder.addChild(zombie); //here's the problem, it does not duplicate
        //landHolder is empty MovieClip placed on the stage
        i++;
    }

    landHolder.alpha = 1

}

Thanks.

Body:
In case of a loaded image, you could simply clone its bitmap data.

var loadedBitmap : Bitmap = e.content as Bitmap;
var clonedBitmap : Bitmap;
for(var i:Number = 0; i<100; i++) {
    clonedBitmap = new Bitmap(loadedBitmap.bitmapData.clone());
    clonedBitmap.x = i*clonedBitmap.width;
    landHolder.addChild(clonedBitmap);
}

The other suggested solutions are good alternatives when you need to clone more than a simple image.


问:
How to serialize an object containing an XML property
Note this is .NET 4.8

I have created this sample code to illustrate the problem

[XmlRoot(ElementName = "RESULT", Namespace = "", IsNullable = false)]
public class Result
{
    public string Message { get; set; }

    public XElement Stuff { get; set; }

    public override string ToString()
    {
        var ser = new XmlSerializer(GetType());

        using (var stream = new StringWriter())
        {
            ser.Serialize(stream, this);
            return stream.ToString();
        }
    }
}
```
<p>I will have some <code>XML</code> already that looks like this</p>
<pre class="lang-xml prettyprint-override"><code><FOO>
      <BAR>Hello World</BAR>
      <BAR2>Hello World</BAR2>
      <BAR3>Hello World</BAR3>
</FOO>
</code>```

This is assigned to the XElement Stuff property and when an instance of Result is then serialized, you get this XML:

<?xml version="1.0" encoding="utf-16"?>
<RESULT xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Message>Hello World</Message>
  <Stuff>
    <FOO>
      <BAR>Hello World</BAR>
      <BAR2>Hello World</BAR2>
      <BAR3>Hello World</BAR3>
    </FOO>
  </Stuff>
</RESULT>
```
<p>Question: Is there any way to get this result instead?</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-16"?>
<RESULT xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Message>Hello World</Message>
  <FOO>
    <BAR>Hello World</BAR>
    <BAR2>Hello World</BAR2>
    <BAR3>Hello World</BAR3>
  </FOO>
</RESULT>
</code>```

Note: FOO could be Stuff - I don't care (because I know how to change that name) I just don't want two levels of nested XML for that property in the serialised XML

You can play with the sample code here

答:
If you're happy for the root name to be hard-coded, then you can write a wrapper type for the elements and implement IXmlSerializable within.

This is likely preferable to implementing in Result, as I imagine the real type would have more than 2 properties.

A quick and dirty example - I'll leave implementing ReadXml to you (if you need it):

```<code>public class ElementsWrapper : IXmlSerializable
{
    public XElement[] Elements { get; set; }

    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
    }

    public void WriteXml(XmlWriter writer)
    {
        foreach (var element in Elements)
        {
            element.WriteTo(writer);
        }
    }
}
</code>```

And change your property in Result to:

```<code>public ElementsWrapper FOO { get; set; }
</code>```

When used, the serialiser for Result will write <FOO>, then delegate to the custom serialisation, and then write </FOO>.

You can see an updated fiddle here.

Body:
Note this is .NET 4.8

I have created this sample code to illustrate the problem

[XmlRoot(ElementName = "RESULT", Namespace = "", IsNullable = false)]
public class Result
{
    public string Message { get; set; }

    public XElement Stuff { get; set; }

    public override string ToString()
    {
        var ser = new XmlSerializer(GetType());

        using (var stream = new StringWriter())
        {
            ser.Serialize(stream, this);
            return stream.ToString();
        }
    }
}

I will have some XML already that looks like this

<FOO>
      <BAR>Hello World</BAR>
      <BAR2>Hello World</BAR2>
      <BAR3>Hello World</BAR3>
</FOO>

This is assigned to the XElement Stuff property and when an instance of Result is then serialized, you get this XML:

<?xml version="1.0" encoding="utf-16"?>
<RESULT xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Message>Hello World</Message>
  <Stuff>
    <FOO>
      <BAR>Hello World</BAR>
      <BAR2>Hello World</BAR2>
      <BAR3>Hello World</BAR3>
    </FOO>
  </Stuff>
</RESULT>

Question: Is there any way to get this result instead?

<?xml version="1.0" encoding="utf-16"?>
<RESULT xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Message>Hello World</Message>
  <FOO>
    <BAR>Hello World</BAR>
    <BAR2>Hello World</BAR2>
    <BAR3>Hello World</BAR3>
  </FOO>
</RESULT>

Note: FOO could be Stuff - I don't care (because I know how to change that name) I just don't want two levels of nested XML for that property in the serialised XML

You can play with the sample code here

Body:
If you're happy for the root name to be hard-coded, then you can write a wrapper type for the elements and implement IXmlSerializable within.

This is likely preferable to implementing in Result, as I imagine the real type would have more than 2 properties.

A quick and dirty example - I'll leave implementing ReadXml to you (if you need it):

public class ElementsWrapper : IXmlSerializable
{
    public XElement[] Elements { get; set; }

    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
    }

    public void WriteXml(XmlWriter writer)
    {
        foreach (var element in Elements)
        {
            element.WriteTo(writer);
        }
    }
}

And change your property in Result to:

public ElementsWrapper FOO { get; set; }

When used, the serialiser for Result will write <FOO>, then delegate to the custom serialisation, and then write </FOO>.

You can see an updated fiddle here.


问:
Querying Postgres through Babelfish
I am connected over TDS (1433) to a Postgres/Aurora (babelfish-enabled) database.

I can run the following three queries from my application and I receive confusing responses:

```<code>SELECT current_database()

SELECT * FROM information_schema.tables WHERE table_name = 'PERSON'

SELECT COUNT(1) FROM "PERSON"
</code>```

The responses are:

```<code>current_database":"babelfish_db"

"table_catalog":"babelfish_db","table_schema":"public","table_name":"PERSON","table_type":"BASE TABLE"...}

relation "person" does not exist
</code>```

I simply cannot query the PERSON table. I have tried:

```<code>"PERSON"
"person"
PERSON
person
public.PERSON
public.person
public."PERSON"
</code>```

I have ensured the user I am connecting as has access to the database, schema and tables:

```<code>GRANT CONNECT ON DATABASE babelfish_db TO popweb;
GRANT USAGE ON SCHEMA public TO popweb;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO popweb;
</code>```

Still, I cannot access the table. I feel like such a boob/noob

For anyone who has connected to Postgres via Babelfish, what am I doing wrong?

答:
The GA release of Babelfish didn't make any modifications to the PostgreSQL implementation of the information schema. So, what you see is the physical database of babelfish_db and the public schema. It looks like you created the table using the PostgreSQL endpoint.

To work with tables in Babelfish at this time, you need to create a T-SQL virtual database and your tables inside of that database using the T-SQL endpoint - just like you did before.

For example using SSMS and a new query connected to your Babelfish endpoint. You should notice in the SSMS database drop down and in the status bar that your context shows you are in the master database.

```<code>    CREATE DATABASE ford_prefect;
    GO
    USE ford_prefect;
    GO
    CREATE SCHEMA school;
    GO
    CREATE TABLE [School].[Person](
        [PersonID] [int] NOT NULL,
        [LastName] [nvarchar](50) NOT NULL,
        [FirstName] [nvarchar](50) NOT NULL,
        [HireDate] [datetime] NULL,
        [EnrollmentDate] [datetime] NULL,
        [Discriminator] [nvarchar](50) NOT NULL,
    CONSTRAINT [PK_School.Student] PRIMARY KEY CLUSTERED
    (
        [PersonID] ASC
    )
    GO
</code>```

At this point you can add records via INSERT and select the table without issues.
Cheers,

Bill Ramos

Aurora PostgreSQL Babelfish PM, Amazon

Title: Querying Postgres through Babelfish

Body:
I am connected over TDS (1433) to a Postgres/Aurora (babelfish-enabled) database.

I can run the following three queries from my application and I receive confusing responses:

SELECT current_database()

SELECT * FROM information_schema.tables WHERE table_name = 'PERSON'

SELECT COUNT(1) FROM "PERSON"

The responses are:

current_database":"babelfish_db"

"table_catalog":"babelfish_db","table_schema":"public","table_name":"PERSON","table_type":"BASE TABLE"...}

relation "person" does not exist

I simply cannot query the PERSON table. I have tried:

"PERSON"
"person"
PERSON
person
public.PERSON
public.person
public."PERSON"

I have ensured the user I am connecting as has access to the database, schema and tables:

GRANT CONNECT ON DATABASE babelfish_db TO popweb;
GRANT USAGE ON SCHEMA public TO popweb;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO popweb;

Still, I cannot access the table. I feel like such a boob/noob

For anyone who has connected to Postgres via Babelfish, what am I doing wrong?

Body:
The GA release of Babelfish didn't make any modifications to the PostgreSQL implementation of the information schema. So, what you see is the physical database of babelfish_db and the public schema. It looks like you created the table using the PostgreSQL endpoint.

To work with tables in Babelfish at this time, you need to create a T-SQL virtual database and your tables inside of that database using the T-SQL endpoint - just like you did before.

For example using SSMS and a new query connected to your Babelfish endpoint. You should notice in the SSMS database drop down and in the status bar that your context shows you are in the master database.

    CREATE DATABASE ford_prefect;
    GO
    USE ford_prefect;
    GO
    CREATE SCHEMA school;
    GO
    CREATE TABLE [School].[Person](
        [PersonID] [int] NOT NULL,
        [LastName] [nvarchar](50) NOT NULL,
        [FirstName] [nvarchar](50) NOT NULL,
        [HireDate] [datetime] NULL,
        [EnrollmentDate] [datetime] NULL,
        [Discriminator] [nvarchar](50) NOT NULL,
    CONSTRAINT [PK_School.Student] PRIMARY KEY CLUSTERED
    (
        [PersonID] ASC
    )
    GO

At this point you can add records via INSERT and select the table without issues.
Cheers,

Bill Ramos

Aurora PostgreSQL Babelfish PM, Amazon


问:
What does this lambda mean? (Python, Numpy, Rotation Matrix, Robotics)
In my class, we are learning how to use Python to code robot poses. Specifically, creating a rotation matrix and translation matrix with numpy to represent these relative poses.

The one thing I don't understand is how our lab assistant demonstrated how to create the rotation matrix. I was able to create it a similar way on my own but I'd like to understand what he did. Here is the example he provided:

```<code>Rot = lambda theta: [[np.cos(theta), -np.sin(theta)],
                     [np.sin(theta), np.cos(theta)]]

R = Rot(np.pi/3)
R
</code>```

Can someone explain what is the Rot = lambda theta:  code means? When I did it on my own I just created a variable theta and the equation for Rot with the variable theta inside of it in the appropriate places. I do not understand what this lambda means.

答:
It's the equivalent of this:

```<code>def Rot(theta):
    return [[np.cos(theta), -np.sin(theta)],
            [np.sin(theta), np.cos(theta)]]
</code>```

The code lambda param1, param2: return_value creates a function with param1 and param2 as parameters, the code after the colon (:) is automatically run and returned when you call the function. Rot =  is simply assigning the resulting lambda function to the Rot variable, and since all functions are actually variables, that works.

Body:
In my class, we are learning how to use Python to code robot poses. Specifically, creating a rotation matrix and translation matrix with numpy to represent these relative poses.

The one thing I don't understand is how our lab assistant demonstrated how to create the rotation matrix. I was able to create it a similar way on my own but I'd like to understand what he did. Here is the example he provided:

Rot = lambda theta: [[np.cos(theta), -np.sin(theta)],
                     [np.sin(theta), np.cos(theta)]]

R = Rot(np.pi/3)
R

Can someone explain what is the Rot = lambda theta:  code means? When I did it on my own I just created a variable theta and the equation for Rot with the variable theta inside of it in the appropriate places. I do not understand what this lambda means.

Body:
It's the equivalent of this:

def Rot(theta):
    return [[np.cos(theta), -np.sin(theta)],
            [np.sin(theta), np.cos(theta)]]

The code lambda param1, param2: return_value creates a function with param1 and param2 as parameters, the code after the colon (:) is automatically run and returned when you call the function. Rot =  is simply assigning the resulting lambda function to the Rot variable, and since all functions are actually variables, that works.


问:
How do you prevent a re-created React component from losing state?
The example in this sandbox is a contrived example, but it illustrates the point.

Clicking the "Add column" button is supposed to add a new column. It works the first time, but doesn't work after that. You'll notice from the log that this issue has to do with the fact that columns is always in its original state. Therefore, a column is always being added to this original state, not the current state.

I imagine this issue is related to the fact that the column header is being re-created on each call to renderHeader, but I'm unsure about how to pass the state to the newly created header component.

答:
There are 2 ways to update your state:

The first way:
setColumns(newColumns)

The second way:
setColumns(columns => newColumns)

You should use the second way because the new state depend on the current state.

```<code>onClick={() => {
  setColumns((columns) => {
    console.log(columns.map((column) => column.field));
    const newColumnName = `Column ${columns.length}`;
    const newColumns = [...columns];
    newColumns.splice(
      columns.length - 1,
      0,
      createColumn(newColumnName)
    );
    return newColumns;
  });
}}
</code>```

Your component:

```<code>import React, { useState } from "react";
import { DataGrid } from "@mui/x-data-grid";
import Button from "@mui/material/Button";
import "./styles.css";

export default function App() {
  const [rows] = useState([
    { id: 1, "Column 1": 1, "Column 2": 2 },
    { id: 2, "Column 1": 3, "Column 2": 3 },
    { id: 3, "Column 1": 4, "Column 2": 5 }
  ]);
  const createColumn = (name) => {
    return {
      field: name,
      align: "center",
      editable: true,
      sortable: false
    };
  };
  const [columns, setColumns] = useState([
    createColumn("Column 1"),
    createColumn("Column 2"),
    {
      field: "Add a split",
      width: 150,
      sortable: false,
      renderHeader: (params) => {
        return (
          <Button
            variant="contained"
            onClick={() => {
              setColumns((columns) => { // <== use callback
                console.log(columns.map((column) => column.field));
                const newColumnName = `Column ${columns.length}`;
                const newColumns = [...columns];
                newColumns.splice(
                  columns.length - 1,
                  0,
                  createColumn(newColumnName)
                );
                return newColumns;
              });
            }}
          >
            Add column
          </Button>
        );
      }
    }
  ]);

  return (
    <div className="App">
      <DataGrid
        className="App-data-grid"
        rows={rows}
        columns={columns}
        disableSelectionOnClick
        disableColumnMenu
      />
    </div>
  );
}
</code>```

https://codesandbox.io/s/mui-sandbox-forked-1im0p?file=/src/App.js:0-1562

Body:
There are 2 ways to update your state:

The first way:
setColumns(newColumns)

The second way:
setColumns(columns => newColumns)

You should use the second way because the new state depend on the current state.

onClick={() => {
  setColumns((columns) => {
    console.log(columns.map((column) => column.field));
    const newColumnName = `Column ${columns.length}`;
    const newColumns = [...columns];
    newColumns.splice(
      columns.length - 1,
      0,
      createColumn(newColumnName)
    );
    return newColumns;
  });
}}

Your component:

import React, { useState } from "react";
import { DataGrid } from "@mui/x-data-grid";
import Button from "@mui/material/Button";
import "./styles.css";

export default function App() {
  const [rows] = useState([
    { id: 1, "Column 1": 1, "Column 2": 2 },
    { id: 2, "Column 1": 3, "Column 2": 3 },
    { id: 3, "Column 1": 4, "Column 2": 5 }
  ]);
  const createColumn = (name) => {
    return {
      field: name,
      align: "center",
      editable: true,
      sortable: false
    };
  };
  const [columns, setColumns] = useState([
    createColumn("Column 1"),
    createColumn("Column 2"),
    {
      field: "Add a split",
      width: 150,
      sortable: false,
      renderHeader: (params) => {
        return (
          <Button
            variant="contained"
            onClick={() => {
              setColumns((columns) => { // <== use callback
                console.log(columns.map((column) => column.field));
                const newColumnName = `Column ${columns.length}`;
                const newColumns = [...columns];
                newColumns.splice(
                  columns.length - 1,
                  0,
                  createColumn(newColumnName)
                );
                return newColumns;
              });
            }}
          >
            Add column
          </Button>
        );
      }
    }
  ]);

  return (
    <div className="App">
      <DataGrid
        className="App-data-grid"
        rows={rows}
        columns={columns}
        disableSelectionOnClick
        disableColumnMenu
      />
    </div>
  );
}

https://codesandbox.io/s/mui-sandbox-forked-1im0p?file=/src/App.js:0-1562


问:
Image Loading problem in Listbox, WP7
I have a Listbox in which every element has an image that is already stored as content.
I choose the image to be displayed using a converter.

If the image for the corresponding value does not exist, I have to display a default image
which I have handled in the ImageFailed event.

The problem is that when I run the program I am getting the default image for a few images that already exist.
If I scroll down the list box and back up again sometimes an image which was displayed properly displays the default image.
This seems to be an performance issue.

I am new to application development, Let me know any detail even though it might seem trivial to you.

Below is my implementation

```<code><ListBox DataContext="{Binding}">
    <ListBox.ItemTemplate>
        <DataTemplate>
                <StackPanel>
                            <Image Width="90" Height="67" Source="{Binding id,Converter={StaticResource imageConverter}}" ImageFailed="ImageFailed" />
                             _
                             _
                    </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
</code>```

The convert function

```<code>public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
       string Id = (string)value;
   string imagePath;
   imagePath = string.Format(AppDefines.channelLogoImgPath, prgSvcId);
   return imagePath;
}
</code>```

The ImageFailed handler

```<code>private void ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
    Image Img = (Image)sender;
    string imgPath = Defines.defImagePath
    Uri uri = new Uri(imgPath, UriKind.RelativeOrAbsolute);
    BitmapImage bDefImage = new BitmapImage(uri);
    Img.Source = bDefImage;
}
</code>```

答:
I have got a work around solution to the problem, I put 2 images in the same location. the default image is set visible right from the start.
The source for the item specific image is obtained as above (binding). In the image opened event handler of the item specific image the default image's visiblity is set to collapsed.

After doing this, the app is working fine on both emulator and the device. For now there are only 2 things that I can blame.

the Image failed event.
there are some cases where the image failed event is triggered and the image is displayed as well. (Probably there is some time limit etc which maked the event to be fired)

Listboxes and images dont go together.

Title: Image Loading problem in Listbox, WP7

Body:
I have a Listbox in which every element has an image that is already stored as content.
I choose the image to be displayed using a converter.

If the image for the corresponding value does not exist, I have to display a default image
which I have handled in the ImageFailed event.

The problem is that when I run the program I am getting the default image for a few images that already exist.
If I scroll down the list box and back up again sometimes an image which was displayed properly displays the default image.
This seems to be an performance issue.

I am new to application development, Let me know any detail even though it might seem trivial to you.

Below is my implementation

<ListBox DataContext="{Binding}">
    <ListBox.ItemTemplate>
        <DataTemplate>
                <StackPanel>
                            <Image Width="90" Height="67" Source="{Binding id,Converter={StaticResource imageConverter}}" ImageFailed="ImageFailed" />
                             _
                             _
                    </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

The convert function

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
       string Id = (string)value;
   string imagePath;
   imagePath = string.Format(AppDefines.channelLogoImgPath, prgSvcId);
   return imagePath;
}

The ImageFailed handler

private void ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
    Image Img = (Image)sender;
    string imgPath = Defines.defImagePath
    Uri uri = new Uri(imgPath, UriKind.RelativeOrAbsolute);
    BitmapImage bDefImage = new BitmapImage(uri);
    Img.Source = bDefImage;
}


问:
A RenderFlex overflowed bottom flutter
when I run the project it shows A RenderFlex overflowed on the bottom

A RenderFlex overflowed by 6.7 pixels on the bottom.

答: In your Scaffold, set resizeToAvoidBottomInset property to false.

Title: A RenderFlex overflowed bottom flutter


问:
Hilt integration crashes application MainActivity_GeneratedInjector
Trying to integrate hilt using android Api Documentation but app crashed with following exception. https://developer.android.com/training/dependency-injection/hilt-android</p>
```<code>java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.package.application/com.package.application.MainActivity}:

java.lang.ClassCastException: com.package.application.DaggerAppApplication_HiltComponents_ApplicationC$ActivityRetainedCImpl$ActivityCImpl
cannot be cast to com.package.application.MainActivity_GeneratedInjector

</code>```

答:
It's also happened to me when I'm importing an .aar with "implementation".
(an .aar which includes hilt)

Like Sher Sanginov said instead of using "api" who increase compilation time, you can add the following lines in your build.gradle(app)

```<code>hilt {
    enableAggregatingTask = true
}
</code>```

enableExperimentalClasspathAggregation is now deprecated,

see https://dagger.dev/hilt/gradle-setup#aggregating-task

Body:
Trying to integrate hilt using android Api Documentation but app crashed with following exception. https://developer.android.com/training/dependency-injection/hilt-android

java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.package.application/com.package.application.MainActivity}:

java.lang.ClassCastException: com.package.application.DaggerAppApplication_HiltComponents_ApplicationC$ActivityRetainedCImpl$ActivityCImpl
cannot be cast to com.package.application.MainActivity_GeneratedInjector

Body:
It's also happened to me when I'm importing an .aar with "implementation".
(an .aar which includes hilt)

Like Sher Sanginov said instead of using "api" who increase compilation time, you can add the following lines in your build.gradle(app)

hilt {
    enableAggregatingTask = true
}

enableExperimentalClasspathAggregation is now deprecated,

see https://dagger.dev/hilt/gradle-setup#aggregating-task


问:
How best to loop over a batch of Results with a C# DbDataReader
I'm executing a number of SQL query's as a batch and then getting all of the result sets back in a batch.  The way that my code is currently put together, the first result set gets skipped.  Now that I know this, I could simply throw in another statement outside of my loop that grabs the first result, however I'm wondering if there is a more elegant solution to this problem.

Here is some sudo code of whats going on:

```<code>DbDataReader reader= /*some stuff that returns a batch of results...*/;

while (reader.NextResult())
{
   while (reader.Read())
   {
       if (!reader.IsDBNull(0))
       {
           //do things with the data....
       }
   }
}
</code>```

Now i would have expected that NextResult() advances you to the first result the first time you call it, which is what Read() seems to do.  However what it actually seems to do is bring you to the second result on the first call.  Am I misunderstanding how you're expected to use this method, or are you really expected to do some like the following:

```<code>DbDataReader reader= /*some stuff that returns a batch of results...*/;

//this deals with the row in the the very first result
while (reader.Read())
{
    if (!reader.IsDBNull(0))
    {
        //do things with the data....
    }
}

//this deals with the rest of the rows...
while (reader.NextResult())
{
   while (reader.Read())
   {
       if (!reader.IsDBNull(0))
       {
           //do exact same things with the data....
           //is this not pretty klugey?
       }
   }
}
</code>```

This strikes me as rotten programming style, but I don't see a way around it.  Does anyone know of a more elegant solution to this?

答:
Simply put the NextResult at the end of the loop instead of the beginning:</p>

```<code>do {
   while (reader.Read()) {
      if (!reader.IsDBNull(0)) {
         //do things with the data....
      }
   }
} while (reader.NextResult());
</code>```

OwnerDisplayName: sweeney

ContentLicense: CC BY-SA 2.5

Body:
I'm executing a number of SQL query's as a batch and then getting all of the result sets back in a batch.  The way that my code is currently put together, the first result set gets skipped.  Now that I know this, I could simply throw in another statement outside of my loop that grabs the first result, however I'm wondering if there is a more elegant solution to this problem.

Here is some sudo code of whats going on:

DbDataReader reader= /*some stuff that returns a batch of results...*/;

while (reader.NextResult())
{
   while (reader.Read())
   {
       if (!reader.IsDBNull(0))
       {
           //do things with the data....
       }
   }
}

Now i would have expected that NextResult() advances you to the first result the first time you call it, which is what Read() seems to do.  However what it actually seems to do is bring you to the second result on the first call.  Am I misunderstanding how you're expected to use this method, or are you really expected to do some like the following:

DbDataReader reader= /*some stuff that returns a batch of results...*/;

//this deals with the row in the the very first result
while (reader.Read())
{
    if (!reader.IsDBNull(0))
    {
        //do things with the data....
    }
}

//this deals with the rest of the rows...
while (reader.NextResult())
{
   while (reader.Read())
   {
       if (!reader.IsDBNull(0))
       {
           //do exact same things with the data....
           //is this not pretty klugey?
       }
   }
}

This strikes me as rotten programming style, but I don't see a way around it.  Does anyone know of a more elegant solution to this?

Body:
Simply put the NextResult at the end of the loop instead of the beginning:

do {
   while (reader.Read()) {
      if (!reader.IsDBNull(0)) {
         //do things with the data....
      }
   }
} while (reader.NextResult());

OwnerDisplayName: Guffa


问:
Selenium via Eclipse: is it possible to move the cursor position?
I am using the selenium plug in for eclipse to automate the testing of newly created websites. I am trying to click a button that is in a menu and only visible when the cursor is located over the menu. </p>

<p>Is it possible to move the cursor so that this button can be clicked ? </p>

答:
It will depend a little on how the menu has been implemented (i.e. the event that will trigger your button to appear) but you should look at the focus and mouseOver methods for selenium.

I.e. do something like

```<code>this.selenium.mouseOver(element);
</code>```

where element refers to the menu and then do a click on the button.  If mouseOver does not work (i.e. the button does not become available) try focus instead.

Body:
I am using the selenium plug in for eclipse to automate the testing of newly created websites. I am trying to click a button that is in a menu and only visible when the cursor is located over the menu.

Is it possible to move the cursor so that this button can be clicked ?

Body:
It will depend a little on how the menu has been implemented (i.e. the event that will trigger your button to appear) but you should look at the focus and mouseOver methods for selenium.

I.e. do something like

this.selenium.mouseOver(element);

where element refers to the menu and then do a click on the button.  If mouseOver does not work (i.e. the button does not become available) try focus instead.


问:
Change dovecot user password
I am using dovecot and configured it to load User accounts from a mySQL Table.
This is my configuration:

```<code>driver=mysql
connect = "host=127.0.0.1 dbname=vmail user=vmail password=verySecret"
default_pass_scheme = SHA512-CRYPT

password_query = SELECT username AS user, domain, password FROM accounts WHERE username = '%n' AND domain = '%d' and enabled = true;
user_query = SELECT concat('*:storage=', quota, 'M') AS quota_rule FROM accounts WHERE username = '%n' AND domain = '%d' AND sendonly = false;
iterate_query = SELECT username, domain FROM accounts where sendonly = false;
</code>```

I have a small nodejs application for user administration. But I can't generate the passowrds. I try to use crypto libraray in node, but the user is not able to login.
When I create a password via doveadm the user ist able to login.

What to do, do set a passwort from a nodejs application?

答:
It looks like you are using a database a mySQL driver and using a SHA512-CRYPT hash to control users and passwords, so you need to encrypt the password with doveadm tool.

root@none:~# doveadm pw -s SHA512-CRYPT
Enter new password:
Retype new password:
{SHA512-CRYPT}$6$jS4C7A0o3/roDu8C$cbOHg5Vg6WJKBi/DL2JM7Th4W1LW86RjTTLlwWJa7w7fbKCkLGX0Jl.hGKBFmz3/a1xxYVbO6lc9nF6e26vVe/
```

then all you need is go inside your database and UPDATE the contents of the password to the correct user.

Title: Change dovecot user password

Body:
I am using dovecot and configured it to load User accounts from a mySQL Table.
This is my configuration:

driver=mysql
connect = "host=127.0.0.1 dbname=vmail user=vmail password=verySecret"
default_pass_scheme = SHA512-CRYPT

password_query = SELECT username AS user, domain, password FROM accounts WHERE username = '%n' AND domain = '%d' and enabled = true;
user_query = SELECT concat('*:storage=', quota, 'M') AS quota_rule FROM accounts WHERE username = '%n' AND domain = '%d' AND sendonly = false;
iterate_query = SELECT username, domain FROM accounts where sendonly = false;

I have a small nodejs application for user administration. But I can't generate the passowrds. I try to use crypto libraray in node, but the user is not able to login.
When I create a password via doveadm the user ist able to login.

What to do, do set a passwort from a nodejs application?

Body:
It looks like you are using a database a mySQL driver and using a SHA512-CRYPT hash to control users and passwords, so you need to encrypt the password with doveadm tool.

root@none:~# doveadm pw -s SHA512-CRYPT
Enter new password:
Retype new password:
{SHA512-CRYPT}$6$jS4C7A0o3/roDu8C$cbOHg5Vg6WJKBi/DL2JM7Th4W1LW86RjTTLlwWJa7w7fbKCkLGX0Jl.hGKBFmz3/a1xxYVbO6lc9nF6e26vVe/

then all you need is go inside your database and UPDATE the contents of the password to the correct user.


问:
How to add submenu to kendo ui context menu dynamically
I added Kendo ui context menu to my page by appending UL to body.and added some of the item in context menu as given below .

I want to add submenu to "Sibling".My submenu item have "text" and "URL"(eg.NavigateText & www.xyz.com) which are generating dynamically

I have tried insertAfter and append but its adding it to main context menu list.

how can i add it to submenu.
Thanks in advance.

```<code>var contextMenu = $("#context-menu").data("kendoContextMenu");
if (typeof (contextMenu != undefined) || typeof (contextMenu != '')) {
    contextMenu.append(
        [{
           text: "<span class='k-icon k-i-refresh'></span><b>  Refresh</b>",
           encoded: false
       },
      {
            text: "<span class='k-icon k-i-bookmark'></span><b>  My BookMarks</b>",
            encoded: false
        },
        {
            text: "<span class='k-icon k-i-grid-layout'></span><b>  My Preferences</b>",
            encoded: false
       },
   {
        text: "<span class='k-icon k-i-redo'></span><b>  Back</b>",
        encoded: false
       },
       {
        text: "<span class='k-Sibling'><span class='k-icon k-i-redo'></span><b>  Sibling</b></span>",
        encoded: false,
    }

        ]);
</code>```

// getting element for Context submenu

```<code>var hrefUrl = _spPageContext.webServerUrl;
var elem = $('a[href="' + hrefUrl + '"]');
alert(elem[0].textContent);
var checkLast = $(elem[0]).is(':last-child');
alert(checkLast);
var parentli = $(elem[0]).parent();
//alert(parentli);
var li = $(parentli);
var sib = li.siblings();
var allLi = $(".menu-item-text");
var arr =[];
$.each(sib, function(index) {
    var ctx = $(this).find(allLi);
    alert(ctx[0].textContent);
    //alert($(ctx[0]).closest('a').attr('href'));
    var text = "<div class='dynaList'><span><a href='" + $(ctx[0]).closest('a').attr('href') + "'>" + this.textContent + "</a></span></div>";
    //$("#context-menu").append(text);
    var links = {
        "txt" : ctx[0].textContent,
        "link" : $(ctx[0]).closest('a').attr('href')
    };
</code>```

arr.push(links);
    });

答:
There is an example on their documentation: https://docs.telerik.com/kendo-ui/api/javascript/ui/contextmenu/methods/append</p>
```<code><div id="target">Target</div>
<ul id="context-menu"></ul>
<script>
    // initialize the ContextMenu
    $("#context-menu").kendoContextMenu({
        target: "#target"
    });

    // get a reference to already initialized ContextMenu widget
    var contextMenu = $("#context-menu").data("kendoContextMenu");

    contextMenu.append(
        [{
            text: "Item 1",
            cssClass: "myClass",                         // Add custom CSS class to the item, optional, added 2012 Q3 SP1.
            url: "https://www.telerik.com"                // Link URL if navigation is needed, optional.
        },
        {
            text: "<b>Item 2</b>",
            encoded: false,                              // Allows use of HTML for item text
            content: "text"                              // content within an item
        },
        {
            text: "Item 3",
            imageUrl: "https://demos.telerik.com/kendo-ui/content/web/toolbar/todo.png", // Item image URL, optional.
            items: [{                                    // Sub item collection
                 text: "Sub Item 1"
            },
            {
                 text: "Sub Item 2"
            }]
        },
        {
            text: "Item 4",
            spriteCssClass: "mail"                // Item image sprite CSS class, optional.
        }]
    );
</script>
<style>
.k-sprite {
        background-image: url("https://demos.telerik.com/kendo-ui/content/web/toolbar/mail.png");
    }
</style>
</code>```

Body:
I added Kendo ui context menu to my page by appending UL to body.and added some of the item in context menu as given below .

I want to add submenu to "Sibling".My submenu item have "text" and "URL"(eg.NavigateText & www.xyz.com) which are generating dynamically

I have tried insertAfter and append but its adding it to main context menu list.

how can i add it to submenu.
Thanks in advance.

var contextMenu = $("#context-menu").data("kendoContextMenu");
if (typeof (contextMenu != undefined) || typeof (contextMenu != '')) {
    contextMenu.append(
        [{
           text: "  Refresh",
           encoded: false
       },
      {
            text: "  My BookMarks",
            encoded: false
        },
        {
            text: "  My Preferences",
            encoded: false
       },
   {
        text: "  Back",
        encoded: false
       },
       {
        text: "  Sibling",
        encoded: false,
    }

        ]);

// getting element for Context submenu

var hrefUrl = _spPageContext.webServerUrl;
var elem = $('a[href="' + hrefUrl + '"]');
alert(elem[0].textContent);
var checkLast = $(elem[0]).is(':last-child');
alert(checkLast);
var parentli = $(elem[0]).parent();
//alert(parentli);
var li = $(parentli);
var sib = li.siblings();
var allLi = $(".menu-item-text");
var arr =[];
$.each(sib, function(index) {
    var ctx = $(this).find(allLi);
    alert(ctx[0].textContent);
    //alert($(ctx[0]).closest('a').attr('href'));
    var text = "
" + this.textContent + "
";
    //$("#context-menu").append(text);
    var links = {
        "txt" : ctx[0].textContent,
        "link" : $(ctx[0]).closest('a').attr('href')
    };

arr.push(links);
    });

Body:
There is an example on their documentation: https://docs.telerik.com/kendo-ui/api/javascript/ui/contextmenu/methods/append

<div id="target">Target</div>
<ul id="context-menu"></ul>
<script>
    // initialize the ContextMenu
    $("#context-menu").kendoContextMenu({
        target: "#target"
    });

    // get a reference to already initialized ContextMenu widget
    var contextMenu = $("#context-menu").data("kendoContextMenu");

    contextMenu.append(
        [{
            text: "Item 1",
            cssClass: "myClass",                         // Add custom CSS class to the item, optional, added 2012 Q3 SP1.
            url: "https://www.telerik.com"                // Link URL if navigation is needed, optional.
        },
        {
            text: "<b>Item 2</b>",
            encoded: false,                              // Allows use of HTML for item text
            content: "text"                              // content within an item
        },
        {
            text: "Item 3",
            imageUrl: "https://demos.telerik.com/kendo-ui/content/web/toolbar/todo.png", // Item image URL, optional.
            items: [{                                    // Sub item collection
                 text: "Sub Item 1"
            },
            {
                 text: "Sub Item 2"
            }]
        },
        {
            text: "Item 4",
            spriteCssClass: "mail"                // Item image sprite CSS class, optional.
        }]
    );
</script>
<style>
.k-sprite {
        background-image: url("https://demos.telerik.com/kendo-ui/content/web/toolbar/mail.png");
    }
</style>


问:
leave gcloud project in terminal
How can I leave my current gcloud project via the cloud cli so I can revert back to my normal terminal?

```<code>15:40:08 in ~ using ☁  default/192085439987
</code>```

I just want to be using

```<code>15:40:08 in ~
</code>```

I have managed to swap between projects using

```<code>gcloud config set project <project id>
</code>```

But can't seem to leave anything

答:
I think this is what I am after

https://cloud.google.com/sdk/docs/properties#unsetting_properties

```<code>gcloud config unset disable_usage_reporting
</code>```

Can someone confirm?

Title: leave gcloud project in terminal

Body:
How can I leave my current gcloud project via the cloud cli so I can revert back to my normal terminal?

15:40:08 in ~ using ☁  default/192085439987

I just want to be using

15:40:08 in ~

I have managed to swap between projects using

gcloud config set project <project id>

But can't seem to leave anything

Body:
I think this is what I am after

https://cloud.google.com/sdk/docs/properties#unsetting_properties

gcloud config unset disable_usage_reporting

Can someone confirm?


问:
Can we create a WCF service which publishes events?
I want to create a push web application.

The service layer is built on WCF.

The presentation layer is built on Asp.net 4

The service listens to events and updates its static property (a shared collection list) from the data layer.
I am polling in my presentation layer and calling a method of WCF every second and getting the updated collection.

If a collection is unmodified, I return empty list to save network bandwidth.

To save the round trips, I want the WCF service to publish an event if and when the collection is modified.  Is that possible?  How do I achieve this?

Thank you

答:
I had been looking for same thing but could not find anything with Push facility in .Net, Then I had to use Flex along with .Net.

You may get start from this reference


问:
nock not able to match all path segments for specific string
I tried several approach to match this specific pattern of the url:

https://app.launchdarkly.com/sdk/goals/123123123

so the 123123123 will be always changing.also for some reason its making a OPTION call beside another GET call every time. Not sure why and that's likely another story...

nock return error like:

```<code>Error: Error: Nock: No match for request {
      "method": "OPTIONS",
   "url": "https://app.launchdarkly.com/sdk/goals/123123123",
  "headers": {
    "origin": "http://localhost",
    "access-control-request-method": "GET",
    "access-control-request-headers": "X-LaunchDarkly-User-Agent",
    "user-agent": "Mozilla/5.0 (darwin) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/16.5.3",
    "host": "app.launchdarkly.com",
    "content-length": 0
  }
}
</code>```

nock is not recognizing the pattern if I do (note that I am copying the same pattern as a GET as well)

```<code>nock('https://app.launchdarkly.com')
    .persist()
    .defaultReplyHeaders({
        'access-control-allow-origin': '*',
        'access-control-allow-headers': '*',
        'access-control-allow-credentials': 'true',
    })
    .options('/sdk/goals.*$/')
    .reply(200, mockLDExperiments);
</code>```

or

```<code>nock('https://app.launchdarkly.com')
    .persist()
    .defaultReplyHeaders({
        'access-control-allow-origin': '*',
        'access-control-allow-headers': '*',
        'access-control-allow-credentials': 'true',
    })
    .options('/sdk/goals/**/*')
    .reply(200, mockLDExperiments);
</code>```

or

```<code>nock('https://app.launchdarkly.com')
    .persist()
    .defaultReplyHeaders({
        'access-control-allow-origin': '*',
        'access-control-allow-headers': '*',
        'access-control-allow-credentials': 'true',
    })
    .options('/sdk/goals')
    .reply(200, mockLDExperiments);
</code>```

any idea how to write the correct path matcher so I can allow this segment scenario gets picked up by nock?

答:
Nock supports Regex path matching. It seems you're attempting something similar with globs, however, if a string is provided Nock only does exact matching.
Docs

For your case, something like this should get you going.

```<code>nock('https://app.launchdarkly.com')
  ...
  .options(/^\/sdk\/goals\//)
  ...
</code>```

Body:
I tried several approach to match this specific pattern of the url:

https://app.launchdarkly.com/sdk/goals/123123123

so the 123123123 will be always changing.also for some reason its making a OPTION call beside another GET call every time. Not sure why and that's likely another story...

nock return error like:

Error: Error: Nock: No match for request {
      "method": "OPTIONS",
   "url": "https://app.launchdarkly.com/sdk/goals/123123123",
  "headers": {
    "origin": "http://localhost",
    "access-control-request-method": "GET",
    "access-control-request-headers": "X-LaunchDarkly-User-Agent",
    "user-agent": "Mozilla/5.0 (darwin) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/16.5.3",
    "host": "app.launchdarkly.com",
    "content-length": 0
  }
}

nock is not recognizing the pattern if I do (note that I am copying the same pattern as a GET as well)

nock('https://app.launchdarkly.com')
    .persist()
    .defaultReplyHeaders({
        'access-control-allow-origin': '*',
        'access-control-allow-headers': '*',
        'access-control-allow-credentials': 'true',
    })
    .options('/sdk/goals.*$/')
    .reply(200, mockLDExperiments);

or

nock('https://app.launchdarkly.com')
    .persist()
    .defaultReplyHeaders({
        'access-control-allow-origin': '*',
        'access-control-allow-headers': '*',
        'access-control-allow-credentials': 'true',
    })
    .options('/sdk/goals/**/*')
    .reply(200, mockLDExperiments);

or

nock('https://app.launchdarkly.com')
    .persist()
    .defaultReplyHeaders({
        'access-control-allow-origin': '*',
        'access-control-allow-headers': '*',
        'access-control-allow-credentials': 'true',
    })
    .options('/sdk/goals')
    .reply(200, mockLDExperiments);

any idea how to write the correct path matcher so I can allow this segment scenario gets picked up by nock?

Body:
Nock supports Regex path matching. It seems you're attempting something similar with globs, however, if a string is provided Nock only does exact matching.
Docs

For your case, something like this should get you going.

nock('https://app.launchdarkly.com')
  ...
  .options(/^\/sdk\/goals\//)
  ...


问:
Path for picked file is throwing null check error in flutter
I have a profile picture card which I am using in 3 different places. I am passing some parameters to the ProfilePictureCard to show camera button.

For an example if the ProfilePictureCard is used in a ProfilePage the camera button will be hidden and if the said card is shown in a EditProfilePage the camera button will be visible.

This is the code for ProfilePictureCard:

```<code>class ProfilePictureCard extends StatefulWidget {
  final bool? isSetProfilePage;
  final bool? isEditable;
  File? imageFile;
  final String? imageUrl;
  ProfilePictureCard({
    Key? key,
    this.isSetProfilePage = false,
    this.isEditable = false,
    this.imageFile,
    this.imageUrl,
  }) : super(key: key);

  @override
  _ProfilePictureCardState createState() => _ProfilePictureCardState();
}

class _ProfilePictureCardState extends State<ProfilePictureCard> {
  @override
  void initState() {
    super.initState();
    print('Image Url: ${widget.imageUrl}');
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 150,
      width: 150,
      child: Stack(
        children: [
          Stack(
            children: [
              Center(
                child: _buildProfilePicture(),
              ),
              widget.isEditable == true
                  ? Positioned(
                      bottom: 0,
                      left: 55,
                      right: 55,
                      child: CameraButton(
                        onPressed: () {
                          _handleChangeProfilePicture();
                        },
                      ),
                    )
                  : Container(),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildProfilePicture() {
    return Container(
      height: 100,
      width: 100,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        border: Border.all(
          color: CustomColors.semiSecondary,
          width: 1,
        ),
      ),
      child: _buildImage(),
    );
  }

  Widget _buildImage() {
    return ClipRRect(
      borderRadius: BorderRadius.circular(10.0),
      child: widget.imageFile != null
          ? Image.file(
              widget.imageFile!,
              fit: BoxFit.cover,
            )
          : Image.network(
              widget.imageUrl ?? 'https://picsum.photos/200',
              fit: BoxFit.cover,
            ),
    );
  }

  void _handleChangeProfilePicture() async {
    final result = await showDialog(
      context: context,
      builder: (context) {
        return CameraDialog();
      },
    );
    print("Result: $result");
    if (result != null) {
      setState(() {
        widget.imageFile = result;
      });
      print(widget.imageFile);
    }
  }
}
</code>```

_handleChangeProfilePicture takes a picture from either gallery or camera and returns it using Navigator.of(context).pop(finalImage);

In my EditProfilePage I have a Update Button which for now only prints out the selected images path.

The EditProfilePage file looks like this:

```<code>class _EditProfilePage extends State<EditProfilePage {
    File? imageFile;

    @override
    Widget build(BuildContext context){
       ...other widgets
       ProfilePictureCard(
          isEditable: true, // because of this line the camera button is visible
          imageFile: imageFile,
          imageUrl: 'https://picsum.photos/id/237/200/300', // previous profile picture, will be replaced with selected image
       )
    }

    _handleUpdate(){
       print(imageFile.path);
    }
}
</code>```

Inside the CameraDialog other than the basic UI stuff for returning the selected file I have this:

```<code>  void _captureImage(context) async {
    final XFile? pickedFile =
        await _picker.pickImage(source: ImageSource.camera);
    if (pickedFile != null) {
      final File file = File(pickedFile.path);
      Navigator.of(context).pop(file);
    }
  }
</code>```

But when I press update I am getting: Null check operator used on a null value  from the print(imageFile.path);

What is the reason for this issue, and how to solve this?

答:
You should use function to return your image instead of passing object,

```<code>class ProfilePictureCard extends StatefulWidget {
  final bool? isSetProfilePage;
  final bool? isEditable;
  final Function(File file) handleUpdate;
  final String? imageUrl;
  ProfilePictureCard({
    Key? key,
    this.isSetProfilePage = false,
    this.isEditable = false,
    this.handleUpdate,
    this.imageUrl,
  })
</code>```

usage

```<code>if (result != null) {
    widget.handleUpdate(result);
}
</code>```

In editing profile

```<code> class _EditProfilePage extends State<EditProfilePage {
    File? imageFile;

    @override
    Widget build(BuildContext context){
       ...other widgets
       ProfilePictureCard(
          isEditable: true, // because of this line the camera button is visible
          handleUpdate: _handleUpdate,
          imageUrl: 'https://picsum.photos/id/237/200/300', // previous profile picture, will be replaced with selected image
       )
    }

    _handleUpdate(File file){
       print(file.path);
       setState(() {
         imageFile = file;
       });
    }
}
</code>```

Body:
I have a profile picture card which I am using in 3 different places. I am passing some parameters to the ProfilePictureCard to show camera button.

For an example if the ProfilePictureCard is used in a ProfilePage the camera button will be hidden and if the said card is shown in a EditProfilePage the camera button will be visible.

This is the code for ProfilePictureCard:

class ProfilePictureCard extends StatefulWidget {
  final bool? isSetProfilePage;
  final bool? isEditable;
  File? imageFile;
  final String? imageUrl;
  ProfilePictureCard({
    Key? key,
    this.isSetProfilePage = false,
    this.isEditable = false,
    this.imageFile,
    this.imageUrl,
  }) : super(key: key);

  @override
  _ProfilePictureCardState createState() => _ProfilePictureCardState();
}

class _ProfilePictureCardState extends State<ProfilePictureCard> {
  @override
  void initState() {
    super.initState();
    print('Image Url: ${widget.imageUrl}');
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 150,
      width: 150,
      child: Stack(
        children: [
          Stack(
            children: [
              Center(
                child: _buildProfilePicture(),
              ),
              widget.isEditable == true
                  ? Positioned(
                      bottom: 0,
                      left: 55,
                      right: 55,
                      child: CameraButton(
                        onPressed: () {
                          _handleChangeProfilePicture();
                        },
                      ),
                    )
                  : Container(),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildProfilePicture() {
    return Container(
      height: 100,
      width: 100,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        border: Border.all(
          color: CustomColors.semiSecondary,
          width: 1,
        ),
      ),
      child: _buildImage(),
    );
  }

  Widget _buildImage() {
    return ClipRRect(
      borderRadius: BorderRadius.circular(10.0),
      child: widget.imageFile != null
          ? Image.file(
              widget.imageFile!,
              fit: BoxFit.cover,
            )
          : Image.network(
              widget.imageUrl ?? 'https://picsum.photos/200',
              fit: BoxFit.cover,
            ),
    );
  }

  void _handleChangeProfilePicture() async {
    final result = await showDialog(
      context: context,
      builder: (context) {
        return CameraDialog();
      },
    );
    print("Result: $result");
    if (result != null) {
      setState(() {
        widget.imageFile = result;
      });
      print(widget.imageFile);
    }
  }
}

_handleChangeProfilePicture takes a picture from either gallery or camera and returns it using Navigator.of(context).pop(finalImage);

In my EditProfilePage I have a Update Button which for now only prints out the selected images path.

The EditProfilePage file looks like this:

class _EditProfilePage extends State<EditProfilePage {
    File? imageFile;

    @override
    Widget build(BuildContext context){
       ...other widgets
       ProfilePictureCard(
          isEditable: true, // because of this line the camera button is visible
          imageFile: imageFile,
          imageUrl: 'https://picsum.photos/id/237/200/300', // previous profile picture, will be replaced with selected image
       )
    }

    _handleUpdate(){
       print(imageFile.path);
    }
}

Inside the CameraDialog other than the basic UI stuff for returning the selected file I have this:

  void _captureImage(context) async {
    final XFile? pickedFile =
        await _picker.pickImage(source: ImageSource.camera);
    if (pickedFile != null) {
      final File file = File(pickedFile.path);
      Navigator.of(context).pop(file);
    }
  }

But when I press update I am getting: Null check operator used on a null value  from the print(imageFile.path);

What is the reason for this issue, and how to solve this?

Body:
You should use function to return your image instead of passing object,

class ProfilePictureCard extends StatefulWidget {
  final bool? isSetProfilePage;
  final bool? isEditable;
  final Function(File file) handleUpdate;
  final String? imageUrl;
  ProfilePictureCard({
    Key? key,
    this.isSetProfilePage = false,
    this.isEditable = false,
    this.handleUpdate,
    this.imageUrl,
  })

usage

if (result != null) {
    widget.handleUpdate(result);
}

In editing profile

 class _EditProfilePage extends State<EditProfilePage {
    File? imageFile;

    @override
    Widget build(BuildContext context){
       ...other widgets
       ProfilePictureCard(
          isEditable: true, // because of this line the camera button is visible
          handleUpdate: _handleUpdate,
          imageUrl: 'https://picsum.photos/id/237/200/300', // previous profile picture, will be replaced with selected image
       )
    }

    _handleUpdate(File file){
       print(file.path);
       setState(() {
         imageFile = file;
       });
    }
}