问:
Show fullscreen image onTap in Flutter
I have image shown using one of Flutter widgets

```<code>Image.network(....);
</code>```

I want to add functionality that after tapping on image I can present this image in fullscreen mode. How it can be done?

答:
You can use this code to have full screen of image!</p>

```<code>class DetailScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: Hero(
            tag: 'imageHero',
            child: Image.network(
              'https://picsum.photos/250?image=9',
            ),
          ),
        ),
        onTap: () {
          Navigator.pop(context);
        },
      ),
    );
  }
}
</code>```

Title: Show fullscreen image onTap in Flutter

Body:
I have image shown using one of Flutter widgets

Image.network(....);

I want to add functionality that after tapping on image I can present this image in fullscreen mode. How it can be done?

Body:
You can use this code to have full screen of image!

class DetailScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: Hero(
            tag: 'imageHero',
            child: Image.network(
              'https://picsum.photos/250?image=9',
            ),
          ),
        ),
        onTap: () {
          Navigator.pop(context);
        },
      ),
    );
  }
}


来源: stackexchange

问:
Spring Security: Custom UserDetailsService not being called (using Auth0 authentication)
I'm new to the Spring framework, so I apologize in advance for any gaping holes in my understanding.

I'm using Auth0 to secure my API, which works perfectly. My setup & config is the same as the suggested setup in the Auth0 documentation:

```<code>// SecurityConfig.java
@Configuration
@EnableWebSecurity(debug = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // auth0 config vars here

    @Override
    protected void configure(HttpSecurity http) {
        JwtWebSecurityConfigurer
                .forRS256(apiAudience, issuer)
                .configure(http)
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/api/public").permitAll()
                .antMatchers(HttpMethod.GET, "/api/private").authenticated();
    }
}
</code>```

With this setup, the spring security principal is being set to the userId (sub) from the jwt token: auth0|5b2b.... However, instead of just the userId, I want it set to the matching user (from my database). My question is how to do that.

What I've tried

I've tried implementing a custom database-backed UserDetailsService that I copied from this tutorial.
However, it's not getting called regardless of how I try to add it to my conf. I've tried adding it several different ways with no effect:

```<code>// SecurityConfig.java (changes only)

    // My custom userDetailsService, overriding the loadUserByUsername
    // method from Spring Framework's UserDetailsService.
    @Autowired
    private MyUserDetailsService userDetailsService;

    protected void configure(HttpSecurity http) {
        http.userDetailsService(userDetailsService);  // Option 1
        http.authenticationProvider(authenticationProvider());  // Option 2
        JwtWebSecurityConfigurer
                [...]  // The rest unchanged from above
    }

    @Override  // Option 3 & 4: Override the following method
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(authenticationProvider());  // Option 3
        auth.userDetailsService(userDetailsService);  // Option 4
    }

    @Bean  // Needed for Options 2 or 4
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService);
        return authProvider;
    }
</code>```

Unfortunately none of the similar "userDetails not being called" questions have helped me due to me needing to combine it with Auth0 authentication.

I'm not positive that I'm on the right path with this. It seems strange to me that I can't find any documentation from Auth0 on this extremely common use case, so maybe I'm missing something obvious.

PS: Not sure if relevant, but the following is always logged during init.

Jun 27, 2018 11:25:22 AM com.test.UserRepository initDao
INFO: No authentication manager set. Reauthentication of users when changing passwords will not be performed.
```

<h2>EDIT 1:</h2>

<p>Based on Ashish451's answer, I tried copying his CustomUserDetailsService, and added the following to my SecurityConfig:</p>

```@Autowired
private CustomUserDetailsService userService;

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

@Autowired
public void configureGlobal( AuthenticationManagerBuilder auth ) throws Exception {
    auth.userDetailsService( userService );
}
```

<p>Unfortunately with those changes, CustomUserDetailsService is still not being called.</p>

<h2>EDIT 2:</h2>

<p>Output when adding the logging method suggested by @Norberto Ritzmann:</p>

<pre class="lang-none prettyprint-override"><code>Jul 04, 2018 3:49:22 PM com.test.repositories.UserRepositoryImpl initDao
INFO: No authentication manager set. Reauthentication of users when changing passwords will not be performed.
Jul 04, 2018 3:49:22 PM com.test.runner.JettyRunner testUserDetailsImpl
INFO: UserDetailsService implementation: com.test.services.CustomUserDetailsService
</code>```

答:
This is what I ended up doing if you want to just stick with using spring libraries. You can change Auth0UserDetailsService to query user details from any source.

```<code>public class Auth0JwtAuthenticationProvider implements AuthenticationProvider {

@Autowired
ApplicationContext context;
@Autowired
@Qualifier("auth0UserDetailsService")
UserDetailsService auth0UserDetailsService;
private JwtAuthenticationProvider jwtAuthenticationProvider;

public Auth0JwtAuthenticationProvider() {

}

@PostConstruct
public void postConstruct() {
    jwtAuthenticationProvider = new JwtAuthenticationProvider(context.getBean(JwtDecoder.class));
}

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Authentication token = jwtAuthenticationProvider.authenticate(authentication);
    ((AbstractAuthenticationToken) token).setDetails(auth0UserDetailsService.loadUserByUsername(authentication.getName()));
    return token;
}

@Override
public boolean supports(Class<?> authentication) {
    return BearerTokenAuthenticationToken.class.isAssignableFrom(authentication);
}
</code>```

}

And for UserDetailsService I am getting user details using a service.

```<code>public class Auth0UserDetailsService implements UserDetailsService {

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    RestTemplate restTemplate = new RestTemplate();

    .....
  ResponseEntity<Auth0UserDetails> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, Auth0UserDetails.class);
    return responseEntity.getBody();

}
</code>```

.....

}

And UserDetails will have all details you need.

```<code>public class Auth0UserDetails implements UserDetails {

@JsonProperty("name")
private String userName;

@JsonProperty("created_at")
private LocalDateTime createdAt;

@JsonProperty("email")
private String email;

@JsonProperty("email_verified")
private boolean isEmailVerified;

@JsonProperty("nickname")
private String nickName;

@JsonProperty("picture")
private String pictureURL;

@JsonProperty("updated_at")
private LocalDateTime updatedAt;

@JsonProperty("user_id")
private String userID;
</code>```

...
//Getters and Setter and overridden methods.

}

```<code>    @EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public Auth0JwtAuthenticationProvider auth0JwtAuthenticationProvider() {
        return new Auth0JwtAuthenticationProvider();
    }

    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception {

        httpSecurity.authenticationProvider(auth0JwtAuthenticationProvider()).authorizeRequests().
....
.oauth2ResourceServer().jwt();

}}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new to the Spring framework, so I apologize in advance for any gaping holes in my understanding.

I'm using Auth0 to secure my API, which works perfectly. My setup & config is the same as the suggested setup in the Auth0 documentation:

// SecurityConfig.java
@Configuration
@EnableWebSecurity(debug = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // auth0 config vars here

    @Override
    protected void configure(HttpSecurity http) {
        JwtWebSecurityConfigurer
                .forRS256(apiAudience, issuer)
                .configure(http)
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/api/public").permitAll()
                .antMatchers(HttpMethod.GET, "/api/private").authenticated();
    }
}

With this setup, the spring security principal is being set to the userId (sub) from the jwt token: auth0|5b2b.... However, instead of just the userId, I want it set to the matching user (from my database). My question is how to do that.

What I've tried

I've tried implementing a custom database-backed UserDetailsService that I copied from this tutorial.
However, it's not getting called regardless of how I try to add it to my conf. I've tried adding it several different ways with no effect:

// SecurityConfig.java (changes only)

    // My custom userDetailsService, overriding the loadUserByUsername
    // method from Spring Framework's UserDetailsService.
    @Autowired
    private MyUserDetailsService userDetailsService;

    protected void configure(HttpSecurity http) {
        http.userDetailsService(userDetailsService);  // Option 1
        http.authenticationProvider(authenticationProvider());  // Option 2
        JwtWebSecurityConfigurer
                [...]  // The rest unchanged from above
    }

    @Override  // Option 3 & 4: Override the following method
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(authenticationProvider());  // Option 3
        auth.userDetailsService(userDetailsService);  // Option 4
    }

    @Bean  // Needed for Options 2 or 4
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService);
        return authProvider;
    }

Unfortunately none of the similar "userDetails not being called" questions have helped me due to me needing to combine it with Auth0 authentication.

I'm not positive that I'm on the right path with this. It seems strange to me that I can't find any documentation from Auth0 on this extremely common use case, so maybe I'm missing something obvious.

PS: Not sure if relevant, but the following is always logged during init.

Jun 27, 2018 11:25:22 AM com.test.UserRepository initDao
INFO: No authentication manager set. Reauthentication of users when changing passwords will not be performed.

EDIT 1:

Based on Ashish451's answer, I tried copying his CustomUserDetailsService, and added the following to my SecurityConfig:

@Autowired
private CustomUserDetailsService userService;

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

@Autowired
public void configureGlobal( AuthenticationManagerBuilder auth ) throws Exception {
    auth.userDetailsService( userService );
}

Unfortunately with those changes, CustomUserDetailsService is still not being called.

EDIT 2:

Output when adding the logging method suggested by @Norberto Ritzmann:

Jul 04, 2018 3:49:22 PM com.test.repositories.UserRepositoryImpl initDao
INFO: No authentication manager set. Reauthentication of users when changing passwords will not be performed.
Jul 04, 2018 3:49:22 PM com.test.runner.JettyRunner testUserDetailsImpl
INFO: UserDetailsService implementation: com.test.services.CustomUserDetailsService

Body:
This is what I ended up doing if you want to just stick with using spring libraries. You can change Auth0UserDetailsService to query user details from any source.

public class Auth0JwtAuthenticationProvider implements AuthenticationProvider {

@Autowired
ApplicationContext context;
@Autowired
@Qualifier("auth0UserDetailsService")
UserDetailsService auth0UserDetailsService;
private JwtAuthenticationProvider jwtAuthenticationProvider;

public Auth0JwtAuthenticationProvider() {

}

@PostConstruct
public void postConstruct() {
    jwtAuthenticationProvider = new JwtAuthenticationProvider(context.getBean(JwtDecoder.class));
}

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Authentication token = jwtAuthenticationProvider.authenticate(authentication);
    ((AbstractAuthenticationToken) token).setDetails(auth0UserDetailsService.loadUserByUsername(authentication.getName()));
    return token;
}

@Override
public boolean supports(Class<?> authentication) {
    return BearerTokenAuthenticationToken.class.isAssignableFrom(authentication);
}

}

And for UserDetailsService I am getting user details using a service.

public class Auth0UserDetailsService implements UserDetailsService {

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    RestTemplate restTemplate = new RestTemplate();

    .....
  ResponseEntity<Auth0UserDetails> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, Auth0UserDetails.class);
    return responseEntity.getBody();

}

.....

}

And UserDetails will have all details you need.

public class Auth0UserDetails implements UserDetails {

@JsonProperty("name")
private String userName;

@JsonProperty("created_at")
private LocalDateTime createdAt;

@JsonProperty("email")
private String email;

@JsonProperty("email_verified")
private boolean isEmailVerified;

@JsonProperty("nickname")
private String nickName;

@JsonProperty("picture")
private String pictureURL;

@JsonProperty("updated_at")
private LocalDateTime updatedAt;

@JsonProperty("user_id")
private String userID;

...
//Getters and Setter and overridden methods.

}

    @EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public Auth0JwtAuthenticationProvider auth0JwtAuthenticationProvider() {
        return new Auth0JwtAuthenticationProvider();
    }

    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception {

        httpSecurity.authenticationProvider(auth0JwtAuthenticationProvider()).authorizeRequests().
....
.oauth2ResourceServer().jwt();

}}


问:
Straight line in html
What's the best way to draw a whole single line using html?

What I want is something like this:

but shorter.

I know about the existence [1][2] of ― (―), — (—), &ndash (–), figure dash etc...

But the problem is that they are not cross platform / cross browser: sometimes I get this --- behaviour instead of this ___ but in the middle.

I didn't test all of them, but using the horizontal line does not work on Windows Chrome (while it does on Ubuntu and Android), the em dash works on Windows Chrome but does not work on Firefox and the en dash does not work neither on Android Chrome, Windows Chrome or Firefox.

I know that I could just make a span/div with a border and relatively position it, but the problem is that it would be fixed length, while I need a line which extends based on the content (so that ---this--- could be longer than ---this longer one---), since I have the same content displayed with different languages.

So, is there any character able to draw a cross-browser solid line?

UPDATE: This is what I need

答:
I'm not 100% sure what you want but maybe some CSS might help you?
I don't think using a character for embellishment is appropriate here.

body {
  text-align: center;
}

.with-line {
  display: block;
}

.with-line:before,
.with-line:after {
  content: "";
  display: inline-block;
  border-top: 1px solid #000;
  width: 3em;
  vertical-align: middle;
  margin: 0 0.5em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="with-line">Short</span>

<span class="with-line">Longer</span>

<span class="with-line">Real long sentence to show the length</span></code>```

Title: Straight line in html

Body:
I'm not 100% sure what you want but maybe some CSS might help you?
I don't think using a character for embellishment is appropriate here.

body {
  text-align: center;
}

.with-line {
  display: block;
}

.with-line:before,
.with-line:after {
  content: "";
  display: inline-block;
  border-top: 1px solid #000;
  width: 3em;
  vertical-align: middle;
  margin: 0 0.5em;
}

<span class="with-line">Short</span>

<span class="with-line">Longer</span>

<span class="with-line">Real long sentence to show the length</span>


问:
Can't set the title attribute while loading image in IE 7 and IE 8
I'm in the process of debugging a background image slideshow I wrote.

The flow of the script is that it loads the first image and displays it and then calls the preloadImages function which then loads the rest of the images at a preset interval.

preload_img is a global variable defined at the start of my plugin ( var preload_img = 1; ) that keeps track of the current image number being preloaded and keeps its value like it should, but this value isn't being applied to the title attribute of the image.

```<code>// load the images in sequence one after another
function preloadImages()
{
    clearInterval(interval_preload);

    var div = '<div id="'+options.id_holder+preload_img+'" class="bg_img_holder"></div>';
    $('#'+options.id_wrapper).append(div);

    var img = new Image();

    //alert("loading: " + options.img_path + images[preload_img].image + " " + preload_img);
    $(img).load(function()
    {
        alert("loaded: " + $(this).attr('src') + " " + $(this).attr('title'));
        $img_holder = $('#'+options.id_holder+$(this).attr('title'));

        $img_holder.append(this)
        .css({
        'display':      'none',
        'background-color': images[$(this).attr('title')].background,
        'z-index':      -500
        })
        .find('img')
        .height($img_holder.width() * 0.5625);

    }).attr({
        'src':      options.img_path + images[preload_img].image,
        'title':    preload_img
    });

    //if there's another image to load after this one
    if(++preload_img < (images.length))
    {
        interval_preload = setInterval(preloadImages,1500);
    }
}
</code>```

Although preload_img is defined while it loads the image ( the first alert which is commented out shows the correct value ) when the image is loaded the title is an empty string (the second, uncommented alert).

The issue doesn't present itself when the page is initially opened (open up browser, type in address, hit enter) but does every other time.

It's probably something small I've missed, but I've spent the last hour looking through this and am going crazy.

There's a really basic test case at: http://jsfiddle.net/72Sy6/4/
The alerts generate the expected data in all the browsers I've tested apart from IE7 which, has the expected data when the page is opened, but all other times does not.

I apologise in advance for the alert boxes, but that's the only way I know of debugging in IE7 :X

edit: Hadn't been experiencing errors in IE 8 with the slideshow, but this testcase shows the local variables as being similarly undefined.

答:
For a reason I'm not entirely sure of, changing this:

```<code>var img = new Image();
$(img).load(function(){
    //..
}).attr({
    'src':      options.img_path + images[preload_img].image,
    'title':    preload_img
});
</code>```

to this:

```<code>var img = $('<img src="'+images[preload_img].image+'" title="'+images[preload_img].title+'" />');
$(img).load(function(){
    //..
});
</code>```

fixed the problem.

ContentLicense: CC BY-SA 3.0

Body:
I'm in the process of debugging a background image slideshow I wrote.

The flow of the script is that it loads the first image and displays it and then calls the preloadImages function which then loads the rest of the images at a preset interval.

preload_img is a global variable defined at the start of my plugin ( var preload_img = 1; ) that keeps track of the current image number being preloaded and keeps its value like it should, but this value isn't being applied to the title attribute of the image.

// load the images in sequence one after another
function preloadImages()
{
    clearInterval(interval_preload);

    var div = '

';
    $('#'+options.id_wrapper).append(div);

    var img = new Image();

    //alert("loading: " + options.img_path + images[preload_img].image + " " + preload_img);
    $(img).load(function()
    {
        alert("loaded: " + $(this).attr('src') + " " + $(this).attr('title'));
        $img_holder = $('#'+options.id_holder+$(this).attr('title'));

        $img_holder.append(this)
        .css({
        'display':      'none',
        'background-color': images[$(this).attr('title')].background,
        'z-index':      -500
        })
        .find('img')
        .height($img_holder.width() * 0.5625);

    }).attr({
        'src':      options.img_path + images[preload_img].image,
        'title':    preload_img
    });

    //if there's another image to load after this one
    if(++preload_img < (images.length))
    {
        interval_preload = setInterval(preloadImages,1500);
    }
}

Although preload_img is defined while it loads the image ( the first alert which is commented out shows the correct value ) when the image is loaded the title is an empty string (the second, uncommented alert).

The issue doesn't present itself when the page is initially opened (open up browser, type in address, hit enter) but does every other time.

It's probably something small I've missed, but I've spent the last hour looking through this and am going crazy.

There's a really basic test case at: http://jsfiddle.net/72Sy6/4/
The alerts generate the expected data in all the browsers I've tested apart from IE7 which, has the expected data when the page is opened, but all other times does not.

I apologise in advance for the alert boxes, but that's the only way I know of debugging in IE7 :X

edit: Hadn't been experiencing errors in IE 8 with the slideshow, but this testcase shows the local variables as being similarly undefined.

Body:
For a reason I'm not entirely sure of, changing this:

var img = new Image();
$(img).load(function(){
    //..
}).attr({
    'src':      options.img_path + images[preload_img].image,
    'title':    preload_img
});

to this:

var img = $('<img src="'+images[preload_img].image+'" title="'+images[preload_img].title+'" />');
$(img).load(function(){
    //..
});

fixed the problem.


问:
R: source multiple files with chdir = TRUE using safely
I want to run multiple R scripts that are located in different sub-folders in the "path_source".

```<code>files <- list.files(path = path_source, full.names = T, recursive = T)
</code>```

Scripts that don't run correctly should not stop the program, therefore I use safely()

```<code>safesource <- safely(source)
map_chr(files, safesource)
</code>```

However, in the source() function, I need to pass the additional argument "chdir = T" to change directories accordingly. How would I go about this?

答:
Below does what exactly what I wanted.

```<code>files <- list.files(path = pathsource, full.names = T, recursive = T)
sourcefile <- function(file) {
  source(file, chdir = T)
}
safesource <- safely(sourcefile)
sourceinfo <- map(files, safesource)
</code>```

I consider this solved.

Body:
I want to run multiple R scripts that are located in different sub-folders in the "path_source".

files <- list.files(path = path_source, full.names = T, recursive = T)

Scripts that don't run correctly should not stop the program, therefore I use safely()

safesource <- safely(source)
map_chr(files, safesource)

However, in the source() function, I need to pass the additional argument "chdir = T" to change directories accordingly. How would I go about this?

Body:
Below does what exactly what I wanted.

files <- list.files(path = pathsource, full.names = T, recursive = T)
sourcefile <- function(file) {
  source(file, chdir = T)
}
safesource <- safely(sourcefile)
sourceinfo <- map(files, safesource)

I consider this solved.


问:
Data.frame from nested list of rows, with columns of class list
Very similar to my question here.

Given a named list where each element represents a row in a data.frame one element which may be a list or similar class such as data.frame how can this be transformed into a proper data.frame-like object in a concise manner

Example

```<code>library(data.table)
df_list <- lapply(1:10, function(x)list(a = 1, b = 'hello',
                                        c = 3 - 1i,
                                        d = data.table(e = 1:3,
                                                       f = LETTERS[1:3])))
names(df_list) <- LETTERS[1:10]
</code>```

Expected output

May be exchanged for a data.table object with a rownames column or a data.frame.

```<code>d <- lapply(1:10, function(x)data.table(e = 1:3, f = LETTERS[1:3]))
df <- tibble(a = rep(1, 10), b = rep('hello', 10), c = rep(3 - 1i, 10), d = d)
df$rownames <- LETTERS[1:10]
</code>```

Note:

data.table::rbindlist(df_list, fill = TRUE) and dplyr::bind_rows(df_list) failed in their raw form.

答:
We can use unnest_wider

```<code>library(dplyr)
library(tidyr)
library(tibble)
tibble(col1 = df_list, rn = names(col1)) %>%
             unnest_wider(c(col1))
# A tibble: 10 x 5
#       a b     c     d                        rn
#   <dbl> <chr> <cpl> <list>                   <chr>
# 1     1 hello 3-1i  <data.table[,2] [3 × 2]> A
# 2     1 hello 3-1i  <data.table[,2] [3 × 2]> B
# 3     1 hello 3-1i  <data.table[,2] [3 × 2]> C
# 4     1 hello 3-1i  <data.table[,2] [3 × 2]> D
# 5     1 hello 3-1i  <data.table[,2] [3 × 2]> E
# 6     1 hello 3-1i  <data.table[,2] [3 × 2]> F
# 7     1 hello 3-1i  <data.table[,2] [3 × 2]> G
# 8     1 hello 3-1i  <data.table[,2] [3 × 2]> H
# 9     1 hello 3-1i  <data.table[,2] [3 × 2]> I
#10     1 hello 3-1i  <data.table[,2] [3 × 2]> J
</code>```

Or if we want to use data.table, we can loop over the list, then convert the atomic elements to data.table and create a column with the non-atomic, and then use rbindlist

```<code>library(data.table)
rbindlist(lapply(df_list, function(x)  {
    i1 <- sapply(x, is.data.table)
     as.data.table(x[!i1])[, names(x)[i1] := x[i1]]
    }), idcol= 'rn')
#    rn a     b    c            d
# 1:  A 1 hello 3-1i <data.table>
# 2:  B 1 hello 3-1i <data.table>
# 3:  C 1 hello 3-1i <data.table>
# 4:  D 1 hello 3-1i <data.table>
# 5:  E 1 hello 3-1i <data.table>
# 6:  F 1 hello 3-1i <data.table>
# 7:  G 1 hello 3-1i <data.table>
# 8:  H 1 hello 3-1i <data.table>
# 9:  I 1 hello 3-1i <data.table>
#10:  J 1 hello 3-1i <data.table>
</code>```

Body:
Very similar to my question here.

Given a named list where each element represents a row in a data.frame one element which may be a list or similar class such as data.frame how can this be transformed into a proper data.frame-like object in a concise manner

Example

library(data.table)
df_list <- lapply(1:10, function(x)list(a = 1, b = 'hello',
                                        c = 3 - 1i,
                                        d = data.table(e = 1:3,
                                                       f = LETTERS[1:3])))
names(df_list) <- LETTERS[1:10]

Expected output

May be exchanged for a data.table object with a rownames column or a data.frame.

d <- lapply(1:10, function(x)data.table(e = 1:3, f = LETTERS[1:3]))
df <- tibble(a = rep(1, 10), b = rep('hello', 10), c = rep(3 - 1i, 10), d = d)
df$rownames <- LETTERS[1:10]

Note:

data.table::rbindlist(df_list, fill = TRUE) and dplyr::bind_rows(df_list) failed in their raw form.

Body:
We can use unnest_wider

library(dplyr)
library(tidyr)
library(tibble)
tibble(col1 = df_list, rn = names(col1)) %>%
             unnest_wider(c(col1))
# A tibble: 10 x 5
#       a b     c     d                        rn
#   <dbl> <chr> <cpl> <list>                   <chr>
# 1     1 hello 3-1i  <data.table[,2] [3 × 2]> A
# 2     1 hello 3-1i  <data.table[,2] [3 × 2]> B
# 3     1 hello 3-1i  <data.table[,2] [3 × 2]> C
# 4     1 hello 3-1i  <data.table[,2] [3 × 2]> D
# 5     1 hello 3-1i  <data.table[,2] [3 × 2]> E
# 6     1 hello 3-1i  <data.table[,2] [3 × 2]> F
# 7     1 hello 3-1i  <data.table[,2] [3 × 2]> G
# 8     1 hello 3-1i  <data.table[,2] [3 × 2]> H
# 9     1 hello 3-1i  <data.table[,2] [3 × 2]> I
#10     1 hello 3-1i  <data.table[,2] [3 × 2]> J

Or if we want to use data.table, we can loop over the list, then convert the atomic elements to data.table and create a column with the non-atomic, and then use rbindlist

library(data.table)
rbindlist(lapply(df_list, function(x)  {
    i1 <- sapply(x, is.data.table)
     as.data.table(x[!i1])[, names(x)[i1] := x[i1]]
    }), idcol= 'rn')
#    rn a     b    c            d
# 1:  A 1 hello 3-1i <data.table>
# 2:  B 1 hello 3-1i <data.table>
# 3:  C 1 hello 3-1i <data.table>
# 4:  D 1 hello 3-1i <data.table>
# 5:  E 1 hello 3-1i <data.table>
# 6:  F 1 hello 3-1i <data.table>
# 7:  G 1 hello 3-1i <data.table>
# 8:  H 1 hello 3-1i <data.table>
# 9:  I 1 hello 3-1i <data.table>
#10:  J 1 hello 3-1i <data.table>


问:
Calling pj_thread_register from python
I'm trying to use pjsip via pjsua2 in python.
I have a problem with threading.

```<code>import pjsua2 as pj
import threading

# pjsua2 test function
def pjsua2_test():
  # Create and initialize the library
  ep = pj.Endpoint()
  ep.libCreate()

if __name__ == "__main__":
  pjsuadaemonthread = threading.Thread(name='PJSUA',
                      target=pjsua2_test)
  pjsuadaemonthread.start()
  ep = pj.Endpoint()
  ep.libHandleEvents(10)
</code>```

I get this error:

```<code>python3: ../src/pj/os_core_unix.c:692: pj_thread_this: Assertion `!"Calling pjlib from unknown/external thread. You must " "register external threads with pj_thread_register() " "before calling any pjlib functions."' failed.
</code>```

How do I call pj_thread_register(), from python?

答:
This is the syntax to pj_thread_register():

```<code>ep.libRegisterThread('PJSUA')
</code>```

Unfortunately even if you call libRegisterThread it does not seem compatible with python threading.

I think this is because pjsip internally uses threads of type pj_thread_t and python threads are not of type pj_thread_t.

For more info take a look at Endpoint::libRegisterThread in the pjsip source code.

However, if you just want to run pjsip on a different thread, the code below may help.  It runs pjsip on a background thread named 'PJSUA-THREAD'.  The key is to call libCreate() on a different thread like I do below.

```<code>'''Tests running PJSUA2 in a different thread'''
import logging
import threading
import pjsua2

date_fmt = '%Y-%m-%d,%H:%M:%S'
log_format = "%(levelname)s %(asctime)s.%(msecs)03d %(threadName)s %(name)s.%(funcName)s %(message)s"
logging.basicConfig(format=log_format, datefmt=date_fmt, level=logging.DEBUG)

_logger = logging.getLogger(__name__)

THREAD_NAME = "PJSUA-THREAD"

def main():
    _logger.debug("entered main()")
    pjsuadaemonthread = threading.Thread(name=THREAD_NAME, target=pjsua2_test)
    pjsuadaemonthread.start()
    _logger.debug("thread started")
    pjsuadaemonthread.join()

# pjsua2 test function
def pjsua2_test():
    # NOTE: PjSip will initialize and run on PJSUA-THREAD, see logs
    ep = pjsua2.Endpoint()
    ep.libCreate()
    _logger.debug("after libCreate()")
    ep_cfg = pjsua2.EpConfig()
    ep_cfg.uaConfig.mainThreadOnly = False
    ep_cfg.uaConfig.threadCnt = 1
    ep.libInit(ep_cfg)
    _logger.debug("after libInit(ep_cfg)")
    ep.libStart()
    _logger.debug("after libStart()")
    iter_count = 0
    event_count = 0
    while iter_count < 10:
        event_count += ep.libHandleEvents(10)
        _logger.debug("iter_count %d (%d events processed)", iter_count, event_count)
        iter_count += 1
    ep.libDestroy()
    _logger.debug("after ep.libDestroy()")

if __name__ == "__main__":
    main()
    _logger.debug("after main()")
</code>```

Here is the log output.  You can see pjsip is running on thread PJSUA-THREAD.

```<code>DEBUG 2020-05-31,14:49:43.259 MainThread __main__.main entered main()
14:49:43.261         os_core_unix.c !pjlib 2.8 for POSIX initialized
14:49:43.261         sip_endpoint.c  .Creating endpoint instance...
14:49:43.262                  pjlib  .select() I/O Queue created (0x7fd530013550)
14:49:43.262         sip_endpoint.c  .Module "mod-msg-print" registered
14:49:43.262        sip_transport.c  .Transport manager created.
14:49:43.262           pjsua_core.c  .PJSUA state changed: NULL --> CREATED
DEBUG 2020-05-31,14:49:43.262 PJSUA-THREAD __main__.pjsua2_test after libCreate()
14:49:43.262         sip_endpoint.c  .Module "mod-pjsua-log" registered
14:49:43.263         sip_endpoint.c  .Module "mod-tsx-layer" registered
14:49:43.263         sip_endpoint.c  .Module "mod-stateful-util" registered
14:49:43.263         sip_endpoint.c  .Module "mod-ua" registered
14:49:43.263         sip_endpoint.c  .Module "mod-100rel" registered
14:49:43.263         sip_endpoint.c  .Module "mod-pjsua" registered
14:49:43.263         sip_endpoint.c  .Module "mod-invite" registered
14:49:43.496             alsa_dev.c  ..ALSA driver found 32 devices
14:49:43.496             alsa_dev.c  ..ALSA initialized
14:49:43.496                  pjlib  ..select() I/O Queue created (0x7fd53009cf08)
14:49:43.499         sip_endpoint.c  .Module "mod-evsub" registered
14:49:43.499         sip_endpoint.c  .Module "mod-presence" registered
14:49:43.499         sip_endpoint.c  .Module "mod-mwi" registered
14:49:43.499         sip_endpoint.c  .Module "mod-refer" registered
14:49:43.499         sip_endpoint.c  .Module "mod-pjsua-pres" registered
14:49:43.499         sip_endpoint.c  .Module "mod-pjsua-im" registered
14:49:43.499         sip_endpoint.c  .Module "mod-pjsua-options" registered
14:49:43.499           pjsua_core.c  .1 SIP worker threads created
14:49:43.499           pjsua_core.c  .pjsua version 2.8 for Linux-5.3.0.53/x86_64/glibc-2.27 initialized
14:49:43.499           pjsua_core.c  .PJSUA state changed: CREATED --> INIT
DEBUG 2020-05-31,14:49:43.262 MainThread __main__.main thread started
DEBUG 2020-05-31,14:49:43.499 PJSUA-THREAD __main__.pjsua2_test after libInit(ep_cfg)
14:49:43.499           pjsua_core.c  PJSUA state changed: INIT --> STARTING
DEBUG 2020-05-31,14:49:43.500 PJSUA-THREAD __main__.pjsua2_test after libStart()
14:49:43.500         sip_endpoint.c  .Module "mod-unsolicited-mwi" registered
14:49:43.500           pjsua_core.c  .PJSUA state changed: STARTING --> RUNNING
DEBUG 2020-05-31,14:49:43.510 PJSUA-THREAD __main__.pjsua2_test iter_count 0 (0 events processed)
DEBUG 2020-05-31,14:49:43.520 PJSUA-THREAD __main__.pjsua2_test iter_count 1 (0 events processed)
DEBUG 2020-05-31,14:49:43.531 PJSUA-THREAD __main__.pjsua2_test iter_count 2 (0 events processed)
DEBUG 2020-05-31,14:49:43.541 PJSUA-THREAD __main__.pjsua2_test iter_count 3 (0 events processed)
DEBUG 2020-05-31,14:49:43.551 PJSUA-THREAD __main__.pjsua2_test iter_count 4 (0 events processed)
DEBUG 2020-05-31,14:49:43.562 PJSUA-THREAD __main__.pjsua2_test iter_count 5 (0 events processed)
DEBUG 2020-05-31,14:49:43.572 PJSUA-THREAD __main__.pjsua2_test iter_count 6 (0 events processed)
DEBUG 2020-05-31,14:49:43.582 PJSUA-THREAD __main__.pjsua2_test iter_count 7 (0 events processed)
DEBUG 2020-05-31,14:49:43.593 PJSUA-THREAD __main__.pjsua2_test iter_count 8 (0 events processed)
DEBUG 2020-05-31,14:49:43.603 PJSUA-THREAD __main__.pjsua2_test iter_count 9 (0 events processed)
14:49:43.604           pjsua_core.c  Shutting down, flags=0...
14:49:43.604           pjsua_core.c  PJSUA state changed: RUNNING --> CLOSING
14:49:43.610           pjsua_call.c  .Hangup all calls..
14:49:43.610          pjsua_media.c  .Call 0: deinitializing media..
14:49:43.610          pjsua_media.c  .Call 1: deinitializing media..
14:49:43.610          pjsua_media.c  .Call 2: deinitializing media..
14:49:43.610          pjsua_media.c  .Call 3: deinitializing media..
14:49:43.610           pjsua_pres.c  .Shutting down presence..
14:49:44.610           pjsua_core.c  .Destroying...
14:49:44.610          pjsua_media.c  .Shutting down media..
14:49:44.997      sip_transaction.c  .Stopping transaction layer module
14:49:44.997      sip_transaction.c  .Stopped transaction layer module
14:49:44.997         sip_endpoint.c  .Module "mod-unsolicited-mwi" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-pjsua-options" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-pjsua-im" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-pjsua-pres" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-pjsua" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-stateful-util" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-refer" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-mwi" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-presence" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-evsub" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-invite" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-100rel" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-ua" unregistered
14:49:44.997      sip_transaction.c  .Transaction layer module destroyed
14:49:44.997         sip_endpoint.c  .Module "mod-tsx-layer" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-msg-print" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-pjsua-log" unregistered
14:49:44.997         sip_endpoint.c  .Endpoint 0x7fd5300087b8 destroyed
14:49:44.997           pjsua_core.c  .PJSUA state changed: CLOSING --> NULL
14:49:44.997           pjsua_core.c  .PJSUA destroyed...
DEBUG 2020-05-31,14:49:44.997 PJSUA-THREAD __main__.pjsua2_test after ep.libDestroy()
DEBUG 2020-05-31,14:49:45.000 MainThread __main__.<module> after main()
</code>```

Title: Calling pj_thread_register from python

Body:
I'm trying to use pjsip via pjsua2 in python.
I have a problem with threading.

import pjsua2 as pj
import threading

# pjsua2 test function
def pjsua2_test():
  # Create and initialize the library
  ep = pj.Endpoint()
  ep.libCreate()

if __name__ == "__main__":
  pjsuadaemonthread = threading.Thread(name='PJSUA',
                      target=pjsua2_test)
  pjsuadaemonthread.start()
  ep = pj.Endpoint()
  ep.libHandleEvents(10)

I get this error:

python3: ../src/pj/os_core_unix.c:692: pj_thread_this: Assertion `!"Calling pjlib from unknown/external thread. You must " "register external threads with pj_thread_register() " "before calling any pjlib functions."' failed.

How do I call pj_thread_register(), from python?

Body:
This is the syntax to pj_thread_register():

ep.libRegisterThread('PJSUA')

Unfortunately even if you call libRegisterThread it does not seem compatible with python threading.

I think this is because pjsip internally uses threads of type pj_thread_t and python threads are not of type pj_thread_t.

For more info take a look at Endpoint::libRegisterThread in the pjsip source code.

However, if you just want to run pjsip on a different thread, the code below may help.  It runs pjsip on a background thread named 'PJSUA-THREAD'.  The key is to call libCreate() on a different thread like I do below.

'''Tests running PJSUA2 in a different thread'''
import logging
import threading
import pjsua2

date_fmt = '%Y-%m-%d,%H:%M:%S'
log_format = "%(levelname)s %(asctime)s.%(msecs)03d %(threadName)s %(name)s.%(funcName)s %(message)s"
logging.basicConfig(format=log_format, datefmt=date_fmt, level=logging.DEBUG)

_logger = logging.getLogger(__name__)

THREAD_NAME = "PJSUA-THREAD"

def main():
    _logger.debug("entered main()")
    pjsuadaemonthread = threading.Thread(name=THREAD_NAME, target=pjsua2_test)
    pjsuadaemonthread.start()
    _logger.debug("thread started")
    pjsuadaemonthread.join()

# pjsua2 test function
def pjsua2_test():
    # NOTE: PjSip will initialize and run on PJSUA-THREAD, see logs
    ep = pjsua2.Endpoint()
    ep.libCreate()
    _logger.debug("after libCreate()")
    ep_cfg = pjsua2.EpConfig()
    ep_cfg.uaConfig.mainThreadOnly = False
    ep_cfg.uaConfig.threadCnt = 1
    ep.libInit(ep_cfg)
    _logger.debug("after libInit(ep_cfg)")
    ep.libStart()
    _logger.debug("after libStart()")
    iter_count = 0
    event_count = 0
    while iter_count < 10:
        event_count += ep.libHandleEvents(10)
        _logger.debug("iter_count %d (%d events processed)", iter_count, event_count)
        iter_count += 1
    ep.libDestroy()
    _logger.debug("after ep.libDestroy()")

if __name__ == "__main__":
    main()
    _logger.debug("after main()")

Here is the log output.  You can see pjsip is running on thread PJSUA-THREAD.

DEBUG 2020-05-31,14:49:43.259 MainThread __main__.main entered main()
14:49:43.261         os_core_unix.c !pjlib 2.8 for POSIX initialized
14:49:43.261         sip_endpoint.c  .Creating endpoint instance...
14:49:43.262                  pjlib  .select() I/O Queue created (0x7fd530013550)
14:49:43.262         sip_endpoint.c  .Module "mod-msg-print" registered
14:49:43.262        sip_transport.c  .Transport manager created.
14:49:43.262           pjsua_core.c  .PJSUA state changed: NULL --> CREATED
DEBUG 2020-05-31,14:49:43.262 PJSUA-THREAD __main__.pjsua2_test after libCreate()
14:49:43.262         sip_endpoint.c  .Module "mod-pjsua-log" registered
14:49:43.263         sip_endpoint.c  .Module "mod-tsx-layer" registered
14:49:43.263         sip_endpoint.c  .Module "mod-stateful-util" registered
14:49:43.263         sip_endpoint.c  .Module "mod-ua" registered
14:49:43.263         sip_endpoint.c  .Module "mod-100rel" registered
14:49:43.263         sip_endpoint.c  .Module "mod-pjsua" registered
14:49:43.263         sip_endpoint.c  .Module "mod-invite" registered
14:49:43.496             alsa_dev.c  ..ALSA driver found 32 devices
14:49:43.496             alsa_dev.c  ..ALSA initialized
14:49:43.496                  pjlib  ..select() I/O Queue created (0x7fd53009cf08)
14:49:43.499         sip_endpoint.c  .Module "mod-evsub" registered
14:49:43.499         sip_endpoint.c  .Module "mod-presence" registered
14:49:43.499         sip_endpoint.c  .Module "mod-mwi" registered
14:49:43.499         sip_endpoint.c  .Module "mod-refer" registered
14:49:43.499         sip_endpoint.c  .Module "mod-pjsua-pres" registered
14:49:43.499         sip_endpoint.c  .Module "mod-pjsua-im" registered
14:49:43.499         sip_endpoint.c  .Module "mod-pjsua-options" registered
14:49:43.499           pjsua_core.c  .1 SIP worker threads created
14:49:43.499           pjsua_core.c  .pjsua version 2.8 for Linux-5.3.0.53/x86_64/glibc-2.27 initialized
14:49:43.499           pjsua_core.c  .PJSUA state changed: CREATED --> INIT
DEBUG 2020-05-31,14:49:43.262 MainThread __main__.main thread started
DEBUG 2020-05-31,14:49:43.499 PJSUA-THREAD __main__.pjsua2_test after libInit(ep_cfg)
14:49:43.499           pjsua_core.c  PJSUA state changed: INIT --> STARTING
DEBUG 2020-05-31,14:49:43.500 PJSUA-THREAD __main__.pjsua2_test after libStart()
14:49:43.500         sip_endpoint.c  .Module "mod-unsolicited-mwi" registered
14:49:43.500           pjsua_core.c  .PJSUA state changed: STARTING --> RUNNING
DEBUG 2020-05-31,14:49:43.510 PJSUA-THREAD __main__.pjsua2_test iter_count 0 (0 events processed)
DEBUG 2020-05-31,14:49:43.520 PJSUA-THREAD __main__.pjsua2_test iter_count 1 (0 events processed)
DEBUG 2020-05-31,14:49:43.531 PJSUA-THREAD __main__.pjsua2_test iter_count 2 (0 events processed)
DEBUG 2020-05-31,14:49:43.541 PJSUA-THREAD __main__.pjsua2_test iter_count 3 (0 events processed)
DEBUG 2020-05-31,14:49:43.551 PJSUA-THREAD __main__.pjsua2_test iter_count 4 (0 events processed)
DEBUG 2020-05-31,14:49:43.562 PJSUA-THREAD __main__.pjsua2_test iter_count 5 (0 events processed)
DEBUG 2020-05-31,14:49:43.572 PJSUA-THREAD __main__.pjsua2_test iter_count 6 (0 events processed)
DEBUG 2020-05-31,14:49:43.582 PJSUA-THREAD __main__.pjsua2_test iter_count 7 (0 events processed)
DEBUG 2020-05-31,14:49:43.593 PJSUA-THREAD __main__.pjsua2_test iter_count 8 (0 events processed)
DEBUG 2020-05-31,14:49:43.603 PJSUA-THREAD __main__.pjsua2_test iter_count 9 (0 events processed)
14:49:43.604           pjsua_core.c  Shutting down, flags=0...
14:49:43.604           pjsua_core.c  PJSUA state changed: RUNNING --> CLOSING
14:49:43.610           pjsua_call.c  .Hangup all calls..
14:49:43.610          pjsua_media.c  .Call 0: deinitializing media..
14:49:43.610          pjsua_media.c  .Call 1: deinitializing media..
14:49:43.610          pjsua_media.c  .Call 2: deinitializing media..
14:49:43.610          pjsua_media.c  .Call 3: deinitializing media..
14:49:43.610           pjsua_pres.c  .Shutting down presence..
14:49:44.610           pjsua_core.c  .Destroying...
14:49:44.610          pjsua_media.c  .Shutting down media..
14:49:44.997      sip_transaction.c  .Stopping transaction layer module
14:49:44.997      sip_transaction.c  .Stopped transaction layer module
14:49:44.997         sip_endpoint.c  .Module "mod-unsolicited-mwi" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-pjsua-options" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-pjsua-im" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-pjsua-pres" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-pjsua" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-stateful-util" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-refer" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-mwi" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-presence" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-evsub" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-invite" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-100rel" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-ua" unregistered
14:49:44.997      sip_transaction.c  .Transaction layer module destroyed
14:49:44.997         sip_endpoint.c  .Module "mod-tsx-layer" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-msg-print" unregistered
14:49:44.997         sip_endpoint.c  .Module "mod-pjsua-log" unregistered
14:49:44.997         sip_endpoint.c  .Endpoint 0x7fd5300087b8 destroyed
14:49:44.997           pjsua_core.c  .PJSUA state changed: CLOSING --> NULL
14:49:44.997           pjsua_core.c  .PJSUA destroyed...
DEBUG 2020-05-31,14:49:44.997 PJSUA-THREAD __main__.pjsua2_test after ep.libDestroy()
DEBUG 2020-05-31,14:49:45.000 MainThread __main__.<module> after main()


问:
Nested material-ui table using recursive function on tree data structure, how to align columns?
I have a nested material-ui, the code for which is here table which displays a to-do-list of tasks. I use a tree structure to store the tasks and their child tasks and so on. The problem I have is that the table's columns do not line up with each other or the header, I believe this is due to the div tags surrounding the tableRow and Collapse components and possibly the collapse component, however I'm not sure how to rewrite the code without this, as the function must render a row for the tasks data and run the function recursively on the tasks' children in the collapse component to render them.</p>

答:
I have implemented a solution here that works pretty well.

The 2 problems were in this particular function for the table rows:

```<code>function treeTable(taskTree) {
    return taskTree.children.map(task => (
      <div>
        <TableRow hover key={task.value.id}>
          {headers.map(({ key, format = value => value }) => (
            <TableCell>{format(task.value[key])}</TableCell>
          ))}
          <TableCell padding="default">
            {task.children.length > 0 ? (
              <Button
                key={task.value.id}
                onClick={() => handleClick(task.value.id)}
              >
                {state[task.value.id] ? <ExpandLess /> : <ExpandMore />}
              </Button>
            ) : null}
          </TableCell>
        </TableRow>
        <Collapse
          key={task.value.id}
          // component="table"
          in={state[task.value.id]}
          timeout="auto"
          unmountOnExit
        >
          {treeTable(task)}
        </Collapse>
      </div>
    ));
  }
</code>```

Problem 1: the  wrapping the table row and collapse element breaks the continuity of the table components (which must come one after the other without another component outside). The solution here was simple, to replace the div with a React.fragment.

Problem 2: The collapse component also breaks this continuity of table components. If one instead puts the contents of the cells in a collapse component then they collapse appropriately.

The other facet of this solution is it now means one must pass down the state key for the collapse element down into the function as an argument, with a parent key for the top layer which is created and set true on the first load of the react component, when that state is undefined.

In order to have the rows collapse one must also add the prop style={{ padding: 0 }} to any cells containing collapse components (if you want more padding when the rows are expanded you'll need to add a conditional padding.

The improved function is now as follows:

```<code>function treeTable(taskTree, collapseId) {
    return taskTree.children.map(task => (
      <React.Fragment>
        <TableRow hover key={task.value.id}>
        {headers.map(({ key, format = value => value }) => (
            <TableCell style={{ padding: 0 }}>
              <Collapse
                key={collapseId}
                // component="table"
                in={state[collapseId]}
                timeout="auto"
                unmountOnExit
              >
                {format(task.value[key])}
              </Collapse>
            </TableCell>
          ))}
          <TableCell style={{ padding: 0 }}>
            <Collapse
              key={collapseId}
              // component="table"
              in={state[collapseId]}
              timeout="auto"
              unmountOnExit
            >
              {task.children.length > 0 ? (
                <Button
                  key={task.value.id}
                  onClick={() => handleClick(task.value.id)}
                >
                  {state[task.value.id] ? <ExpandLess /> : <ExpandMore />}
                </Button>
              ) : null}
            </Collapse>
          </TableCell>
        </TableRow>
        {treeTable(task, task.value.id)}
      </React.Fragment>
    ));
  }
</code>```

Body:
I have implemented a solution here that works pretty well.

The 2 problems were in this particular function for the table rows:

function treeTable(taskTree) {
    return taskTree.children.map(task => (
      <div>
        <TableRow hover key={task.value.id}>
          {headers.map(({ key, format = value => value }) => (
            <TableCell>{format(task.value[key])}</TableCell>
          ))}
          <TableCell padding="default">
            {task.children.length > 0 ? (
              <Button
                key={task.value.id}
                onClick={() => handleClick(task.value.id)}
              >
                {state[task.value.id] ? <ExpandLess /> : <ExpandMore />}
              </Button>
            ) : null}
          </TableCell>
        </TableRow>
        <Collapse
          key={task.value.id}
          // component="table"
          in={state[task.value.id]}
          timeout="auto"
          unmountOnExit
        >
          {treeTable(task)}
        </Collapse>
      </div>
    ));
  }

Problem 1: the  wrapping the table row and collapse element breaks the continuity of the table components (which must come one after the other without another component outside). The solution here was simple, to replace the div with a React.fragment.

Problem 2: The collapse component also breaks this continuity of table components. If one instead puts the contents of the cells in a collapse component then they collapse appropriately.

The other facet of this solution is it now means one must pass down the state key for the collapse element down into the function as an argument, with a parent key for the top layer which is created and set true on the first load of the react component, when that state is undefined.

In order to have the rows collapse one must also add the prop style={{ padding: 0 }} to any cells containing collapse components (if you want more padding when the rows are expanded you'll need to add a conditional padding.

The improved function is now as follows:

function treeTable(taskTree, collapseId) {
    return taskTree.children.map(task => (
      <React.Fragment>
        <TableRow hover key={task.value.id}>
        {headers.map(({ key, format = value => value }) => (
            <TableCell style={{ padding: 0 }}>
              <Collapse
                key={collapseId}
                // component="table"
                in={state[collapseId]}
                timeout="auto"
                unmountOnExit
              >
                {format(task.value[key])}
              </Collapse>
            </TableCell>
          ))}
          <TableCell style={{ padding: 0 }}>
            <Collapse
              key={collapseId}
              // component="table"
              in={state[collapseId]}
              timeout="auto"
              unmountOnExit
            >
              {task.children.length > 0 ? (
                <Button
                  key={task.value.id}
                  onClick={() => handleClick(task.value.id)}
                >
                  {state[task.value.id] ? <ExpandLess /> : <ExpandMore />}
                </Button>
              ) : null}
            </Collapse>
          </TableCell>
        </TableRow>
        {treeTable(task, task.value.id)}
      </React.Fragment>
    ));
  }


问:
When we keep two images only one image is shown Android
I need to solve this problem actually , I made a activity and I took two different images of different ratio and when I put two Images in them only one is showing why is that I have already done some fixing which are android:adjustViewBonds=true and many more but it isn't working, I am using URI instead of Bitmap any suggestions how can it be fixed I did every available method
above is the xml file you can see two images inside constraint layout they both are parallel to each other when I keep the ratio of any image say 1:1 for image 1, 13:3 for image 2 or something like this
all this doesn't work only one image displays any suggests how to make it work thanks
Thanks...Any Questions Kindly ask :)</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="600dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/hgfgfh"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:background="@color/common_google_signin_btn_text_dark_default"
            android:gravity="center"
            android:maxLines="1"
            android:textSize="23sp"
            android:textAlignment="center"
            android:textColor="#000000" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="57dp"
            android:orientation="horizontal">

            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/fdgfdg"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:layout_margin="10dp"/>

            <TextView
                android:layout_width="172dp"
                android:layout_height="31dp"
                android:layout_gravity="center_vertical"
                android:layout_marginStart="8dp"
                android:text="ghfhgf"
                android:textColor="#000000"
                android:textSize="16sp" />

            <ImageView
                android:id="@+id/textView2"
                android:layout_width="37dp"
                android:layout_height="32dp"
                android:layout_gravity="center_vertical"
                android:layout_marginStart="70dp"
                android:src="@drawable/moreitems_foreground" />

        </LinearLayout>

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/image1"
                android:layout_width="198dp"
                android:layout_height="302dp"
                android:layout_centerInParent="true"
                android:adjustViewBounds="true"
                android:maxWidth="39dip"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.5"

                app:layout_constraintTop_toTopOf="parent" />

            <ImageView
                android:id="@+id/image2"
                android:layout_width="198dp"
                android:layout_height="302dp"
                android:adjustViewBounds="true"
                android:maxWidth="39dip"
                android:layout_centerInParent="true"

                app:layout_constraintHorizontal_bias="0.5"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintVertical_bias="0.0" />

        </androidx.constraintlayout.widget.ConstraintLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:padding="8dp">

            <ImageView
                android:layout_width="38dp"
                android:layout_height="33dp"
                android:id="@+id/view"
                android:background="@drawable/border"
                android:src="@drawable/view_v_foreground" />

            <Button
                android:id="@+id/like"
                android:layout_width="35dp"
                android:layout_height="36dp"
                android:layout_marginStart="43dp"
                android:background="@drawable/ic_fd_foreground"
                android:backgroundTint="@color/blue"
                android:focusedByDefault="true" />

            <ImageView
                android:id="@+id/save"
                android:layout_width="36dp"
                android:layout_height="32dp"
                android:layout_alignParentEnd="true"
                android:src="@drawable/pump" />

        </RelativeLayout>

        <TextView
            android:id="@+id/sdfsdf"
            android:layout_width="411dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="1dp"
            android:text="Vsdfs"
            android:textColor="@color/blue" />

        <ImageView
            android:layout_width="36dp"
            android:layout_height="33dp"
            android:layout_marginTop="8dp"
            android:src="@drawable/ic_rfgfdrt_foreground" />

    </LinearLayout>

</RelativeLayout>
</code>```

答:
As i see in your xml view you have some errors. In ImageView with id=@+id/image1 you should replace

```<code>    app:layout_constraintStart_toEndOf="@+id/gfdfdg"
</code>```

with

```<code>    app:layout_constraintStart_toEndOf="@+id/image2"
</code>```

and in ImageView with id=@+id/image2 you should replace

```<code>    app:layout_constraintEnd_toStartOf="@+id/dfgdfg"
</code>```

with

```<code>    app:layout_constraintEnd_toStartOf="@+id/image1"
</code>```

try it out and let me know is it working with replacements.

EDIT>
with this replacements set for image1 and image2

```<code>    android:layout_width="0dp"
</code>```

Body:
I need to solve this problem actually , I made a activity and I took two different images of different ratio and when I put two Images in them only one is showing why is that I have already done some fixing which are android:adjustViewBonds=true and many more but it isn't working, I am using URI instead of Bitmap any suggestions how can it be fixed I did every available method
above is the xml file you can see two images inside constraint layout they both are parallel to each other when I keep the ratio of any image say 1:1 for image 1, 13:3 for image 2 or something like this
all this doesn't work only one image displays any suggests how to make it work thanks
Thanks...Any Questions Kindly ask :)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="600dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/hgfgfh"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:background="@color/common_google_signin_btn_text_dark_default"
            android:gravity="center"
            android:maxLines="1"
            android:textSize="23sp"
            android:textAlignment="center"
            android:textColor="#000000" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="57dp"
            android:orientation="horizontal">

            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/fdgfdg"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:layout_margin="10dp"/>

            <TextView
                android:layout_width="172dp"
                android:layout_height="31dp"
                android:layout_gravity="center_vertical"
                android:layout_marginStart="8dp"
                android:text="ghfhgf"
                android:textColor="#000000"
                android:textSize="16sp" />

            <ImageView
                android:id="@+id/textView2"
                android:layout_width="37dp"
                android:layout_height="32dp"
                android:layout_gravity="center_vertical"
                android:layout_marginStart="70dp"
                android:src="@drawable/moreitems_foreground" />

        </LinearLayout>

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/image1"
                android:layout_width="198dp"
                android:layout_height="302dp"
                android:layout_centerInParent="true"
                android:adjustViewBounds="true"
                android:maxWidth="39dip"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.5"

                app:layout_constraintTop_toTopOf="parent" />

            <ImageView
                android:id="@+id/image2"
                android:layout_width="198dp"
                android:layout_height="302dp"
                android:adjustViewBounds="true"
                android:maxWidth="39dip"
                android:layout_centerInParent="true"

                app:layout_constraintHorizontal_bias="0.5"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintVertical_bias="0.0" />

        </androidx.constraintlayout.widget.ConstraintLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:padding="8dp">

            <ImageView
                android:layout_width="38dp"
                android:layout_height="33dp"
                android:id="@+id/view"
                android:background="@drawable/border"
                android:src="@drawable/view_v_foreground" />

            <Button
                android:id="@+id/like"
                android:layout_width="35dp"
                android:layout_height="36dp"
                android:layout_marginStart="43dp"
                android:background="@drawable/ic_fd_foreground"
                android:backgroundTint="@color/blue"
                android:focusedByDefault="true" />

            <ImageView
                android:id="@+id/save"
                android:layout_width="36dp"
                android:layout_height="32dp"
                android:layout_alignParentEnd="true"
                android:src="@drawable/pump" />

        </RelativeLayout>

        <TextView
            android:id="@+id/sdfsdf"
            android:layout_width="411dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="1dp"
            android:text="Vsdfs"
            android:textColor="@color/blue" />

        <ImageView
            android:layout_width="36dp"
            android:layout_height="33dp"
            android:layout_marginTop="8dp"
            android:src="@drawable/ic_rfgfdrt_foreground" />

    </LinearLayout>

</RelativeLayout>

Body:
As i see in your xml view you have some errors. In ImageView with id=@+id/image1 you should replace

    app:layout_constraintStart_toEndOf="@+id/gfdfdg"

with

    app:layout_constraintStart_toEndOf="@+id/image2"

and in ImageView with id=@+id/image2 you should replace

    app:layout_constraintEnd_toStartOf="@+id/dfgdfg"

with

    app:layout_constraintEnd_toStartOf="@+id/image1"

try it out and let me know is it working with replacements.

EDIT>
with this replacements set for image1 and image2

    android:layout_width="0dp"


问:
Count decimal numbers in a string using the standard library
I have white-space separeted integers inside a string, e.g.:

```<code>std::string s = "1 2 33 444 0 5";
</code>```

The string is well-formed: just white-space separated numbers without any letters, new-lines, etc.

How to count the number of integers in the above string in an STL way? I am looking for something "short" that will use e.g. iterators or <algorithm>.

答:
You can use regular expressions:

```<code>#include <iterator>
#include <regex>
#include <string>

std::string s = "1 2 33 444 0 5";

const std::regex regex("\\d+");
const auto n = std::distance(
    std::sregex_iterator(s.begin(), s.end(), regex),
    std::sregex_iterator());
</code>```

This will handle multiple, leading and trailing whitespaces automatically. This approach doesn't impose any limitation on the length of each integer.

Body:
I have white-space separeted integers inside a string, e.g.:

std::string s = "1 2 33 444 0 5";

The string is well-formed: just white-space separated numbers without any letters, new-lines, etc.

How to count the number of integers in the above string in an STL way? I am looking for something "short" that will use e.g. iterators or <algorithm>.

Body:
You can use regular expressions:

#include <iterator>
#include <regex>
#include <string>

std::string s = "1 2 33 444 0 5";

const std::regex regex("\\d+");
const auto n = std::distance(
    std::sregex_iterator(s.begin(), s.end(), regex),
    std::sregex_iterator());

This will handle multiple, leading and trailing whitespaces automatically. This approach doesn't impose any limitation on the length of each integer.


问:
How to check if all values in the columns of a numpy matrix are the same?
I want to check if all values in the columns of a numpy array/matrix are the same.
I tried to use reduce of the ufunc equal, but it doesn't seem to work in all cases:

```<code>In [55]: a = np.array([[1,1,0],[1,-1,0],[1,0,0],[1,1,0]])

In [56]: a
Out[56]:
array([[ 1,  1,  0],
       [ 1, -1,  0],
       [ 1,  0,  0],
       [ 1,  1,  0]])

In [57]: np.equal.reduce(a)
Out[57]: array([ True, False,  True], dtype=bool)

In [58]: a = np.array([[1,1,0],[1,0,0],[1,0,0],[1,1,0]])

In [59]: a
Out[59]:
array([[1, 1, 0],
       [1, 0, 0],
       [1, 0, 0],
       [1, 1, 0]])

In [60]: np.equal.reduce(a)
Out[60]: array([ True,  True,  True], dtype=bool)
</code>```

Why does the middle column in the second case also evaluate to True, while it should be False?

Thanks for any help!

答:
Not as elegant but may also work in the example above.

```<code>a = np.array([[1,1,0],[1,-1,0],[1,0,0],[1,1,0]])
</code>```

take the difference between the each row and the one above it

```<code>np.diff(a,axis=0)==0

array([[ True, False,  True],
       [ True, False,  True],
       [ True, False,  True]])
</code>```

Body:
I want to check if all values in the columns of a numpy array/matrix are the same.
I tried to use reduce of the ufunc equal, but it doesn't seem to work in all cases:

In [55]: a = np.array([[1,1,0],[1,-1,0],[1,0,0],[1,1,0]])

In [56]: a
Out[56]:
array([[ 1,  1,  0],
       [ 1, -1,  0],
       [ 1,  0,  0],
       [ 1,  1,  0]])

In [57]: np.equal.reduce(a)
Out[57]: array([ True, False,  True], dtype=bool)

In [58]: a = np.array([[1,1,0],[1,0,0],[1,0,0],[1,1,0]])

In [59]: a
Out[59]:
array([[1, 1, 0],
       [1, 0, 0],
       [1, 0, 0],
       [1, 1, 0]])

In [60]: np.equal.reduce(a)
Out[60]: array([ True,  True,  True], dtype=bool)

Why does the middle column in the second case also evaluate to True, while it should be False?

Thanks for any help!

Body:
Not as elegant but may also work in the example above.

a = np.array([[1,1,0],[1,-1,0],[1,0,0],[1,1,0]])

take the difference between the each row and the one above it

np.diff(a,axis=0)==0

array([[ True, False,  True],
       [ True, False,  True],
       [ True, False,  True]])


问:
Implementation Issue: Deep ConvNet for Pattern Recognition
I'm trying to implement a pattern recognition model using a fully convolutional network (fig 1 in https://www.sciencedirect.com/science/article/pii/S0031320318304370, I was able to get the full text without signing in or anything but if it's a problem I can attach a picture too!) but I'm getting a size error when moving from the final Conv2D layer to the first fc_layer.

Here is my error message:

```<code>RuntimeError: size mismatch, m1: [4 x 1024], m2: [4 x 1024] at /pytorch/aten/src/THC/generic/THCTensorMathBlas.cu:283

</code>```

Originally, as in the figure, my first linear layer was:

```<code>nn.Linear(4*4*512, 1024)

</code>```

but after getting the size mismatch, I changed it to:

```<code>nn.Linear(4,1024)

</code>```

Now, I have a strange error message as written above.

For reference (if it helps), here is my code:

```<code>
import torch.nn as nn
import torch.utils.model_zoo as model_zoo

class convnet(nn.Module):

    def __init__(self, num_classes=1000):
        super(convnet, self).__init__()
        self.features = nn.Sequential(
            nn.Conv2d(1, 64, kernel_size=3, stride=2, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(64, 64, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(64, 64, kernel_size=3, padding=1),
            nn.MaxPool2d(kernel_size=1),
            nn.Conv2d(64, 128, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(128, 128, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=2),# stride=2),
            nn.Conv2d(128, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(256, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=2), #stride=2),
            nn.Conv2d(256, 512, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(512, 512, kernel_size=3, padding=1),
            nn.ReLU(inplace=True), #nn.Dropout(p=0.5)
        )

        self.classifier = nn.Sequential(
            nn.Linear(4, 1024),
            nn.Dropout(p=0.5),
            nn.ReLU(inplace=True),
            #nn.Dropout(p=0.5),
            nn.Linear(1024, 1024),
            nn.ReLU(inplace=True),
            nn.Linear(1024, num_classes),
        )

    def forward(self, x):
        x = self.features(x)
        x = torch.flatten(x,1)
        x = self.classifier(x)
        return x
</code>```

I suspect it's an issue with the padding and stride.
Thanks!

答:
The error is from a matrix multiplication, where m1 should be an m x n matrix and m2 an n x p matrix and the result would be an m x p matrix. In your case it's 4 x 1024 and 4 x 1024, but that doesn't work since 1024 != 4.

That means your input to the first linear layer has size [4, 1024] (4 being the batch size), therefore the input features of the first linear layer should be 1024.

self.classifier = nn.Sequential(
    nn.Linear(1024, 1024),
    nn.Dropout(p=0.5),
    nn.ReLU(inplace=True),
    #nn.Dropout(p=0.5),
    nn.Linear(1024, 1024),
    nn.ReLU(inplace=True),
    nn.Linear(1024, num_classes),
)
```

<p>If you are uncertain how many features your input has, you can print out its size just before the layer:</p>

<pre class="lang-py prettyprint-override"><code>x = self.features(x)
x = torch.flatten(x,1)
print(x.size()) # => torch.Size([4, 1024])
x = self.classifier(x)
</code>```

Body:
I'm trying to implement a pattern recognition model using a fully convolutional network (fig 1 in https://www.sciencedirect.com/science/article/pii/S0031320318304370, I was able to get the full text without signing in or anything but if it's a problem I can attach a picture too!) but I'm getting a size error when moving from the final Conv2D layer to the first fc_layer.

Here is my error message:

RuntimeError: size mismatch, m1: [4 x 1024], m2: [4 x 1024] at /pytorch/aten/src/THC/generic/THCTensorMathBlas.cu:283

Originally, as in the figure, my first linear layer was:

nn.Linear(4*4*512, 1024)

but after getting the size mismatch, I changed it to:

nn.Linear(4,1024)

Now, I have a strange error message as written above.

For reference (if it helps), here is my code:

import torch.nn as nn
import torch.utils.model_zoo as model_zoo

class convnet(nn.Module):

    def __init__(self, num_classes=1000):
        super(convnet, self).__init__()
        self.features = nn.Sequential(
            nn.Conv2d(1, 64, kernel_size=3, stride=2, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(64, 64, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(64, 64, kernel_size=3, padding=1),
            nn.MaxPool2d(kernel_size=1),
            nn.Conv2d(64, 128, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(128, 128, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=2),# stride=2),
            nn.Conv2d(128, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(256, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=2), #stride=2),
            nn.Conv2d(256, 512, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(512, 512, kernel_size=3, padding=1),
            nn.ReLU(inplace=True), #nn.Dropout(p=0.5)
        )

        self.classifier = nn.Sequential(
            nn.Linear(4, 1024),
            nn.Dropout(p=0.5),
            nn.ReLU(inplace=True),
            #nn.Dropout(p=0.5),
            nn.Linear(1024, 1024),
            nn.ReLU(inplace=True),
            nn.Linear(1024, num_classes),
        )

    def forward(self, x):
        x = self.features(x)
        x = torch.flatten(x,1)
        x = self.classifier(x)
        return x

I suspect it's an issue with the padding and stride.
Thanks!

Body:
The error is from a matrix multiplication, where m1 should be an m x n matrix and m2 an n x p matrix and the result would be an m x p matrix. In your case it's 4 x 1024 and 4 x 1024, but that doesn't work since 1024 != 4.

That means your input to the first linear layer has size [4, 1024] (4 being the batch size), therefore the input features of the first linear layer should be 1024.

self.classifier = nn.Sequential(
    nn.Linear(1024, 1024),
    nn.Dropout(p=0.5),
    nn.ReLU(inplace=True),
    #nn.Dropout(p=0.5),
    nn.Linear(1024, 1024),
    nn.ReLU(inplace=True),
    nn.Linear(1024, num_classes),
)

If you are uncertain how many features your input has, you can print out its size just before the layer:

x = self.features(x)
x = torch.flatten(x,1)
print(x.size()) # => torch.Size([4, 1024])
x = self.classifier(x)


问:
How can I remove an object from array in python?
How can I remove an object from array in python?

I want to select an msgID and want to delete that full object with username, msg, time_stamp (all of it).

```<code>room_msg =  [
 {
  'msgID': 1,
  'username': 'User1',
  'msg': 'msg1',
  'time_stamp': 'May-31 05:29PM'},
 {
  'msgID': 2,
  'username': 'User2',
  'msg': 'msg2',
  'time_stamp': 'May-31 05:29PM'},
{
  'msgID': 3,
  'username': 'User3',
  'msg': 'msg3',
  'time_stamp': 'May-31 05:29PM'} ]
</code>```

Like if I select 'msgID': 3
after deleting the 'msgID': 3 the array should like this

```<code>room_msg = [
 {
  'msgID': 1,
  'username': 'User1',
  'msg': 'msg1',
  'time_stamp': 'May-31 05:29PM'},
 {
  'msgID': 2,
  'username': 'User2',
  'msg': 'msg2',
  'time_stamp': 'May-31 05:29PM'}
]
</code>```

Is that possible?
I can't find x with that msgID room_msg[x].

答:
Try using del on the matching array indices.

```<code>for index, msg in enumerate(room_msg):
    if msg['msgID'] == 3:
        del room_msg[index]
</code>```

Body:
How can I remove an object from array in python?

I want to select an msgID and want to delete that full object with username, msg, time_stamp (all of it).

room_msg =  [
 {
  'msgID': 1,
  'username': 'User1',
  'msg': 'msg1',
  'time_stamp': 'May-31 05:29PM'},
 {
  'msgID': 2,
  'username': 'User2',
  'msg': 'msg2',
  'time_stamp': 'May-31 05:29PM'},
{
  'msgID': 3,
  'username': 'User3',
  'msg': 'msg3',
  'time_stamp': 'May-31 05:29PM'} ]

Like if I select 'msgID': 3
after deleting the 'msgID': 3 the array should like this

room_msg = [
 {
  'msgID': 1,
  'username': 'User1',
  'msg': 'msg1',
  'time_stamp': 'May-31 05:29PM'},
 {
  'msgID': 2,
  'username': 'User2',
  'msg': 'msg2',
  'time_stamp': 'May-31 05:29PM'}
]

Is that possible?
I can't find x with that msgID room_msg[x].

Body:
Try using del on the matching array indices.

for index, msg in enumerate(room_msg):
    if msg['msgID'] == 3:
        del room_msg[index]


答:
You can use list comprehension:

```<code>room_msg = [m for m in room_msg if m['msgID'] != 3]

from pprint import pprint
pprint(room_msg)
</code>```

Prints:

```<code>[{'msg': 'msg1',
  'msgID': 1,
  'time_stamp': 'May-31 05:29PM',
  'username': 'User1'},
 {'msg': 'msg2',
  'msgID': 2,
  'time_stamp': 'May-31 05:29PM',
  'username': 'User2'}]
</code>```

Title: How can I remove an object from array in python?

Body:
You can use list comprehension:

room_msg = [m for m in room_msg if m['msgID'] != 3]

from pprint import pprint
pprint(room_msg)

Prints:

[{'msg': 'msg1',
  'msgID': 1,
  'time_stamp': 'May-31 05:29PM',
  'username': 'User1'},
 {'msg': 'msg2',
  'msgID': 2,
  'time_stamp': 'May-31 05:29PM',
  'username': 'User2'}]


问:
Just defined a new variable and now program is stuck in an infinite loop
I am a beginner at programing, and I wrote a script that implements an Optimization algorithm. It worked fine at first; but then I tried to make it faster by defining a new variable, and now for some reason it appears to be stuck in an infinite loop. Here is the first version (I have indicated in a comment where the change will happen):

```<code># This program uses the Steepest Descent Method to
# minimize the Rosenbrock function
import numpy as np
import time

# Define the Rosenbrock Function
def f(x_k):
    x, y = x_k[0, 0], x_k[0, 1]
    return 100 * (y - x**2)**2 + (1 - x)**2

# Gradient of f
def gradient(x_k):
    x, y = x_k[0, 0], x_k[0, 1]
    return  np.array([[-400*x*(y-x**2)-2*(1-x), 200*(y-x**2)]])

def main():
    start = time.time()
    # Define the starting guess
    x_k = np.array([[2, 2]])
    # Define counter for number of steps
    numSteps = 0

    # Keep iterating until both components of the gradient are less than 0.1 in absolute value
    while abs((gradient(x_k)[0, 0])) > 0.1 or abs((gradient(x_k))[0, 1]) > 0.1:
        numSteps = numSteps + 1

        # Step direction
        p_k = - gradient(x_k)
        gradTrans = - p_k.T

        # Now we use a backtracking algorithm to find a step length
        alpha = 1.0
        ratio = 0.8
        c = 0.01 # This is just a constant that is used in the algorithm

        # This loop selects an alpha which satisfies the Armijo condition

        #####################################
        ###### CHANGE WILL HAPPEN HERE ######
        #####################################

        while f(x_k + alpha * p_k) > f(x_k) + (alpha * c * (gradTrans  @ p_k))[0, 0]:
            alpha = ratio * alpha

        x_k = x_k + alpha * p_k
    end =  time.time()
    print("The number of steps is: ", numSteps)
    print("The final step is:", x_k)
    print("The gradient is: ", gradient(x_k))
    print("The elapsed time is:", round(end - start, 2), "seconds.")

main()
</code>```

Now, the program is very inefficient because in the second while loop, the quantity f(x_k) + (alpha * c * (gradTrans  @ p_k))[0, 0]: is computed at each iteration, even though it is constant. So I decided to name this quantity RHS = f(x_k) + (alpha * c * (gradTrans  @ p_k))[0, 0]: and just put that in the while loop. The new code is below. All I did was define this quantity as a variable, and now the program gets stuck in a infinite loop. Thank you very much for any help.

```<code># This program uses the Steepest Descent Method to
# minimize the Rosenbrock function
import numpy as np
import time

# Define the Rosenbrock Function
def f(x_k):
    x, y = x_k[0, 0], x_k[0, 1]
    return 100 * (y - x**2)**2 + (1 - x)**2

# Gradient of f
def gradient(x_k):
    x, y = x_k[0, 0], x_k[0, 1]
    return  np.array([[-400*x*(y-x**2)-2*(1-x), 200*(y-x**2)]])

def main():
    start = time.time()
    # Define the starting guess
    x_k = np.array([[2, 2]])
    # Define counter for number of steps
    numSteps = 0

    # Keep iterating until both components of the gradient are less than 0.1 in absolute value
    while abs((gradient(x_k)[0, 0])) > 0.1 or abs((gradient(x_k))[0, 1]) > 0.1:
        numSteps = numSteps + 1

        # Step direction
        p_k = - gradient(x_k)
        gradTrans = - p_k.T

        # Now we use a backtracking algorithm to find a step length
        alpha = 1.0
        ratio = 0.8
        c = 0.01 # This is just a constant that is used in the algorithm

        # This loop selects an alpha which satisfies the Armijo condition
        RHS = f(x_k) + (alpha * c * (gradTrans  @ p_k))[0, 0]

        #####################################
        ###### CHANGE HAS OCCURED ###########
        #####################################

        while f(x_k + alpha * p_k) > RHS:
            alpha = ratio * alpha

        x_k = x_k + alpha * p_k
    end =  time.time()
    print("The number of steps is: ", numSteps)
    print("The final step is:", x_k)
    print("The gradient is: ", gradient(x_k))
    print("The elapsed time is:", round(end - start), "seconds.")

main()
</code>```

答: RHS needs to be re-calcuated inside the loop, using the new value for alpha.  (Not sure how this is meant to speed things up.)

Body:
I am a beginner at programing, and I wrote a script that implements an Optimization algorithm. It worked fine at first; but then I tried to make it faster by defining a new variable, and now for some reason it appears to be stuck in an infinite loop. Here is the first version (I have indicated in a comment where the change will happen):

# This program uses the Steepest Descent Method to
# minimize the Rosenbrock function
import numpy as np
import time

# Define the Rosenbrock Function
def f(x_k):
    x, y = x_k[0, 0], x_k[0, 1]
    return 100 * (y - x**2)**2 + (1 - x)**2

# Gradient of f
def gradient(x_k):
    x, y = x_k[0, 0], x_k[0, 1]
    return  np.array([[-400*x*(y-x**2)-2*(1-x), 200*(y-x**2)]])

def main():
    start = time.time()
    # Define the starting guess
    x_k = np.array([[2, 2]])
    # Define counter for number of steps
    numSteps = 0

    # Keep iterating until both components of the gradient are less than 0.1 in absolute value
    while abs((gradient(x_k)[0, 0])) > 0.1 or abs((gradient(x_k))[0, 1]) > 0.1:
        numSteps = numSteps + 1

        # Step direction
        p_k = - gradient(x_k)
        gradTrans = - p_k.T

        # Now we use a backtracking algorithm to find a step length
        alpha = 1.0
        ratio = 0.8
        c = 0.01 # This is just a constant that is used in the algorithm

        # This loop selects an alpha which satisfies the Armijo condition

        #####################################
        ###### CHANGE WILL HAPPEN HERE ######
        #####################################

        while f(x_k + alpha * p_k) > f(x_k) + (alpha * c * (gradTrans  @ p_k))[0, 0]:
            alpha = ratio * alpha

        x_k = x_k + alpha * p_k
    end =  time.time()
    print("The number of steps is: ", numSteps)
    print("The final step is:", x_k)
    print("The gradient is: ", gradient(x_k))
    print("The elapsed time is:", round(end - start, 2), "seconds.")

main()

Now, the program is very inefficient because in the second while loop, the quantity f(x_k) + (alpha * c * (gradTrans  @ p_k))[0, 0]: is computed at each iteration, even though it is constant. So I decided to name this quantity RHS = f(x_k) + (alpha * c * (gradTrans  @ p_k))[0, 0]: and just put that in the while loop. The new code is below. All I did was define this quantity as a variable, and now the program gets stuck in a infinite loop. Thank you very much for any help.

# This program uses the Steepest Descent Method to
# minimize the Rosenbrock function
import numpy as np
import time

# Define the Rosenbrock Function
def f(x_k):
    x, y = x_k[0, 0], x_k[0, 1]
    return 100 * (y - x**2)**2 + (1 - x)**2

# Gradient of f
def gradient(x_k):
    x, y = x_k[0, 0], x_k[0, 1]
    return  np.array([[-400*x*(y-x**2)-2*(1-x), 200*(y-x**2)]])

def main():
    start = time.time()
    # Define the starting guess
    x_k = np.array([[2, 2]])
    # Define counter for number of steps
    numSteps = 0

    # Keep iterating until both components of the gradient are less than 0.1 in absolute value
    while abs((gradient(x_k)[0, 0])) > 0.1 or abs((gradient(x_k))[0, 1]) > 0.1:
        numSteps = numSteps + 1

        # Step direction
        p_k = - gradient(x_k)
        gradTrans = - p_k.T

        # Now we use a backtracking algorithm to find a step length
        alpha = 1.0
        ratio = 0.8
        c = 0.01 # This is just a constant that is used in the algorithm

        # This loop selects an alpha which satisfies the Armijo condition
        RHS = f(x_k) + (alpha * c * (gradTrans  @ p_k))[0, 0]

        #####################################
        ###### CHANGE HAS OCCURED ###########
        #####################################

        while f(x_k + alpha * p_k) > RHS:
            alpha = ratio * alpha

        x_k = x_k + alpha * p_k
    end =  time.time()
    print("The number of steps is: ", numSteps)
    print("The final step is:", x_k)
    print("The gradient is: ", gradient(x_k))
    print("The elapsed time is:", round(end - start), "seconds.")

main()


问:
How to split array in chunks of set size by value in javascript?
I've been trying to get my head around this but I've had no luck at all. I've tried various ways, one of it being the forEach array method but I'm not able to get the output I need.

Idea is, MEAL DEAL: $2.99 - must be a combination of 1x Sandwich, 1x drink and 1x quick bite.

If it's just 1x each of the items in array, it works but when there are more than 1 of each item in array, I cant get it to work

I have the following array but it may vary:

[
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 },
  { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
]
```

<p>I need to split that into parts like below:</p>

<pre class="lang-js prettyprint-override"><code>IN MEAL DEAL
[
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
  { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
]

NOT IN MEAL DEAL (IF SANDWICH IS ADDED, IT BECOMES MEAL DEAL)
[
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 }
]
</code>```

Sorry, if the explanation is not too good.

Idea is, each chunk must have all 3 element with following values.
1x COLD DRINK
1x SANDWICH
1x QUICK BITES

What I've tried:

```<code>var ITM ="";
var PER_CATEGORY_SET = [];
var value = [
      { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
      { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
      { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
      { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 },
      { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 },
      { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 7.5 }
    ]

value.forEach(function (my_item){
var xx = value.length;

while (xx > 0) {
   if(ITM !=  my_item.CAT ){
   ITM = my_item.CAT;PER_CATEGORY_SET.push({'CAT':my_item.CAT,'QTY':my_item.QTY,'PRICE':my_item.PRICE});
   value.splice(0, 1);
 }
   xx--;
  }
});
</code>```

Output I get is below, it work to create only initial array than it don't do anything:

```<code> [
      { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
      { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
      { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
 ]
</code>```

答:
Create 2 new arrays and loop through the original array once. If i is even, then push in first array, else push in second array.

```<code>const originalArray =  [
    {"CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2},
    {"CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5},
    {"CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5},
    {"CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5},
    {"CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3},
    {"CAT": "SANDWICHES", "QTY": 1, "PRICE": 7.5}
    ]

 var firstChunk = [];
 var secondChunk = [];

 for(var i = 0; i<originalArray.length; i++){
     if(i%2 === 0){
         firstChunk.push(originalArray[i]);
     }
     else{
         secondChunk.push(originalArray[i]);
     }
 }
</code>```

You can access both chucks through firstChunk and secondChunk respectively

Body:
I've been trying to get my head around this but I've had no luck at all. I've tried various ways, one of it being the forEach array method but I'm not able to get the output I need.

Idea is, MEAL DEAL: $2.99 - must be a combination of 1x Sandwich, 1x drink and 1x quick bite.

If it's just 1x each of the items in array, it works but when there are more than 1 of each item in array, I cant get it to work

I have the following array but it may vary:

[
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 },
  { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
]

I need to split that into parts like below:

IN MEAL DEAL
[
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
  { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
]

NOT IN MEAL DEAL (IF SANDWICH IS ADDED, IT BECOMES MEAL DEAL)
[
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 }
]

Sorry, if the explanation is not too good.

Idea is, each chunk must have all 3 element with following values.
1x COLD DRINK
1x SANDWICH
1x QUICK BITES

What I've tried:

var ITM ="";
var PER_CATEGORY_SET = [];
var value = [
      { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
      { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
      { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
      { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 },
      { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 },
      { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 7.5 }
    ]

value.forEach(function (my_item){
var xx = value.length;

while (xx > 0) {
   if(ITM !=  my_item.CAT ){
   ITM = my_item.CAT;PER_CATEGORY_SET.push({'CAT':my_item.CAT,'QTY':my_item.QTY,'PRICE':my_item.PRICE});
   value.splice(0, 1);
 }
   xx--;
  }
});

Output I get is below, it work to create only initial array than it don't do anything:

 [
      { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
      { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
      { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
 ]

Body:
Create 2 new arrays and loop through the original array once. If i is even, then push in first array, else push in second array.

const originalArray =  [
    {"CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2},
    {"CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5},
    {"CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5},
    {"CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5},
    {"CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3},
    {"CAT": "SANDWICHES", "QTY": 1, "PRICE": 7.5}
    ]

 var firstChunk = [];
 var secondChunk = [];

 for(var i = 0; i<originalArray.length; i++){
     if(i%2 === 0){
         firstChunk.push(originalArray[i]);
     }
     else{
         secondChunk.push(originalArray[i]);
     }
 }

You can access both chucks through firstChunk and secondChunk respectively


问:
C# - Why float.CompareTo() using big numbers (like 1000000000f) don't work as expected
Why float.CompareTo() using big numbers don't work as expected?

Test numbers:

```<code>float a = 1000000000f;
float b = 1000000001f;
float c = 1000000002f;
float d = 999999999f;
</code>```

Results:

```<code>a.CompareTo(a) = 0
a.CompareTo(b) = 0
a.CompareTo(c) = 0
a.CompareTo(d) = 0
</code>```

The documentation says that:

Less than zero: This instance precedes obj in the sort order.

Zero: This instance occurs in the same position in the sort order as obj.

Greater than zero: This instance follows obj in the sort order.

And as you can see the results says that a, b, c and d are the same.

But, if I use smaller numbers, like:

```<code>float a = 100000f;
float b = 100001f;
float c = 100002f;
float d = 99999f;
</code>```

Results:

```<code>a.CompareTo(a) = 0
a.CompareTo(b) = -1
a.CompareTo(c) = -1
a.CompareTo(d) = 1
</code>```

Comparing the numbers correctly.

I read Is floating point math broken? and I understand the precision errors when having decimal numbers. But why that big numbers without decimals have this unexpected results?

Context. Why using CompareTo?

I was working on some pathfinding algorithms like BFS, Dijkstra and A*, and I end up using IComparable in a class for my PriorityQueue, then while testing I got that errors. And while I solved all the errors in my algorithm, I want to know why that happened.

Edit

I test printing the value as @GSerg suggested, and I got more questions.
a.ToString("N0"), b.ToString("N0"), c.ToString("N0"), d.ToString("N0"), in the first scenario all four variables print: "1,000,000,000". And in the second scenario prints the correct smaller numbers.

Answer

As I understand, the reason of this behaviour is because a large float number is stored in a "scientific notation" like style, making them to lose precision with their decimals. And Is floating point math broken? explains that.

答:
This is because a float can represent integer values from −16,777,216 to 16,777,216.
https://en.wikipedia.org/wiki/Single-precision_floating-point_format#Precision_limitations_on_integer_values

When using double you get expected results.

```<code>double a = 1000000000;
double b = 1000000001;
double c = 1000000002;
double d = 999999999;
</code>```

Body:
Why float.CompareTo() using big numbers don't work as expected?

Test numbers:

float a = 1000000000f;
float b = 1000000001f;
float c = 1000000002f;
float d = 999999999f;

Results:

a.CompareTo(a) = 0
a.CompareTo(b) = 0
a.CompareTo(c) = 0
a.CompareTo(d) = 0

The documentation says that:

Less than zero: This instance precedes obj in the sort order.

Zero: This instance occurs in the same position in the sort order as obj.

Greater than zero: This instance follows obj in the sort order.

And as you can see the results says that a, b, c and d are the same.

But, if I use smaller numbers, like:

float a = 100000f;
float b = 100001f;
float c = 100002f;
float d = 99999f;

Results:

a.CompareTo(a) = 0
a.CompareTo(b) = -1
a.CompareTo(c) = -1
a.CompareTo(d) = 1

Comparing the numbers correctly.

I read Is floating point math broken? and I understand the precision errors when having decimal numbers. But why that big numbers without decimals have this unexpected results?

Context. Why using CompareTo?

I was working on some pathfinding algorithms like BFS, Dijkstra and A*, and I end up using IComparable in a class for my PriorityQueue, then while testing I got that errors. And while I solved all the errors in my algorithm, I want to know why that happened.

Edit

I test printing the value as @GSerg suggested, and I got more questions.
a.ToString("N0"), b.ToString("N0"), c.ToString("N0"), d.ToString("N0"), in the first scenario all four variables print: "1,000,000,000". And in the second scenario prints the correct smaller numbers.

Answer

As I understand, the reason of this behaviour is because a large float number is stored in a "scientific notation" like style, making them to lose precision with their decimals. And Is floating point math broken? explains that.

Body:
This is because a float can represent integer values from −16,777,216 to 16,777,216.
https://en.wikipedia.org/wiki/Single-precision_floating-point_format#Precision_limitations_on_integer_values

When using double you get expected results.

double a = 1000000000;
double b = 1000000001;
double c = 1000000002;
double d = 999999999;