问:
Spring Oauth2 CORS
I'm trying to call my login service in an Angular app but I'm stuck with CORS error.
I already added cors config on WebSecurityConfigurerAdapter. I already tried some configurations like the ones below. Everything works nice on postman.

AuthorizationServerConfigurerAdapter

```<code>            import java.util.Arrays;
            import java.util.Collections;
            import java.util.List;
            import javax.servlet.http.HttpServletRequest;
            import javax.servlet.http.HttpServletResponse;
            import javax.sql.DataSource;
            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.beans.factory.annotation.Qualifier;
            import org.springframework.context.annotation.Bean;
            import org.springframework.context.annotation.Configuration;
            import org.springframework.security.authentication.AuthenticationManager;
            import org.springframework.security.core.userdetails.UserDetailsService;
            import org.springframework.security.crypto.password.PasswordEncoder;
            import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
            import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
            import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
            import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
            import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
            import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
            import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
            import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
            import org.springframework.security.oauth2.provider.token.TokenEnhancer;
            import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
            import org.springframework.security.oauth2.provider.token.TokenStore;
            import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
            import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
            import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
            import org.springframework.web.cors.CorsConfiguration;
            import org.springframework.web.cors.CorsConfigurationSource;
            import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
            import org.springframework.web.servlet.config.annotation.CorsRegistry;
            import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

            @Configuration
            @EnableAuthorizationServer
            public class OAuth2AuthorizationServer extends AuthorizationServerConfigurerAdapter {

              @Autowired
              @Qualifier("dataSource")
              private DataSource dataSource;

              @Autowired private AuthenticationManager authenticationManager;
              @Autowired private UserDetailsService userDetailsService;
              @Autowired private PasswordEncoder oauthClientPasswordEncoder;

              @Bean
              JwtAccessTokenConverter accessTokenConverter() {
                JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
                ((DefaultAccessTokenConverter) converter.getAccessTokenConverter())
                    .setUserTokenConverter(userAuthenticationConverter());

                return converter;
              }

              @Bean
              public TokenEnhancer tokenEnhancer() {
                return new CustomTokenEnhancer();
              }

              @Bean
              public TokenStore tokenStore() {
                return new JwtTokenStore(accessTokenConverter());
              }

              @Bean
              public OAuth2AccessDeniedHandler oauthAccessDeniedHandler() {
                return new OAuth2AccessDeniedHandler();
              }

              @Override
              public void configure(AuthorizationServerSecurityConfigurer oauthServer) {

                oauthServer
                    .tokenKeyAccess("permitAll()")
                    .checkTokenAccess("isAuthenticated()")
                    .passwordEncoder(oauthClientPasswordEncoder);
              }

              @Override
              public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
                clients.jdbc(dataSource);
              }

              @Bean
              public UserAuthenticationConverter userAuthenticationConverter() {
                DefaultUserAuthenticationConverter defaultUserAuthenticationConverter =
                    new DefaultUserAuthenticationConverter();
                defaultUserAuthenticationConverter.setUserDetailsService(userDetailsService);
                return defaultUserAuthenticationConverter;
              }

              @Override
              public void configure(final AuthorizationServerEndpointsConfigurer endpoints) {
                TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
                tokenEnhancerChain.setTokenEnhancers(
                    List.of(new CustomTokenEnhancer(), accessTokenConverter()));

                endpoints
                    .accessTokenConverter(accessTokenConverter())
                    .userDetailsService(userDetailsService)
                    .authenticationManager(authenticationManager)
                    .tokenEnhancer(tokenEnhancerChain);
              }

            }
</code>```

ResourceServerConfigurerAdapter

```<code>            import org.springframework.context.annotation.Bean;
            import org.springframework.context.annotation.Configuration;
            import org.springframework.security.config.annotation.web.builders.HttpSecurity;
            import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
            import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
            import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
            import org.springframework.web.cors.CorsConfiguration;
            import org.springframework.web.cors.CorsConfigurationSource;
            import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

            import java.util.Arrays;

            @Configuration
            @EnableResourceServer
            public class OAuth2ResourceServer extends ResourceServerConfigurerAdapter {
              private static final String SECURED_PATTERN = "/secured/**";
              private static final String SECURED_READ_SCOPE = "#oauth2.hasScope('read')";
              private static final String SECURED_WRITE_SCOPE = "#oauth2.hasScope('write')";

              @Override
              public void configure(ResourceServerSecurityConfigurer resources) {
                resources.resourceId("resource-server-rest-api").stateless(false);
              }

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

                http.cors().and().antMatcher("/api/**")
                        .authorizeRequests()
                        .antMatchers("/**", "/login**", "/error**", "/api/auth/**")
                        .permitAll()
                ;
                http.authorizeRequests().antMatchers("/api/**").authenticated();

              }
              @Bean
              CorsConfigurationSource corsConfigurationSource() {
                CorsConfiguration configuration = new CorsConfiguration();
                configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200/"));
                configuration.setAllowedMethods(Arrays.asList("GET","POST"));
                UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
                source.registerCorsConfiguration("/**", configuration);
                return source;
              }
            }
</code>```

WebSecurityConfigurerAdapter

```<code>            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.context.annotation.Bean;
            import org.springframework.context.annotation.Configuration;
            import org.springframework.security.authentication.AuthenticationManager;
            import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
            import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
            import org.springframework.security.config.annotation.web.builders.HttpSecurity;
            import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
            import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
            import org.springframework.security.core.userdetails.UserDetailsService;
            import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
            import org.springframework.security.crypto.password.PasswordEncoder;

            @Configuration
            @EnableWebSecurity
            @EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
            public class Oauth2WebSecurityConfig extends WebSecurityConfigurerAdapter {

              @Autowired private UserDetailsService userDetailsService;
              @Autowired private PasswordEncoder userPasswordEncoder;

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

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

              @Override
              protected void configure(HttpSecurity http) throws Exception {

                http.cors().and().antMatcher("/**")
                    .authorizeRequests()
                    .antMatchers("/**", "/login**", "/error**", "/api/auth/**")
                    .permitAll()
                ;

                http.cors().and()
                        .formLogin();
            ;
              }

              @Bean
              public BCryptPasswordEncoder passwordEncoder() {
                return new BCryptPasswordEncoder();
              }
            }
</code>```

答:
The first step when a browser tries to verify CORS is by sending an option method, so you should also enable OPTIONS method, you cors configuration</p>

```<code>@Bean
              CorsConfigurationSource corsConfigurationSource() {
                CorsConfiguration configuration = new CorsConfiguration();
                configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200/"));
                configuration.setAllowedMethods(Arrays.asList("GET","POST","OPTIONS"));
                UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
                source.registerCorsConfiguration("/**", configuration);
                return source;
              }
</code>```

Title: Spring Oauth2 CORS

Body:
I'm trying to call my login service in an Angular app but I'm stuck with CORS error.
I already added cors config on WebSecurityConfigurerAdapter. I already tried some configurations like the ones below. Everything works nice on postman.

AuthorizationServerConfigurerAdapter

            import java.util.Arrays;
            import java.util.Collections;
            import java.util.List;
            import javax.servlet.http.HttpServletRequest;
            import javax.servlet.http.HttpServletResponse;
            import javax.sql.DataSource;
            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.beans.factory.annotation.Qualifier;
            import org.springframework.context.annotation.Bean;
            import org.springframework.context.annotation.Configuration;
            import org.springframework.security.authentication.AuthenticationManager;
            import org.springframework.security.core.userdetails.UserDetailsService;
            import org.springframework.security.crypto.password.PasswordEncoder;
            import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
            import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
            import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
            import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
            import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
            import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
            import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
            import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
            import org.springframework.security.oauth2.provider.token.TokenEnhancer;
            import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
            import org.springframework.security.oauth2.provider.token.TokenStore;
            import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
            import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
            import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
            import org.springframework.web.cors.CorsConfiguration;
            import org.springframework.web.cors.CorsConfigurationSource;
            import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
            import org.springframework.web.servlet.config.annotation.CorsRegistry;
            import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

            @Configuration
            @EnableAuthorizationServer
            public class OAuth2AuthorizationServer extends AuthorizationServerConfigurerAdapter {

              @Autowired
              @Qualifier("dataSource")
              private DataSource dataSource;

              @Autowired private AuthenticationManager authenticationManager;
              @Autowired private UserDetailsService userDetailsService;
              @Autowired private PasswordEncoder oauthClientPasswordEncoder;

              @Bean
              JwtAccessTokenConverter accessTokenConverter() {
                JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
                ((DefaultAccessTokenConverter) converter.getAccessTokenConverter())
                    .setUserTokenConverter(userAuthenticationConverter());

                return converter;
              }

              @Bean
              public TokenEnhancer tokenEnhancer() {
                return new CustomTokenEnhancer();
              }

              @Bean
              public TokenStore tokenStore() {
                return new JwtTokenStore(accessTokenConverter());
              }

              @Bean
              public OAuth2AccessDeniedHandler oauthAccessDeniedHandler() {
                return new OAuth2AccessDeniedHandler();
              }

              @Override
              public void configure(AuthorizationServerSecurityConfigurer oauthServer) {

                oauthServer
                    .tokenKeyAccess("permitAll()")
                    .checkTokenAccess("isAuthenticated()")
                    .passwordEncoder(oauthClientPasswordEncoder);
              }

              @Override
              public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
                clients.jdbc(dataSource);
              }

              @Bean
              public UserAuthenticationConverter userAuthenticationConverter() {
                DefaultUserAuthenticationConverter defaultUserAuthenticationConverter =
                    new DefaultUserAuthenticationConverter();
                defaultUserAuthenticationConverter.setUserDetailsService(userDetailsService);
                return defaultUserAuthenticationConverter;
              }

              @Override
              public void configure(final AuthorizationServerEndpointsConfigurer endpoints) {
                TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
                tokenEnhancerChain.setTokenEnhancers(
                    List.of(new CustomTokenEnhancer(), accessTokenConverter()));

                endpoints
                    .accessTokenConverter(accessTokenConverter())
                    .userDetailsService(userDetailsService)
                    .authenticationManager(authenticationManager)
                    .tokenEnhancer(tokenEnhancerChain);
              }

            }

ResourceServerConfigurerAdapter

            import org.springframework.context.annotation.Bean;
            import org.springframework.context.annotation.Configuration;
            import org.springframework.security.config.annotation.web.builders.HttpSecurity;
            import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
            import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
            import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
            import org.springframework.web.cors.CorsConfiguration;
            import org.springframework.web.cors.CorsConfigurationSource;
            import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

            import java.util.Arrays;

            @Configuration
            @EnableResourceServer
            public class OAuth2ResourceServer extends ResourceServerConfigurerAdapter {
              private static final String SECURED_PATTERN = "/secured/**";
              private static final String SECURED_READ_SCOPE = "#oauth2.hasScope('read')";
              private static final String SECURED_WRITE_SCOPE = "#oauth2.hasScope('write')";

              @Override
              public void configure(ResourceServerSecurityConfigurer resources) {
                resources.resourceId("resource-server-rest-api").stateless(false);
              }

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

                http.cors().and().antMatcher("/api/**")
                        .authorizeRequests()
                        .antMatchers("/**", "/login**", "/error**", "/api/auth/**")
                        .permitAll()
                ;
                http.authorizeRequests().antMatchers("/api/**").authenticated();

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

WebSecurityConfigurerAdapter

            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.context.annotation.Bean;
            import org.springframework.context.annotation.Configuration;
            import org.springframework.security.authentication.AuthenticationManager;
            import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
            import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
            import org.springframework.security.config.annotation.web.builders.HttpSecurity;
            import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
            import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
            import org.springframework.security.core.userdetails.UserDetailsService;
            import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
            import org.springframework.security.crypto.password.PasswordEncoder;

            @Configuration
            @EnableWebSecurity
            @EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
            public class Oauth2WebSecurityConfig extends WebSecurityConfigurerAdapter {

              @Autowired private UserDetailsService userDetailsService;
              @Autowired private PasswordEncoder userPasswordEncoder;

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

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

              @Override
              protected void configure(HttpSecurity http) throws Exception {

                http.cors().and().antMatcher("/**")
                    .authorizeRequests()
                    .antMatchers("/**", "/login**", "/error**", "/api/auth/**")
                    .permitAll()
                ;

                http.cors().and()
                        .formLogin();
            ;
              }

              @Bean
              public BCryptPasswordEncoder passwordEncoder() {
                return new BCryptPasswordEncoder();
              }
            }

Body:
The first step when a browser tries to verify CORS is by sending an option method, so you should also enable OPTIONS method, you cors configuration

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


来源: stackexchange

问:
Multiple if and for loop in list comprehension
I am facing issue while converting my below code in list comprehension

```<code>A = {
  "name": ['sahil', 'pankaj', 'honey'],
  'test': 'data'
}

Mylist = []
for k, v in A.items():
    if isinstance(v, list):
        for i in v:
            Mylist.append(i)
    else:
        Mylist.append(v)
</code>```

I tried this code via list comprehension but failed to get the result

```<code>Mylist = [i
  for k, v in A.items() if isinstance(v, list) for i in v
  else i = v
]
</code>```

I am facing issue syntax error.

答:
since you know that key 'name' holds a list and the key 'test' holds a string you can use:

```<code>Mylist = [e for e in [*A['name'], A['test']]]
</code>```

and more simple:

```<code>Mylist = [*A['name'], A['test']]
</code>```

in the above line, you are creating a list using the unpacking operator and your string element

output:

```<code>['sahil', 'pankaj', 'honey', 'data']
</code>```

or if you do not want wnat to use the dict keys you can use:

```<code>Mylist = [i for e in A.values()  for i in (e if isinstance(e, list) else [e])]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am facing issue while converting my below code in list comprehension

A = {
  "name": ['sahil', 'pankaj', 'honey'],
  'test': 'data'
}

Mylist = []
for k, v in A.items():
    if isinstance(v, list):
        for i in v:
            Mylist.append(i)
    else:
        Mylist.append(v)

I tried this code via list comprehension but failed to get the result

Mylist = [i
  for k, v in A.items() if isinstance(v, list) for i in v
  else i = v
]

I am facing issue syntax error.

Body:
since you know that key 'name' holds a list and the key 'test' holds a string you can use:

Mylist = [e for e in [*A['name'], A['test']]]

and more simple:

Mylist = [*A['name'], A['test']]

in the above line, you are creating a list using the unpacking operator and your string element

output:

['sahil', 'pankaj', 'honey', 'data']

or if you do not want wnat to use the dict keys you can use:

Mylist = [i for e in A.values()  for i in (e if isinstance(e, list) else [e])]


问:
how to remove header and footer into the window.print();
I am using window.print() for printing page, but I got header and footer contains page title, file path, page number, and date. How to remove them or edit?

I tried this also.

```<code>@media print {
  @page { margin: 0; }
  body { margin: 1.6cm; }
}
</code>```

i try all solution of this page
but any solution is not working for me.

this is my div content that is find from POJO.

```<code><div id="textDiv">
    <pre id="foo"><%= student.getDescription()%>```

```

<p>this is my button.</p>

```<button onclick="printDiv('textDiv')">Print PDF</button>
```

<p>this is my Script for Print.</p>

```function printDiv(divName) {
 var printContents = document.getElementById(divName).innerHTML;
 var originalContents = document.body.innerHTML;
 document.body.innerHTML = printContents;
 window.print();
 document.body.innerHTML = originalContents;
}

// Use this method

@media print {
    .footer,
    #non-printable {
        display: none !important;
    }
    #printable {
        display: block;
    }
}
```

答:
Try this below

```<code><script language="javascript">
function printDiv() {
var printContents = document.getElementById("divName").innerHTML;
var originalContents = document.body.innerHTML;
document.getElementById('header').style.display = 'none';
document.getElementById('footer').style.display = 'none';
document.body.innerHTML = printContents;

window.print();

document.body.innerHTML = originalContents;
}
</script>
</code>```

The content div to be visible to print would be named below

```<code><div id="divName">Print Content</div>
</code>```

Then on the print button, you do the below

```<code><button onClick="printDiv();">Print</button>
</code>```

Body:
I am using window.print() for printing page, but I got header and footer contains page title, file path, page number, and date. How to remove them or edit?

I tried this also.

@media print {
  @page { margin: 0; }
  body { margin: 1.6cm; }
}

i try all solution of this page
but any solution is not working for me.

this is my div content that is find from POJO.

<%= student.getDescription()%>

this is my button.

<button onclick="printDiv('textDiv')">Print PDF</button>

this is my Script for Print.

function printDiv(divName) {
 var printContents = document.getElementById(divName).innerHTML;
 var originalContents = document.body.innerHTML;
 document.body.innerHTML = printContents;
 window.print();
 document.body.innerHTML = originalContents;
}

// Use this method

@media print {
    .footer,
    #non-printable {
        display: none !important;
    }
    #printable {
        display: block;
    }
}

Body:
Try this below

<script language="javascript">
function printDiv() {
var printContents = document.getElementById("divName").innerHTML;
var originalContents = document.body.innerHTML;
document.getElementById('header').style.display = 'none';
document.getElementById('footer').style.display = 'none';
document.body.innerHTML = printContents;

window.print();

document.body.innerHTML = originalContents;
}
</script>

The content div to be visible to print would be named below

<div id="divName">Print Content</div>

Then on the print button, you do the below

<button onClick="printDiv();">Print</button>


问:
What's means SPI on Spring-Cache CacheManager

package org.springframework.cache;

/**
 * Spring's central cache manager SPI.
 * Allows for retrieving named {@link Cache} regions.
 *
 * @author Costin Leau
 * @since 3.1
 */
public interface CacheManager { ... }
```

what is means by SPI?

is that "https://en.wikipedia.org/wiki/Serial_Peripheral_Interface"?

答:
SPI =: Service Provider Interface

from wikipedia:

Service Provider Interface (SPI) is an API intended to be implemented
  or extended by a third party. It can be used to enable framework
  extension and replaceable components.

Body:
package org.springframework.cache;

/**
 * Spring's central cache manager SPI.
 * Allows for retrieving named {@link Cache} regions.
 *
 * @author Costin Leau
 * @since 3.1
 */
public interface CacheManager { ... }

what is means by SPI?

is that "https://en.wikipedia.org/wiki/Serial_Peripheral_Interface"?


问:
Ruby, Rails - how to check if a var is an Email
Does Rails 3 or Ruby have a built in way to return true or false on if a var is an EMAIL ADDRESS?

example

```<code>1 returns false
dadadad@asdasd.net returns true
blah+asdasds@asdasd.net returns true
asdasdasdads returns false
</code>```

Maybe something like, if 1.is_a? Email end

thanks

答:
Use https://github.com/OpenGems/rails_email_checker

ActiveModel email validation. Checks MX records, sub address, regex, whitelisted and blacklisted check

ContentLicense: CC BY-SA 2.5

Body:
Does Rails 3 or Ruby have a built in way to return true or false on if a var is an EMAIL ADDRESS?

example

1 returns false
dadadad@asdasd.net returns true
blah+asdasds@asdasd.net returns true
asdasdasdads returns false

Maybe something like, if 1.is_a? Email end

thanks


问:
How to automatically scale down a 100% div without showing browser vertical scrollbars?
I have a table with three rows. I have 1 main #container div (height 100%) and inside it is a table with 3 rows. The first and last row have fixed size content. In the second row is a #content div with 100% height and overflow:auto. (actually the table has a lot more rows and the page has more divs, but for the sake of clarity i scalled it down for this question).

If there is more content in #content than fits, a vertical scrollbar should appear next to that div's content. However, a vertical scrollbar appears at the browser window itself. When i set the #content div to a fixed size however, that vertical scrollbar does appear in the correct place.

I must be doing something wrong, or maybe misinterpreting something :) Any ideas? Maybe there's jquery/javascript out there that can monitor the page and when loading/resizing the browser, scales down that particular div?

EDIT: I just created a small example: http://wierdaonline.com/softest.html

In the ideal situation, the whole thing (table) should always be visible in the browser window, without any window scrollbar other than in the #content div.

答:
Edit: these changes should work for the height, a similar thing can be done with the width if you so desire.

javascript:

```<code>window.onresize = function() {
    var tehdiv = document.getElementById('content2');
    if($(window).height() < 100) { tehdiv.height = 50; }
    else if($(window).height() > 2000) { tehdiv.height = '100%'; }
    else { tehdiv.height = ($(window).height()/2);}
};
</code>```

the content div's table:

```<code><td valign='top' id='content2'>
</code>```

Would something like this work?

```<code>window.onresize = function() {
    var minh = 50;
    var minw = 50;
    var tehh = (window.height/2);
    var tehw = (window.width/2);
    var tehdiv = document.getElementById('yourdiv');
    tehdiv.height = (tehh > minh)? tehh : minh;
    tehdiv.width = (tehw > minw)? tehw : minw;
};
</code>```

That would make it scale to half the window size, as long as it can be bigger whan 50. You could also change the min to max and make it perform tehdiv.height = 100% at that point.

ContentLicense: CC BY-SA 3.0

Body:
Edit: these changes should work for the height, a similar thing can be done with the width if you so desire.

javascript:

window.onresize = function() {
    var tehdiv = document.getElementById('content2');
    if($(window).height() < 100) { tehdiv.height = 50; }
    else if($(window).height() > 2000) { tehdiv.height = '100%'; }
    else { tehdiv.height = ($(window).height()/2);}
};

the content div's table:

<td valign='top' id='content2'>

Would something like this work?

window.onresize = function() {
    var minh = 50;
    var minw = 50;
    var tehh = (window.height/2);
    var tehw = (window.width/2);
    var tehdiv = document.getElementById('yourdiv');
    tehdiv.height = (tehh > minh)? tehh : minh;
    tehdiv.width = (tehw > minw)? tehw : minw;
};

That would make it scale to half the window size, as long as it can be bigger whan 50. You could also change the min to max and make it perform tehdiv.height = 100% at that point.


问:
TypeError: unsupported operand type(s) for /: 'float' and 'Dimension', please use // instead
I'm getting the following error when I try to call the RA_unit_v4_1 method internally from the UNet model. I converted all the dimension values using the method x.shape[y].value but it doesn't help. Both the shapes of x and conv_n are the same. How to resolve this issue or what causes this to occur?

Error

```<code>TypeError: unsupported operand type(s) for /: 'float' and 'Dimension', please use // instead
</code>```

RA_unit_v4_1

```<code>def RA_unit_v4_1(x, h, w, n):
    x_1_n = MaxPooling2D(pool_size=(int(h/n), 2), strides=(int(h/n),2), padding='same', data_format='channels_last')(x)
    x_t_n = K.zeros([1, h, w, 0], K.floatx())

    for k in range(n):
        x_t_1_n =K.slice(x_1_n, [0,k,0,0], [1,1,int(w/2),x.shape[3].value])
        x_t_2_n = K.resize_images(x_t_1_n, int(h//x_t_1_n.shape[1].value), int(w//x_t_1_n.shape[2].value), data_format='channels_last',interpolation='nearest')
        x_t_3_n = K.abs(x - x_t_2_n)
        x_t_n = concatenate([x_t_n, x_t_3_n], axis=3)

    x_out_n = concatenate([x, x_t_n], axis=3)
    conv_n = Conv2D(x.shape[3], 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(x_out_n)

    return conv_n
</code>```

Unet Model

```<code>def unet(pretrained_weights = None,input_size = None):
    inputs = Input(batch_shape=input_size)

    conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs)
    conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1)

    pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)

    RA_1 = RA_unit_v4_1(x=pool1,h=pool1.shape[1].value, w=pool1.shape[2].value,n=16)

    conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(RA_1)
    conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv2)
    pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)

    conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool2)
    conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv3)
    pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)

    conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool3)
    conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv4)
    drop4 = Dropout(0.5)(conv4)
    pool4 = MaxPooling2D(pool_size=(2, 2))(drop4)

    conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool4)
    conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv5)
    drop5 = Dropout(0.5)(conv5)

    up6 = Conv2D(512, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(drop5))
    merge6 = concatenate([drop4,up6], axis = 3)

    conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge6)
    conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv6)

    up7 = Conv2D(256, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv6))
    merge7 = concatenate([conv3,up7], axis = 3)

    conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge7)
    conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv7)

    up8 = Conv2D(128, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv7))
    merge8 = concatenate([conv2,up8], axis = 3)

    conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge8)
    conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv8)

    up9 = Conv2D(64, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv8))
    merge9 = concatenate([conv1,up9], axis = 3)

    conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge9)
    conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)
    conv9 = Conv2D(2, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)

    conv10 = Conv2D(3, 1, activation = 'sigmoid')(conv9)

    model = Model(input = inputs, output = conv10)

    model.compile(optimizer = Adam(lr = 1e-4), loss = 'binary_crossentropy', metrics = ['accuracy']) # original 1e-4 | 2e-4 = 0.00020

    model.summary()

    if(pretrained_weights):
        model.load_weights(pretrained_weights)

    return model
</code>```

答:
I resolved it. It's in line before the last line in method RA_unit_v4_1 ;

```<code>conv_n = Conv2D(x.shape[3], 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(x_out_n)
</code>```

by

```<code>conv_n = Conv2D(x.shape[3].value, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(x_out_n)
</code>```

That is x.shape[3] should be replaced by x.shape[3].value.

After resolving that the following error occurs. 'AttributeError: 'NoneType' object has no attribute '_inbound_nodes'' .To resolve this lambda functions should be used. Its as follows:

```<code>pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)

RA_1 = Lambda(lambda y: RA_unit_v4_1(x=y, h=y.shape[1].value, w=y.shape[2].value, n=16) )
RA_1_n = RA_1(pool1)

conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(RA_1_n)
</code>```

Body:
I'm getting the following error when I try to call the RA_unit_v4_1 method internally from the UNet model. I converted all the dimension values using the method x.shape[y].value but it doesn't help. Both the shapes of x and conv_n are the same. How to resolve this issue or what causes this to occur?

Error

TypeError: unsupported operand type(s) for /: 'float' and 'Dimension', please use // instead

RA_unit_v4_1

def RA_unit_v4_1(x, h, w, n):
    x_1_n = MaxPooling2D(pool_size=(int(h/n), 2), strides=(int(h/n),2), padding='same', data_format='channels_last')(x)
    x_t_n = K.zeros([1, h, w, 0], K.floatx())

    for k in range(n):
        x_t_1_n =K.slice(x_1_n, [0,k,0,0], [1,1,int(w/2),x.shape[3].value])
        x_t_2_n = K.resize_images(x_t_1_n, int(h//x_t_1_n.shape[1].value), int(w//x_t_1_n.shape[2].value), data_format='channels_last',interpolation='nearest')
        x_t_3_n = K.abs(x - x_t_2_n)
        x_t_n = concatenate([x_t_n, x_t_3_n], axis=3)

    x_out_n = concatenate([x, x_t_n], axis=3)
    conv_n = Conv2D(x.shape[3], 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(x_out_n)

    return conv_n

Unet Model

def unet(pretrained_weights = None,input_size = None):
    inputs = Input(batch_shape=input_size)

    conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs)
    conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1)

    pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)

    RA_1 = RA_unit_v4_1(x=pool1,h=pool1.shape[1].value, w=pool1.shape[2].value,n=16)

    conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(RA_1)
    conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv2)
    pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)

    conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool2)
    conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv3)
    pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)

    conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool3)
    conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv4)
    drop4 = Dropout(0.5)(conv4)
    pool4 = MaxPooling2D(pool_size=(2, 2))(drop4)

    conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool4)
    conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv5)
    drop5 = Dropout(0.5)(conv5)

    up6 = Conv2D(512, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(drop5))
    merge6 = concatenate([drop4,up6], axis = 3)

    conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge6)
    conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv6)

    up7 = Conv2D(256, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv6))
    merge7 = concatenate([conv3,up7], axis = 3)

    conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge7)
    conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv7)

    up8 = Conv2D(128, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv7))
    merge8 = concatenate([conv2,up8], axis = 3)

    conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge8)
    conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv8)

    up9 = Conv2D(64, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv8))
    merge9 = concatenate([conv1,up9], axis = 3)

    conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge9)
    conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)
    conv9 = Conv2D(2, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)

    conv10 = Conv2D(3, 1, activation = 'sigmoid')(conv9)

    model = Model(input = inputs, output = conv10)

    model.compile(optimizer = Adam(lr = 1e-4), loss = 'binary_crossentropy', metrics = ['accuracy']) # original 1e-4 | 2e-4 = 0.00020

    model.summary()

    if(pretrained_weights):
        model.load_weights(pretrained_weights)

    return model

Body:
I resolved it. It's in line before the last line in method RA_unit_v4_1 ;

conv_n = Conv2D(x.shape[3], 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(x_out_n)

by

conv_n = Conv2D(x.shape[3].value, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(x_out_n)

That is x.shape[3] should be replaced by x.shape[3].value.

After resolving that the following error occurs. 'AttributeError: 'NoneType' object has no attribute '_inbound_nodes'' .To resolve this lambda functions should be used. Its as follows:

pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)

RA_1 = Lambda(lambda y: RA_unit_v4_1(x=y, h=y.shape[1].value, w=y.shape[2].value, n=16) )
RA_1_n = RA_1(pool1)

conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(RA_1_n)


问:
get specific value in each group and add it as new column in each group
I want to have something like this:

dataframe:

```<code> col1            col2             col3
A               'aa'            date1
A               'aa'            date2
A               'aa'            date3
A               'bb'            date4
B               'aa'            date5
B               'bb'            date6
B               'aa'            date7
</code>```

output:

```<code>  col1            col2             col3        col4
    A               'aa'            date1        date4
    A               'aa'            date2        date4
    A               'aa'            date3        date4
    A               'bb'            date4        date4
    B               'aa'            date5        date6
    B               'bb'            date6        date6
    B               'aa'            date7        date6

</code>```

I want to group by col1 and based on value in col2 get col3 and add a new column as col4 and set it as this value of col3

'aa' and 'bb' are examples so I can't use sort...I should compare it with a value.

答:
Try:

df=df.sort_values("col2", ascending=False).set_index("col1")

df["col4"]=df.groupby("col1")["col3"].first()

df=df.reset_index(drop=False)
```

<p>Outputs:</p>

<pre class="lang-py prettyprint-override"><code>  col1 col2   col3   col4
0    A   bb  date4  date4
1    B   bb  date6  date6
2    A   aa  date1  date4
3    A   aa  date2  date4
4    A   aa  date3  date4
5    B   aa  date5  date6
6    B   aa  date7  date6
</code>```

Edit
IIUC - to get col4 the value from col3, grouped by col1 for where col2=="bb"

Try:

df=df.set_index("col1")

df["col4"]=df.loc[df["col2"]=="bb"].groupby("col1")["col3"].first()

df=df.reset_index(drop=False)
```

Body:
I want to have something like this:

dataframe:

 col1            col2             col3
A               'aa'            date1
A               'aa'            date2
A               'aa'            date3
A               'bb'            date4
B               'aa'            date5
B               'bb'            date6
B               'aa'            date7

output:

  col1            col2             col3        col4
    A               'aa'            date1        date4
    A               'aa'            date2        date4
    A               'aa'            date3        date4
    A               'bb'            date4        date4
    B               'aa'            date5        date6
    B               'bb'            date6        date6
    B               'aa'            date7        date6

I want to group by col1 and based on value in col2 get col3 and add a new column as col4 and set it as this value of col3

'aa' and 'bb' are examples so I can't use sort...I should compare it with a value.

Body:
Try:

df=df.sort_values("col2", ascending=False).set_index("col1")

df["col4"]=df.groupby("col1")["col3"].first()

df=df.reset_index(drop=False)

Outputs:

  col1 col2   col3   col4
0    A   bb  date4  date4
1    B   bb  date6  date6
2    A   aa  date1  date4
3    A   aa  date2  date4
4    A   aa  date3  date4
5    B   aa  date5  date6
6    B   aa  date7  date6

Edit
IIUC - to get col4 the value from col3, grouped by col1 for where col2=="bb"

Try:

df=df.set_index("col1")

df["col4"]=df.loc[df["col2"]=="bb"].groupby("col1")["col3"].first()

df=df.reset_index(drop=False)


问:
make the first tab the active tab when open a bootstrap modal
i have a button that will show a bootstrap modal when clicks on it
the modal contains sidebar tabs.

my problem is when i close the modal and open it again by clicking on the button it will open with the last activated tab
i want the activated tab to be the first tab once i close the modal and open the modal again without reloading the page.

my html

```<code> // the button that will open the bootstrap modal
            <div>
            <a href="#"  class="popupLink" data-toggle="modal" data-target="#yDetailsModal">
            </a>
            </div>

// bootstrap modal

<div class="modal" id="MyDetailsModal" tabindex="-1" role="dialog" arialabelledby="myDetailsModal" aria-hidden="true" >

 <div class="modal-dialog modal-details" role="document">

  <div class="modal-content modal-details">

   <div class="modal-header">

 <button type="button" class="close close-button"  data-dismiss="modal" aria-label="Close" id="btnId"> </button>

  </div>

 <div class="modal-body">
  <div class=" tabs-left" id= "modal-tabs">
   <ul class="nav nav-tabs">

   <li class="active">
   <a href="#personal"  data-toggle="tab"></a></li>

  <li>
   <a  href="#promotion" data-toggle="tab"> </a> </li>
    <li>
    <a  href="#vacation" data-toggle="tab"> </a> </li>

</ul>
 </div>

<div class="tab-content" id="tab-content">
 <div class="tab-pane active" id="personalInformation">
  <div>
   <ul>
     <li>

      <span> this is a personal information</span>
      </li>
</ul>
</div>
</div>

</code>```

答:
Give it a try. (Run in a snippet to test)

<!DOCTYPE html>

    <title>Bootstrap Modal Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

    <button type="button" onclick="openModal();" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

                <button type="button" class="close close-button" data-dismiss="modal" aria-label="Close" id="btnId"></button>

One

Two

Three

Menu 1

Some content in menu 1.

Menu 2

Some content in menu 2.

Menu 2

Some content in menu 3.

```

Body:
i have a button that will show a bootstrap modal when clicks on it
the modal contains sidebar tabs.

my problem is when i close the modal and open it again by clicking on the button it will open with the last activated tab
i want the activated tab to be the first tab once i close the modal and open the modal again without reloading the page.

my html

 // the button that will open the bootstrap modal

// bootstrap modal

 <button type="button" class="close close-button"  data-dismiss="modal" aria-label="Close" id="btnId"> </button>

       this is a personal information

Body:
Give it a try. (Run in a snippet to test)

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Bootstrap Modal Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div>
    <button type="button" onclick="openModal();" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
</div>
<div class="modal" id="myModal" tabindex="-1" role="dialog" arialabelledby="myModal" aria-hidden="true">
    <div class="modal-dialog modal-details" role="document">
        <div class="modal-content modal-details">
            <div class="modal-header">
                <button type="button" class="close close-button" data-dismiss="modal" aria-label="Close" id="btnId"></button>
            </div>
            <div class="modal-body">
                <div class=" tabs-left" id="modal-tabs">
                    <ul class="nav nav-tabs">
                        <li class="active"><a href="#one" data-toggle="tab">One</a></li>
                        <li><a href="#two" data-toggle="tab">Two</a></li>
                        <li><a href="#three" data-toggle="tab">Three</a></li>
                    </ul>
                    <div class="tab-content">
                        <div id="one" class="tab-pane fade in active">
                            <h3>Menu 1</h3>
                            <p>Some content in menu 1.</p>
                        </div>
                        <div id="two" class="tab-pane fade">
                            <h3>Menu 2</h3>
                            <p>Some content in menu 2.</p>
                        </div>
                        <div id="three" class="tab-pane fade">
                            <h3>Menu 2</h3>
                            <p>Some content in menu 3.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script type="text/javascript">
    function openModal() {
        $("#myModal li").first().children()[0].click();
    }
</script>
</html>


问:
How to change facet labels?
I have used the following ggplot command:

```<code>ggplot(survey, aes(x = age)) + stat_bin(aes(n = nrow(h3), y = ..count.. / n), binwidth = 10)
  + scale_y_continuous(formatter = "percent", breaks = c(0, 0.1, 0.2))
  + facet_grid(hospital ~ .)
  + theme(panel.background = theme_blank())
</code>```

to produce

I'd like to change the facet labels, however, to something shorter (like Hosp 1, Hosp 2...) because they are too long now and look cramped (increasing the height of the graph is not an option, it would take too much space in the document). I looked at the facet_grid help page but cannot figure out how.

答:
After struggling for a while, what I found is that we can use fct_relevel() and fct_recode() from forcats in conjunction to change the order of the facets as well fix the facet labels. I am not sure if it's supported by design, but it works! Check out the plots below:

library(tidyverse)

before <- mpg %>%
  ggplot(aes(displ, hwy)) +
  geom_point() +
  facet_wrap(~class)
before
```

<p><img src="https://i.imgur.com/AEB5g9p.png" alt=""></p>

<pre class="lang-r prettyprint-override"><code>after <- mpg %>%
  ggplot(aes(displ, hwy)) +
  geom_point() +
  facet_wrap(
    vars(
      # Change factor level name
      fct_recode(class, "motorbike" = "2seater") %>%
        # Change factor level order
        fct_relevel("compact")
    )
  )
after
</code>```

Created on 2020-02-16 by the reprex package (v0.3.0)

Title: How to change facet labels?

Body:
I have used the following ggplot command:

ggplot(survey, aes(x = age)) + stat_bin(aes(n = nrow(h3), y = ..count.. / n), binwidth = 10)
  + scale_y_continuous(formatter = "percent", breaks = c(0, 0.1, 0.2))
  + facet_grid(hospital ~ .)
  + theme(panel.background = theme_blank())

to produce

I'd like to change the facet labels, however, to something shorter (like Hosp 1, Hosp 2...) because they are too long now and look cramped (increasing the height of the graph is not an option, it would take too much space in the document). I looked at the facet_grid help page but cannot figure out how.

Body:
After struggling for a while, what I found is that we can use fct_relevel() and fct_recode() from forcats in conjunction to change the order of the facets as well fix the facet labels. I am not sure if it's supported by design, but it works! Check out the plots below:

library(tidyverse)

before <- mpg %>%
  ggplot(aes(displ, hwy)) +
  geom_point() +
  facet_wrap(~class)
before

after <- mpg %>%
  ggplot(aes(displ, hwy)) +
  geom_point() +
  facet_wrap(
    vars(
      # Change factor level name
      fct_recode(class, "motorbike" = "2seater") %>%
        # Change factor level order
        fct_relevel("compact")
    )
  )
after

Created on 2020-02-16 by the reprex package (v0.3.0)


问:
Laravel, how to categorize (group) Eloquent result?
So I have a table that looks like this:

```<code>Name    Class    Remarks
Test1   C1       passed
Test2   C1       failed
Test3   C1       passed
Test4   C2       passed
</code>```

And what I'm trying to output is :

```<code>Class   Name   Remarks
C1      Test1  passed
        Test2  failed
        Test3  passed
C2      Test4  passed
</code>```

I am trying to load it by grouping first the class then loop through the collection. I'm not sure if that was the best solution. I'm thinking there might be a much reliable approach to this kind of requirement.

答:
Eloquent result is a collection, you can just use collection groupBy:

$result->groupBy('Class');
```

Body:
So I have a table that looks like this:

Name    Class    Remarks
Test1   C1       passed
Test2   C1       failed
Test3   C1       passed
Test4   C2       passed

And what I'm trying to output is :

Class   Name   Remarks
C1      Test1  passed
        Test2  failed
        Test3  passed
C2      Test4  passed

I am trying to load it by grouping first the class then loop through the collection. I'm not sure if that was the best solution. I'm thinking there might be a much reliable approach to this kind of requirement.


问:
Finding the maximum and minimum sum of all but 1 integer(s) in a given array
Today I'm here with another problem to solve.

It's one from the HackerRank assignments, https://www.hackerrank.com/challenges/mini-max-sum/problem
So, the general idea is to find the minimum-sum and maximum-sum of 4/5 integers from a given array;

In order to crack this, I came up with using a sorting algorithm to first sort the array in ascending order, post which I shall add all integers except the last one to find the Minimum-Sum and adding all integers except the first one to find the Maximum-Sum.

```<code>void miniMaxSum(int arr_count, int* arr) {

    int i,j,min,temp;
    for(i=0;i<arr_count-1;i++)
    {
        min=i;
        for(j=i+1;j<arr_count;j++)
        {
            if(arr[j]<arr[min])
                min=j;
        }
        temp=arr[i];
        arr[i]=arr[min];
        arr[min]=temp;
    }

    int minsum=0,maxsum=0;
    for(i=0;i<arr_count-1;i++)
        minsum+=arr[i];
    for(i=1;i<arr_count;i++)
        maxsum+=arr[i];

    printf("%d %d",minsum,maxsum);
}
</code>```

The following code works for a few test cases but doesn't work for them all. Any help would be sincerely appreciated.

答:
You do not need to sort the array in order to get the results.
What you need is simply know what is the maximum and minimum value of the array.
Just use a single loop.

```<code>void miniMaxSum(int arr_count, int* arr) {
    int i,min, max;
    min = max = arr[0];
    for(i=1;i<arr_count;i++)
    {
        if(min > arr[i]) min = arr[i];
        else if(max < arr[i]) max = arr[i];
    }

    int sum = 0;
    for(i=0;i<arr_count;i++)
        sum+=arr[i];

    printf("%d %d",sum-max,sum-min);
}
</code>```

HTH

Body:
Today I'm here with another problem to solve.

It's one from the HackerRank assignments, https://www.hackerrank.com/challenges/mini-max-sum/problem
So, the general idea is to find the minimum-sum and maximum-sum of 4/5 integers from a given array;

In order to crack this, I came up with using a sorting algorithm to first sort the array in ascending order, post which I shall add all integers except the last one to find the Minimum-Sum and adding all integers except the first one to find the Maximum-Sum.

void miniMaxSum(int arr_count, int* arr) {

    int i,j,min,temp;
    for(i=0;i<arr_count-1;i++)
    {
        min=i;
        for(j=i+1;j<arr_count;j++)
        {
            if(arr[j]<arr[min])
                min=j;
        }
        temp=arr[i];
        arr[i]=arr[min];
        arr[min]=temp;
    }

    int minsum=0,maxsum=0;
    for(i=0;i<arr_count-1;i++)
        minsum+=arr[i];
    for(i=1;i<arr_count;i++)
        maxsum+=arr[i];

    printf("%d %d",minsum,maxsum);
}

The following code works for a few test cases but doesn't work for them all. Any help would be sincerely appreciated.

Body:
You do not need to sort the array in order to get the results.
What you need is simply know what is the maximum and minimum value of the array.
Just use a single loop.

void miniMaxSum(int arr_count, int* arr) {
    int i,min, max;
    min = max = arr[0];
    for(i=1;i<arr_count;i++)
    {
        if(min > arr[i]) min = arr[i];
        else if(max < arr[i]) max = arr[i];
    }

    int sum = 0;
    for(i=0;i<arr_count;i++)
        sum+=arr[i];

    printf("%d %d",sum-max,sum-min);
}

HTH


问:
Why is R reading only the first nine files
I'm reading multiple .xls from a folder "test_dir" with this code

```<code>library(readxl)
files <- list.files(path = "./test_dir", pattern = "*.xls", full.names = T)
tbl <- sapply(files, read_excel, simplify=FALSE, skip=7) %>%
bind_rows(.id = "id")
</code>```

each time, only the first 9 dataset are read into r i.e Book1-Book9, do anyone know the reason why ?
see the structure of my folder in the image below
Sample Data

答:
There's a lot of comments here. I'll try to synthesize them into one clear answer. The original poster (OP) is trying into read multiple Excel workbooks into R using the read_excel function from the excellent R package called readxl. OP says only the first 9 workbooks could be imported. After providing the files via DropBox, r2evans could only import workbooks 1, 9 and 10 while I could only import workbooks 1 and 9. On further interrogation, OP said that the files were "generated from a software".

I am quite certain that therein lies the problem. The Excel files were generated by software, presumably not by Excel. The OP didn't say what software generated the files. The fact that they said "software", and not Excel, would imply that Excel did not create the files.

I also believe that workbooks 1 and 9 were opened by the OP and then saved and then zipped along with the others. In fact, saving the files after opening them in Excel is not really necessary as Excel does a silent save for you even if the file is closed without saving. In any case, opening the file and then closing it (with or without saving) causes the file to be magically "importable" into R using readxl. I don't know why, but can only assume that allowing software (presumably not Excel) to create an Excel file is the cause of the problem. Note, there is no error nor is there any warning. The data is just empty (no rows, see below for an attempt to import "Book11.xls"). I don't have any answer except to open each file one by one and then close them (with or without saving).

```<code>> Book11 <- read_excel("E:/SO/Book11.xls", skip=7)
> Book11
# A tibble: 0 x 0
</code>```

Edit: Note that "Book11.xls" does actually contain data. The read_excel function successfully reads the file (no error), but unsuccessfully imports the data (again, no error). That is strange to me. All other files, except Book1.xls and Book9.xls give the same results. That is, an empty tibble. All files are not empty. They contain many rows and columns. See below...

"Book1.xls" was probably opened by the OP (or someone else) and is able to be imported:

```<code>> Book1 <- read_excel("E:/SO/Book1.xls", skip=7)
> Book1
# A tibble: 1,524 x 35
   Position `Position [µm]` `Al-K` `Si-K` `S-KA` `K-KA` `Ca-KA` `Ti-KA`
      <dbl>           <dbl>  <dbl>  <dbl>  <dbl>  <dbl>   <dbl>   <dbl>
 1        0             0     3     11.3   1179       0   3076.   3.67
 2        1            14.5   6.33  10.3   1230.      0   3030.   2.67
 3        2            29.0   1.33  15.3   1160.      0   3080.   3.33
 4        3            43.4   1     11.3   1232.      0   3112.   0.667
 5        4            57.9   3.67   8.67  1227.      0   3116.   1.67
 6        5            72.4   5.33   8.67  1313       0   3153    6
 7        6            86.9   5.67  16     1181.      0   3100.   0.333
 8        7           101.    2     15     1218       0   3130.   1.33
 9        8           116.    2.33  11.3   1207.      0   3078.   1.33
10        9           130.    3     15.3   1249       0   3089.   7
# ... with 1,514 more rows, and 27 more variables: `Mn-KA` <dbl>,
#   `Fe-KA` <dbl>, `Mg-K` <dbl>, `Na-KA` <dbl>, `Cr-KA` <dbl>,
#   `Co-KA` <dbl>, `Ni-KA` <dbl>, `Cu-KA` <dbl>, `Zn-KA` <dbl>,
#   `As-KA` <dbl>, `P-KA` <dbl>, `Sr-KA` <dbl>, `Zr-KA` <dbl>,
#   `Mo-KA` <dbl>, `Rb-KA` <dbl>, `Br-KA` <dbl>, `Y-KA` <dbl>,
#   `Cl-KA` <dbl>, `Ga-KA` <dbl>, `Cd-KA` <dbl>, `V-KA` <dbl>,
#   `Cs-KA` <dbl>, `Ba-KA` <dbl>, `Hf-LA` <dbl>, `Pb-LA` <dbl>,
#   `U-LA` <dbl>, `Th-LA` <dbl>
</code>```

I also tried using the XLConnect package and the results were the same. (Edit: I tell a lie. The results are not the same. This package gives an error while trying to import the file. Unlike the readxl package, which gives NO ERROR but fails to import the data.)

```<code>library(XLConnect)
> wb <- loadWorkbook("E:/SO/Book11.xls")
Error: LeftoverDataException (Java): Initialisation of record 0x92(PaletteRecord) left 2 bytes remaining still to be read.

> wb <- loadWorkbook("E:/SO/Book1.xls") # No error
</code>```

So, whether this is a bug in those two packages is debatable. I'd say not. The fact that a warning message appears when you try to open the files in Excel suggests that it's more likely a problem with the software that generated the files.

Body:
I'm reading multiple .xls from a folder "test_dir" with this code

library(readxl)
files <- list.files(path = "./test_dir", pattern = "*.xls", full.names = T)
tbl <- sapply(files, read_excel, simplify=FALSE, skip=7) %>%
bind_rows(.id = "id")

each time, only the first 9 dataset are read into r i.e Book1-Book9, do anyone know the reason why ?
see the structure of my folder in the image below
Sample Data

Body:
There's a lot of comments here. I'll try to synthesize them into one clear answer. The original poster (OP) is trying into read multiple Excel workbooks into R using the read_excel function from the excellent R package called readxl. OP says only the first 9 workbooks could be imported. After providing the files via DropBox, r2evans could only import workbooks 1, 9 and 10 while I could only import workbooks 1 and 9. On further interrogation, OP said that the files were "generated from a software".

I am quite certain that therein lies the problem. The Excel files were generated by software, presumably not by Excel. The OP didn't say what software generated the files. The fact that they said "software", and not Excel, would imply that Excel did not create the files.

I also believe that workbooks 1 and 9 were opened by the OP and then saved and then zipped along with the others. In fact, saving the files after opening them in Excel is not really necessary as Excel does a silent save for you even if the file is closed without saving. In any case, opening the file and then closing it (with or without saving) causes the file to be magically "importable" into R using readxl. I don't know why, but can only assume that allowing software (presumably not Excel) to create an Excel file is the cause of the problem. Note, there is no error nor is there any warning. The data is just empty (no rows, see below for an attempt to import "Book11.xls"). I don't have any answer except to open each file one by one and then close them (with or without saving).

> Book11 <- read_excel("E:/SO/Book11.xls", skip=7)
> Book11
# A tibble: 0 x 0

Edit: Note that "Book11.xls" does actually contain data. The read_excel function successfully reads the file (no error), but unsuccessfully imports the data (again, no error). That is strange to me. All other files, except Book1.xls and Book9.xls give the same results. That is, an empty tibble. All files are not empty. They contain many rows and columns. See below...

"Book1.xls" was probably opened by the OP (or someone else) and is able to be imported:

> Book1 <- read_excel("E:/SO/Book1.xls", skip=7)
> Book1
# A tibble: 1,524 x 35
   Position `Position [µm]` `Al-K` `Si-K` `S-KA` `K-KA` `Ca-KA` `Ti-KA`
      <dbl>           <dbl>  <dbl>  <dbl>  <dbl>  <dbl>   <dbl>   <dbl>
 1        0             0     3     11.3   1179       0   3076.   3.67
 2        1            14.5   6.33  10.3   1230.      0   3030.   2.67
 3        2            29.0   1.33  15.3   1160.      0   3080.   3.33
 4        3            43.4   1     11.3   1232.      0   3112.   0.667
 5        4            57.9   3.67   8.67  1227.      0   3116.   1.67
 6        5            72.4   5.33   8.67  1313       0   3153    6
 7        6            86.9   5.67  16     1181.      0   3100.   0.333
 8        7           101.    2     15     1218       0   3130.   1.33
 9        8           116.    2.33  11.3   1207.      0   3078.   1.33
10        9           130.    3     15.3   1249       0   3089.   7
# ... with 1,514 more rows, and 27 more variables: `Mn-KA` <dbl>,
#   `Fe-KA` <dbl>, `Mg-K` <dbl>, `Na-KA` <dbl>, `Cr-KA` <dbl>,
#   `Co-KA` <dbl>, `Ni-KA` <dbl>, `Cu-KA` <dbl>, `Zn-KA` <dbl>,
#   `As-KA` <dbl>, `P-KA` <dbl>, `Sr-KA` <dbl>, `Zr-KA` <dbl>,
#   `Mo-KA` <dbl>, `Rb-KA` <dbl>, `Br-KA` <dbl>, `Y-KA` <dbl>,
#   `Cl-KA` <dbl>, `Ga-KA` <dbl>, `Cd-KA` <dbl>, `V-KA` <dbl>,
#   `Cs-KA` <dbl>, `Ba-KA` <dbl>, `Hf-LA` <dbl>, `Pb-LA` <dbl>,
#   `U-LA` <dbl>, `Th-LA` <dbl>

I also tried using the XLConnect package and the results were the same. (Edit: I tell a lie. The results are not the same. This package gives an error while trying to import the file. Unlike the readxl package, which gives NO ERROR but fails to import the data.)

library(XLConnect)
> wb <- loadWorkbook("E:/SO/Book11.xls")
Error: LeftoverDataException (Java): Initialisation of record 0x92(PaletteRecord) left 2 bytes remaining still to be read.

> wb <- loadWorkbook("E:/SO/Book1.xls") # No error

So, whether this is a bug in those two packages is debatable. I'd say not. The fact that a warning message appears when you try to open the files in Excel suggests that it's more likely a problem with the software that generated the files.


问:
How to validate email is real or fake in Rails?
I have a problem I need write validator in rails to checking an email is real or fake? I try to research but nothing. Can someone help me? Thanks !</p>

答:
Use https://github.com/OpenGems/rails_email_checker

Checks MX records, sub address, regex, whitelisted and blacklisted check


问:
Module 'tkinter' has no attribute 'Tk'
Tkinter doesnt contain any tk attribute.

```<code>import tkinter

window = tkinter.Tk()

win.mainloop()
</code>```

While running this code it gives me an error saying

```<code>module 'tkinter' has no attribute 'Tk'
</code>```

答:
 Python 3.x

```<code>import tkinter

window = tkinter.Tk()

window.mainloop()
</code>```

Title: Module 'tkinter' has no attribute 'Tk'

Body:
Tkinter doesnt contain any tk attribute.

import tkinter

window = tkinter.Tk()

win.mainloop()

While running this code it gives me an error saying

module 'tkinter' has no attribute 'Tk'

Body:
 Python 3.x

import tkinter

window = tkinter.Tk()

window.mainloop()


问:
How do I easily prohibit access to a Github repository's commit history?
When creating course programming assignments I often work in a Github repo.  These repos usually contain commits that have the solution to the assignment.  Since I don't want to make those commits available to the class is there a way to prohibit access to the commit history?  </p>

<p>Right now I end up having to create a brand new repo and copying the code in manually so there's no commit history. Or providing a zip of the repo.  But a zip is awkward because sometimes I want to make a change to the code in the assignment. There must be a better way!  (I'd be psyched for solutions that can be done through the Github GUI if possible.  But I'll settle for command line.) </p>

答:
Git alone doesn't offer your expectation out of the box. You can achieve this by a git workflow with any Git-repository manager Ex. GitHub and GitLab.

Step 1:
You need to have one private branch. Consider master branch for this example, Which is accessible to only the users who has specific privilege for this branch.

To add such restriction on any branch please refer this post How to restrict access to master branch on git

Step 2:
You need a public branch which is created from the specific commit (where you have committed only assignment not solution).
This branch will not have any history from this commit. (means no assignment solutions)

to create a branch from a particular commit refer this post Branch from a previous commit using Git

By following above workflow you would no longer needed to provide a zip of the repo while avoiding the previous assignment solutions visible from history of the new repo.

Ask your developers to create a new branch from public the branch. Everyone will have their own space.

To create a new branch from the newly created public branch refer this post Create a branch in Git from another branch

Body:
When creating course programming assignments I often work in a Github repo.  These repos usually contain commits that have the solution to the assignment.  Since I don't want to make those commits available to the class is there a way to prohibit access to the commit history?

Right now I end up having to create a brand new repo and copying the code in manually so there's no commit history. Or providing a zip of the repo.  But a zip is awkward because sometimes I want to make a change to the code in the assignment. There must be a better way!  (I'd be psyched for solutions that can be done through the Github GUI if possible.  But I'll settle for command line.)


问:
how to implement facebook like notification?
I am trying to implement a Facebook-like live notifications system to notify users whenever someone adds them as friend, like their post or posts replies to their comments.

All the database and PHP part is done, but I can't figure out how to implement it like Facebook has.

Whenever someone likes/comments on your post in Facebook the light blue box appears at the bottom left corner of the screen. This happens as soon as someone hits like button or posts comment in Facebook. I would like to know what I should do to implement this.

Using YUI or any JavaScript framework I can query a database table after n seconds to check for notifications. This method is too heavy.

I was wondering if there is any server side mod or scripting can be done so that whenever there is new notification entry in my database table the server will tell that particular client. That way unnecessary request calls from client to server will be avoided completely and system can work efficiently for website with more than 50,000 users online at a time.

How can I achieve this?

答: You basically set a request up, like callng the service that asks your server/db for the notifications of that user. You may do a while loop that retries if theres no notification (maybe Thread.Sleep in between searches). Your js request will timeout, then you can call the function again in timeout. This means long polling afaik


问:
Why do I get error in matrix when I try to web scrape a table?
This is a sample of my code. The problem lies with the 2nd link (for Cedar Realty Trust).

```<code>library(rvest)
library(stringr)
library(plyr)
library(dplyr)
library(lubridate)
library(readr)
library(stringi)
library(tidyverse)
library(purrr)

urls <- list(c("CEDAR FAIR L P ", "https://www.sec.gov/Archives/edgar/data/811532/000081153219000037/exhibit212018subsidiaries.htm"),
             c("CEDAR REALTY TRUST, INC.    ", "https://www.sec.gov/Archives/edgar/data/761648/000156459020004590/cdr-ex211_8.htm"),
             c("Celanese Corp ", "https://www.sec.gov/Archives/edgar/data/1306830/000130683020000018/ex211-10k123119.htm"))

List.Of.Tabs <- map(urls, ~ {

  name <- .x[1]
  link <- .x[2]
  Sys.sleep(2)
  webpage <- read_html(link)
  tbls <- html_nodes(webpage, "table")
  tbls_ls <- html_table(tbls, fill = TRUE)
  pos1 <- possibly(function(tbls) bind_rows(tbls) %>%
                     filter_all(any_vars(. %in% c("Singapore", "SGP"))) %>%
                     mutate(name = name)
                   , otherwise = NA)

  pos1(tbls_ls)
})
</code>```

The error message that I got:

```<code>Error in matrix(NA_character_, nrow = n, ncol = maxp) :
  invalid 'ncol' value (too large or NA)
In addition: Warning messages:
1: In max(p) : no non-missing arguments to max; returning -Inf
2: In matrix(NA_character_, nrow = n, ncol = maxp) :
  NAs introduced by coercion to integer range
</code>```

How can I amend my code to take care of this error?

答:
Here is way to do it with tryCatch.

```<code>library(tidyverse)
library(rvest)

map(urls, ~ {

  name <- .x[1]
  link <- .x[2]
  Sys.sleep(2)
  tryCatch({
     temp <- link %>%
               read_html() %>%
               html_nodes("table") %>%
               html_table(fill = TRUE)
      map_df(temp, ~filter_all(.x, any_vars(. %in% c("Singapore", "SGP")))) %>%
          mutate(name = name)
      }, error = function(e) NA
     )
})

#[[1]]
#[1] X1   X2   name
#<0 rows> (or 0-length row.names)

#[[2]]
#[1] NA

#[[3]]
#                                             X1 X2        X3 X4           name
#1                            Celanese PTE. LTD. NA Singapore NA Celanese Corp
#2  Celanese Singapore Acetyls Holding PTE. LTD. NA Singapore NA Celanese Corp
#3 Celanese Singapore Chemical Holding PTE. LTD. NA Singapore NA Celanese Corp
#4                  Celanese Singapore PTE. LTD. NA Singapore NA Celanese Corp
#5              Celanese Singapore VAM PTE. LTD. NA Singapore NA Celanese Corp
#6        Celanese Singapore Emulsions PTE. LTD. NA Singapore NA Celanese Corp
</code>```

Although this gives the warning but it runs without an error.

Body:
This is a sample of my code. The problem lies with the 2nd link (for Cedar Realty Trust).

library(rvest)
library(stringr)
library(plyr)
library(dplyr)
library(lubridate)
library(readr)
library(stringi)
library(tidyverse)
library(purrr)

urls <- list(c("CEDAR FAIR L P ", "https://www.sec.gov/Archives/edgar/data/811532/000081153219000037/exhibit212018subsidiaries.htm"),
             c("CEDAR REALTY TRUST, INC.    ", "https://www.sec.gov/Archives/edgar/data/761648/000156459020004590/cdr-ex211_8.htm"),
             c("Celanese Corp ", "https://www.sec.gov/Archives/edgar/data/1306830/000130683020000018/ex211-10k123119.htm"))

List.Of.Tabs <- map(urls, ~ {

  name <- .x[1]
  link <- .x[2]
  Sys.sleep(2)
  webpage <- read_html(link)
  tbls <- html_nodes(webpage, "table")
  tbls_ls <- html_table(tbls, fill = TRUE)
  pos1 <- possibly(function(tbls) bind_rows(tbls) %>%
                     filter_all(any_vars(. %in% c("Singapore", "SGP"))) %>%
                     mutate(name = name)
                   , otherwise = NA)

  pos1(tbls_ls)
})

The error message that I got:

Error in matrix(NA_character_, nrow = n, ncol = maxp) :
  invalid 'ncol' value (too large or NA)
In addition: Warning messages:
1: In max(p) : no non-missing arguments to max; returning -Inf
2: In matrix(NA_character_, nrow = n, ncol = maxp) :
  NAs introduced by coercion to integer range

How can I amend my code to take care of this error?

Body:
Here is way to do it with tryCatch.

library(tidyverse)
library(rvest)

map(urls, ~ {

  name <- .x[1]
  link <- .x[2]
  Sys.sleep(2)
  tryCatch({
     temp <- link %>%
               read_html() %>%
               html_nodes("table") %>%
               html_table(fill = TRUE)
      map_df(temp, ~filter_all(.x, any_vars(. %in% c("Singapore", "SGP")))) %>%
          mutate(name = name)
      }, error = function(e) NA
     )
})

#[[1]]
#[1] X1   X2   name
#<0 rows> (or 0-length row.names)

#[[2]]
#[1] NA

#[[3]]
#                                             X1 X2        X3 X4           name
#1                            Celanese PTE. LTD. NA Singapore NA Celanese Corp
#2  Celanese Singapore Acetyls Holding PTE. LTD. NA Singapore NA Celanese Corp
#3 Celanese Singapore Chemical Holding PTE. LTD. NA Singapore NA Celanese Corp
#4                  Celanese Singapore PTE. LTD. NA Singapore NA Celanese Corp
#5              Celanese Singapore VAM PTE. LTD. NA Singapore NA Celanese Corp
#6        Celanese Singapore Emulsions PTE. LTD. NA Singapore NA Celanese Corp

Although this gives the warning but it runs without an error.


问:
Parse multilingual json file into C# dictionary
How do I read into a C# dictionary, a multilingual json lexicon in the form:

```<code>[{
  "Top": {
    "de-DE": "Oben",
    "fr-FR": "haut"
  }
},    {
  "Football": {
    "de-DE": "Fußball",
  },
},
{
  "Taxi": {
  }
}]
</code>```

In the json file there is a key, and for each supported language, a property and value. Where the word in the target language is the same as the key, there is no property for that language under that key in the json file.

At startup we load into a C# dictionary only those entries for the user language. In this snippet, the dictionary for German should be

```<code>Top, Oben
Football, Fußball
Taxi, Taxi
</code>```

In French

```<code>Top, Haut
Football, Football,
Taxi, Taxi
</code>```

How do I read the json file into a C# dictionary? The dictionary is not huge ... hundreds rather than millions of entries, so performance is not critical.

答:
I assumed your JSON is List of Array

```<code>[
  {
    "Top": {
      "de-DE": "Oben",
      "fr-FR": "haut"
    }
  },
  {
    "Football": {
      "de-DE": "Fußball"
    }
  },
  {
    "Taxi": {
    }
  }
]
</code>```

You can use JsonConvert.DeserializeObject to convert the json to Dictionary

```<code>var results = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(json);

//DE Dictionary
var deDict = results.SelectMany(x => x).ToDictionary(x => x.Key, x => JObject.Parse(x.Value.ToString())["de-DE"] == null ? "" : JObject.Parse(x.Value.ToString())["de-DE"].ToString());

//FR Dictionary
var frDict = results.SelectMany(x => x).ToDictionary(x => x.Key, x => JObject.Parse(x.Value.ToString())["fr-FR"] == null ? "" : JObject.Parse(x.Value.ToString())["fr-FR"].ToString());

//DE Dictionary
foreach (var keyvalue in deDict)
{
    Console.WriteLine($"{keyvalue.Key} : {keyvalue.Value}");
}

//FR Dictionary
foreach (var keyvalue in frDict)
{
    Console.WriteLine($"{keyvalue.Key} : {keyvalue.Value}");
}
</code>```

OUTPUT

```<code>Top : Oben
Football : Fußball
Taxi :

Top : haut
Football :
Taxi :
</code>```

Body:
How do I read into a C# dictionary, a multilingual json lexicon in the form:

[{
  "Top": {
    "de-DE": "Oben",
    "fr-FR": "haut"
  }
},    {
  "Football": {
    "de-DE": "Fußball",
  },
},
{
  "Taxi": {
  }
}]

In the json file there is a key, and for each supported language, a property and value. Where the word in the target language is the same as the key, there is no property for that language under that key in the json file.

At startup we load into a C# dictionary only those entries for the user language. In this snippet, the dictionary for German should be

Top, Oben
Football, Fußball
Taxi, Taxi

In French

Top, Haut
Football, Football,
Taxi, Taxi

How do I read the json file into a C# dictionary? The dictionary is not huge ... hundreds rather than millions of entries, so performance is not critical.

Body:
I assumed your JSON is List of Array

[
  {
    "Top": {
      "de-DE": "Oben",
      "fr-FR": "haut"
    }
  },
  {
    "Football": {
      "de-DE": "Fußball"
    }
  },
  {
    "Taxi": {
    }
  }
]

You can use JsonConvert.DeserializeObject to convert the json to Dictionary

var results = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(json);

//DE Dictionary
var deDict = results.SelectMany(x => x).ToDictionary(x => x.Key, x => JObject.Parse(x.Value.ToString())["de-DE"] == null ? "" : JObject.Parse(x.Value.ToString())["de-DE"].ToString());

//FR Dictionary
var frDict = results.SelectMany(x => x).ToDictionary(x => x.Key, x => JObject.Parse(x.Value.ToString())["fr-FR"] == null ? "" : JObject.Parse(x.Value.ToString())["fr-FR"].ToString());

//DE Dictionary
foreach (var keyvalue in deDict)
{
    Console.WriteLine($"{keyvalue.Key} : {keyvalue.Value}");
}

//FR Dictionary
foreach (var keyvalue in frDict)
{
    Console.WriteLine($"{keyvalue.Key} : {keyvalue.Value}");
}

OUTPUT

Top : Oben
Football : Fußball
Taxi :

Top : haut
Football :
Taxi :


问:
Filter an array of repeated objects and get the sum of them
So I have the next information, what I want to achieve is filter the array of objects and sum the qty of the objects repeated

```<code>//Original Data
var data = {
    sublists = [
    { item: 1, qty: 2},
    { item: 2, qty: 2},
    { item: 3, qty: 2},
    { item: 1, qty: 5}
    { item: 3, qty: 3}
    ],
    ...
};
//This is what I want to achieve
var result = {
    sublists = [
    { item: 1, qty: 7},
    { item: 2, qty: 2},
    { item: 3, qty: 5}

    ],
    ...
};
</code>```

So far what I got is the items name that repeat and an object that has the data of this variables

```<code>var repeatedObjects = {
  1: [{ item: 1, qty: 2}, { item: 1, qty: 5}],
  3: [{ item: 3, qty: 2}, { item: 3, qty: 3}]
}
var repeatedItems = [1, 3];
</code>```

But Im stuck at reducing the object so I can get the original data, with just one of the repeated objects and the sum of all of them. Any ideas?

答:
Using reduce will simplify

const update = data =>
  Object.values(
    data.sublists.reduce((acc, curr) => {
      acc[curr.item] =
        curr.item in acc
          ? { ...acc[curr.item], qty: acc[curr.item].qty + curr.qty }
          : { ...curr };
      return acc;
    }, {})
  );

var data = {
  sublists: [
    { item: 1, qty: 2 },
    { item: 2, qty: 2 },
    { item: 3, qty: 2 },
    { item: 1, qty: 5 },
    { item: 3, qty: 3 }
  ]
};

const res = { sublists: update(data) };

console.log(res);```

Body:
So I have the next information, what I want to achieve is filter the array of objects and sum the qty of the objects repeated

//Original Data
var data = {
    sublists = [
    { item: 1, qty: 2},
    { item: 2, qty: 2},
    { item: 3, qty: 2},
    { item: 1, qty: 5}
    { item: 3, qty: 3}
    ],
    ...
};
//This is what I want to achieve
var result = {
    sublists = [
    { item: 1, qty: 7},
    { item: 2, qty: 2},
    { item: 3, qty: 5}

    ],
    ...
};

So far what I got is the items name that repeat and an object that has the data of this variables

var repeatedObjects = {
  1: [{ item: 1, qty: 2}, { item: 1, qty: 5}],
  3: [{ item: 3, qty: 2}, { item: 3, qty: 3}]
}
var repeatedItems = [1, 3];

But Im stuck at reducing the object so I can get the original data, with just one of the repeated objects and the sum of all of them. Any ideas?


问:
Javascript, jQuery, Do function after another function
I have this javascript function.

```<code><script type="text/javascript">
  $(document).ready(function () {
  $('#load').html('<img style="display:block; margin:10px auto;background-color: #EEE;" src="<?echo $site["url"];?>images/icons/loading.gif"/>');
  $('#loaded').fadeIn(1500);
     $('#load').fadeOut(2000);
  });
</script>
</code>```

As you may see it simply runs a loading image for a tot of seconds, then shows the div and hide the loading image.
This is not good for me. I need a function that will work in this way. The logic of the code would be:

```<code>As soon as $('#load').html('<img style="display:block; margin:10px auto;background-color: #EEE;" src="<?echo $site["url"];?>images/icons/loading.gif"/>'); is running, then wait 4 seconds, and then show the #loaded DIV.
</code>```

In this way the #loaded DIV will be fully loaded and it will work fine, since it is an heavy one.

In few words I must to be sure that #loaded has been fully loaded by the browser before showing it.
How can I create a function that will do that?

On document ready show the loading DIV. Then WAIT for 3-4 seconds, then make the loading disappear and the loaded DIV visible.

Is this possible?

答:
I am a little confused by all these answers and not sure what your question is or if I am right or they are right, but this is how to wait 4 seconds. (added 2 lines to your original code)</p>

```<code><script type="text/javascript">
  $(document).ready(function () {
    $('#load').html('<img style="display:block; margin:10px auto;background-color: #EEE;" src="<?echo $site["url"];?>images/icons/loading.gif"/>');
    setTimeout(function () {
      $('#loaded').fadeIn(1500);
      $('#load').fadeOut(2000);
    }, 4000)
  });
</script>
</code>```

Body:
I have this javascript function.

As you may see it simply runs a loading image for a tot of seconds, then shows the div and hide the loading image.
This is not good for me. I need a function that will work in this way. The logic of the code would be:

As soon as $('#load').html('<img style="display:block; margin:10px auto;background-color: #EEE;" src="<?echo $site["url"];?>images/icons/loading.gif"/>'); is running, then wait 4 seconds, and then show the #loaded DIV.

In this way the #loaded DIV will be fully loaded and it will work fine, since it is an heavy one.

In few words I must to be sure that #loaded has been fully loaded by the browser before showing it.
How can I create a function that will do that?

On document ready show the loading DIV. Then WAIT for 3-4 seconds, then make the loading disappear and the loaded DIV visible.

Is this possible?

Body:
I am a little confused by all these answers and not sure what your question is or if I am right or they are right, but this is how to wait 4 seconds. (added 2 lines to your original code)

<script type="text/javascript">
  $(document).ready(function () {
    $('#load').html('<img style="display:block; margin:10px auto;background-color: #EEE;" src="<?echo $site["url"];?>images/icons/loading.gif"/>');
    setTimeout(function () {
      $('#loaded').fadeIn(1500);
      $('#load').fadeOut(2000);
    }, 4000)
  });
</script>


问:
Snapshot will keep data against TTL expired or TTL expired table in cassandra
I have one scenario here where I am inserting data with TTL value 5 days so it should be deleted after 5 days once TTL value expired for that rows inserted.
I am taking regular snapshots of my Cassandra nodes daily so my questions are as below:-

1) Will snapshot contain my expired inserted data and useful for restore if required? or It will delete all inserted rows automatically after TTL expired?

2) Does compaction happen on sstables resides on snapshot folder?

Thanks in advance!

答:
A TTL guarantees that after the expiration date, reading the expired data will return nothing. The way this is achieved under the hood, with files on disk, is  that the old data remains on disk, in some old sstable, and when Scylla reads it it notices this data is already past its expiration date, and does not return it. Only later, when Scylla decides to compact the sstable containing the expired data, does it actually remove this old data from disk (and, sometimes, needs to replace it by a deletion marker, a tombstone - the details of this aren't relevant to your question).

So the answer to your questions:

The answer depends what you mean by "useful for restore". The snapshot contains verbatim copies of the existing sstables, and old snapshots before the expiration (or, as explained above, also for some duration after the expiration) will indeed contain the expired data as well. This snapshot can be "restored" to a live database, but even though the expired data is still there reading from it will not return it - since that's the requirement from an expiration date...

No. A snapshot stores verbatim copies of sstables which exist in the live database. Compaction happens only on the live database - the sstables in the snapshot aren't touched after being saved.

If I understand your goal correctly, you are looking for a way to "resurrect" already-expired data, by reading from old snapshot which contained this data before it was expired. As far as I know, neither Scylla nor Cassandra offer an official mechanism to do this.  One way you can achieve this is to restore the old snapshot to a new cluster with its clock set to a date before the expiration date. Then, when the old data is read, it will not be considered expired.


问:
Have someone install "IITB Simplecpp in mac"?
I am trying to install simplecpp from this website "https://www.cse.iitb.ac.in/~ranade/simplecpp/"
I am following the mac version.
but when I try to cp file "/usr/include/xlocale.h ./" it gives an error "cp: /usr/include/xlocale.h: No such file or directory"
Please, someone, install and tells me if I am doing wrong or there is an error with the commands given in the website.</p>

答: Run locate xlocale.h to find where that file exists on your machine, and copy it from one of those locations.  For example on some Macs it is in /Library/Developer/CommandLineTools/SDKs/usr/include/xlocale.h if you have XCode and its "Command Line Tools" installed.


问:
Need Clarity on the Implementation Part of the Diamond Problem
Answers for Why multiple inheritances are not possible?

If there is a method in A that B and C have overridden, and D does not override it, then which version of the method does D inherit: that of B, or that of C?

Okay. Fine

Why it does not apply to Interfaces?
Because it is not implemented.

This answer is confusing to me. I have seen many articles talking about why multiple inheritances with class are not possible and they never talk about the implementation. When we ask the same question about Interfaces, they don't go with the same logic and now they are saying the code is not implemented. Why don't we go with the same logic? Its implementation is the real problem here? Please address only this part.

答:
The diamond problem arises if B and C, which each supply conflicting definitions for an inherited method, are overridden by D.  The problem would not arise if B and C inherited methods without overriding them, and D supplied overrides for the method, since D's override would affect B and C identically.

If A, B, and C are interfaces, then neither B nor C will be able to supply definitions for the methods of A.  A class which implements both interfaces may do so, but any definition it supplies for the methods of A will apply equally to those of B and C.

Another important difference between interfaces and classes is that when overriding a class member, it's possible to chain to a parent method, but when implementing an interface there's never a parent method to chain to.


问:
How to sort a python list of lists by both the values of a nested list and with a condition of reverse=True for only first value of the nested list?
I am trying to sort this list by both the values of the nested list, but I want only alphabets positions in reverse order and the numbers in ascending order.

```<code>sample_list = [
  ['y', 4],
  ['x', 2],
  ['y', 1],
  ['z', 2],
  ['x', 5],
  ['y', 2]]

sorted_list = sorted(sample_list, key=lambda nested: (nested[0], nested[1]), reverse=True)
</code>```

Output:

```<code>[['z', 2],
 ['y', 4],
 ['y', 2],
 ['y', 1],
 ['x', 5],
 ['x', 2]]
</code>```

Expected Output:

```<code>[['z', 2],
 ['y', 1],
 ['y', 2],
 ['y', 4],
 ['x', 2],
 ['x', 5]]
</code>```

答:
You can use -nested[1] in your lambda function.

```<code>>>> sorted_list = sorted(sample_list, key=lambda nested: (nested[0],-nested[1]), reverse=True)
>>> print(*sorted_list,sep='\n')
['z', 2]
['y', 1]
['y', 2]
['y', 4]
['x', 2]
['x', 5]
</code>```

Body:
I am trying to sort this list by both the values of the nested list, but I want only alphabets positions in reverse order and the numbers in ascending order.

sample_list = [
  ['y', 4],
  ['x', 2],
  ['y', 1],
  ['z', 2],
  ['x', 5],
  ['y', 2]]

sorted_list = sorted(sample_list, key=lambda nested: (nested[0], nested[1]), reverse=True)

Output:

[['z', 2],
 ['y', 4],
 ['y', 2],
 ['y', 1],
 ['x', 5],
 ['x', 2]]

Expected Output:

[['z', 2],
 ['y', 1],
 ['y', 2],
 ['y', 4],
 ['x', 2],
 ['x', 5]]

Body:
You can use -nested[1] in your lambda function.

>>> sorted_list = sorted(sample_list, key=lambda nested: (nested[0],-nested[1]), reverse=True)
>>> print(*sorted_list,sep='\n')
['z', 2]
['y', 1]
['y', 2]
['y', 4]
['x', 2]
['x', 5]