问:
Spring Boot creating multiple (functioning) webmvc applications using auto configuration
Updated

My question is how do I initialise an isolated spring webmvc web-app in spring boot. The isolated Web application should:

Should not initialise itself in the application class. We want to do these in a starter pom via auto configuration. We have multiple such web-apps and we need the flexibility of auto configuration.

Have the ability to customise itself using interfaces like:
WebSecurityConfigurer (we have multiple web-apps, each does
security in its own way) and EmbeddedServletContainerCustomizer (to
set the context path of the servlet).

We need to isolate beans specific to certain web-apps and do not want them to enter the parent context.

Progress

The configuration class below is listed in my META-INF/spring.factories.

The following strategy does not lead to a functioning web-mvc servlet. The context path is not set and neither is the security customised. My hunch is that I need to include certain webmvc beans that process the context and auto configure based on what beans are present -- similar to how I got boot based property placeholder configuration working by including PropertySourcesPlaceholderConfigurer.class.

@Configuration
@AutoConfigureAfter(DaoServicesConfiguration.class)
public class MyServletConfiguration {
    @Autowired
    ApplicationContext parentApplicationContext;

    @Bean
    public ServletRegistrationBean myApi() {
        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.setParent(parentApplicationContext);
        applicationContext.register(PropertySourcesPlaceholderConfigurer.class);
        // a few more classes registered. These classes cannot be added to
        // the parent application context.
        // includes implementations of
        //   WebSecurityConfigurerAdapter
        //   EmbeddedServletContainerCustomizer

        applicationContext.scan(
                // a few packages
        );

        DispatcherServlet ds = new DispatcherServlet();
        ds.setApplicationContext(applicationContext);

        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(ds, true, "/my_api/*");
        servletRegistrationBean.setName("my_api");
        servletRegistrationBean.setLoadOnStartup(1);
        return servletRegistrationBean;
    }
}
```

答:
We had the similar issue using Boot (create a multi-servlets app with parent context) and we solved it in the following way:

1.Create your parent Spring config, which will consist all parent's beans which you want to share. Something like this:

```<code>@EnableAutoConfiguration(
    exclude = {
        //use this section if your want to exclude some autoconfigs (from Boot) for example MongoDB if you already have your own
    }
)
@Import(ParentConfig.class)//You can use here many clasess from you parent context
@PropertySource({"classpath:/properties/application.properties"})
@EnableDiscoveryClient
public class BootConfiguration {
}
</code>```

2.Create type which will determine the type of your specific app module (for example ou case is REST or SOAP). Also here you can specify your required context path or another app specific data (I will show bellow how it will be used):

```<code>public final class AppModule {

    private AppType type;

    private String name;

    private String contextPath;

    private String rootPath;

    private Class<?> configurationClass;

    public AppModule() {
    }

    public AppModule(AppType type, String name, String contextPath, Class<?> configurationClass) {
        this.type = type;
        this.name = name;
        this.contextPath = contextPath;
        this.configurationClass = configurationClass;
    }

    public AppType getType() {
        return type;
    }

    public void setType(AppType type) {
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRootPath() {
        return rootPath;
    }

    public AppModule withRootPath(String rootPath) {
        this.rootPath = rootPath;
        return this;
    }

    public String getContextPath() {
        return contextPath;
    }

    public void setContextPath(String contextPath) {
        this.contextPath = contextPath;
    }

    public Class<?> getConfigurationClass() {
        return configurationClass;
    }

    public void setConfigurationClass(Class<?> configurationClass) {
        this.configurationClass = configurationClass;
    }

    public enum AppType {
        REST,
        SOAP
    }
}
</code>```

3.Create Boot app initializer for your whole app:

```<code>public class BootAppContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    private List<AppModule> modules = new ArrayList<>();

    BootAppContextInitializer(List<AppModule> modules) {
        this.modules = modules;
    }

    @Override
    public void initialize(ConfigurableApplicationContext ctx) {

        for (ServletRegistrationBean bean : servletRegs(ctx)) {
            ctx.getBeanFactory()
               .registerSingleton(bean.getServletName() + "Bean", bean);
        }
    }

    private List<ServletRegistrationBean> servletRegs(ApplicationContext parentContext) {

        List<ServletRegistrationBean> beans = new ArrayList<>();

        for (AppModule module: modules) {

            ServletRegistrationBean regBean;

            switch (module.getType()) {
                case REST:
                    regBean = createRestServlet(parentContext, module);
                    break;
                case SOAP:
                    regBean = createSoapServlet(parentContext, module);
                    break;
                default:
                    throw new RuntimeException("Not supported AppType");
            }

            beans.add(regBean);
        }

        return beans;
    }

    private ServletRegistrationBean createRestServlet(ApplicationContext parentContext, AppModule module) {
        WebApplicationContext ctx = createChildContext(parentContext, module.getName(), module.getConfigurationClass());
        //Create and init MessageDispatcherServlet for REST
        //Also here you can init app specific data from AppModule, for example,
        //you  can specify context path in the follwing way
      //servletRegistrationBean.addUrlMappings(module.getContextPath() + module.getRootPath());
    }

    private ServletRegistrationBean createSoapServlet(ApplicationContext parentContext, AppModule module) {
        WebApplicationContext ctx = createChildContext(parentContext, module.getName(), module.getConfigurationClass());
        //Create and init MessageDispatcherServlet for SOAP
        //Also here you can init app specific data from AppModule, for example,
        //you  can specify context path in the follwing way
      //servletRegistrationBean.addUrlMappings(module.getContextPath() + module.getRootPath());
    }

 private WebApplicationContext createChildContext(ApplicationContext parentContext, String name,
                                                     Class<?> configuration) {
        AnnotationConfigEmbeddedWebApplicationContext ctx = new AnnotationConfigEmbeddedWebApplicationContext();
        ctx.setDisplayName(name + "Context");
        ctx.setParent(parentContext);
        ctx.register(configuration);

        Properties source = new Properties();
        source.setProperty("APP_SERVLET_NAME", name);
        PropertiesPropertySource ps = new PropertiesPropertySource("MC_ENV_PROPS", source);

        ctx.getEnvironment()
           .getPropertySources()
           .addLast(ps);

        return ctx;
    }
}
</code>```

4.Create abstract config classes which will contain child-specific beans and everything that you can not or don't want share via parent context. Here you can specify all required interfaces such as WebSecurityConfigurer or EmbeddedServletContainerCustomizer for your particular app module:

```<code>/*Example for REST app*/
@EnableWebMvc
@ComponentScan(basePackages = {
    "com.company.package1",
    "com.company.web.rest"})
@Import(SomeCommonButChildSpecificConfiguration.class)
public abstract class RestAppConfiguration extends WebMvcConfigurationSupport {

    //Some custom logic for your all REST apps

    @Autowired
    private LogRawRequestInterceptor logRawRequestInterceptor;

    @Autowired
    private LogInterceptor logInterceptor;

    @Autowired
    private ErrorRegister errorRegister;

    @Autowired
    private Sender sender;

    @PostConstruct
    public void setup() {
        errorRegister.setSender(sender);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(logRawRequestInterceptor);
        registry.addInterceptor(scopeInterceptor);
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        super.setServletContext(servletContext);
    }
}

/*Example for SOAP app*/
@EnableWs
@ComponentScan(basePackages = {"com.company.web.soap"})
@Import(SomeCommonButChildSpecificConfiguration.class)
public abstract class SoapAppConfiguration implements ApplicationContextAware {

    //Some custom logic for your all SOAP apps

    private boolean logGateWay = false;

    protected ApplicationContext applicationContext;

    @Autowired
    private Sender sender;

    @Autowired
    private ErrorRegister errorRegister;

    @Autowired
    protected WsActivityIdInterceptor activityIdInterceptor;

    @Autowired
    protected WsAuthenticationInterceptor authenticationInterceptor;

    @PostConstruct
    public void setup() {
        errorRegister.setSender(sender);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * Setup preconditions e.g. interceptor deactivation
     */
    protected void setupPrecondition() {
    }

    public boolean isLogGateWay() {
        return logGateWay;
    }

    public void setLogGateWay(boolean logGateWay) {
        this.logGateWay = logGateWay;
    }

    public abstract Wsdl11Definition defaultWsdl11Definition();
}
</code>```

5.Create entry point class which will compile whole our app:

```<code>public final class Entrypoint {

    public static void start(String applicationName, String[] args, AppModule... modules) {
        System.setProperty("spring.application.name", applicationName);
        build(new SpringApplicationBuilder(), modules).run(args);
    }

    private static SpringApplicationBuilder build(SpringApplicationBuilder builder, AppModule[] modules) {
        return builder
                .initializers(
                    new LoggingContextInitializer(),
                    new BootAppContextInitializer(Arrays.asList(modules))
                )
                .sources(BootConfiguration.class)
                .web(true)
                .bannerMode(Banner.Mode.OFF)
                .logStartupInfo(true);
    }
}
</code>```

Now everything is ready to rocket our super multi-app boot in two steps:

1.Init your child apps, for example, REST and SOAP:

```<code>//REST module
@ComponentScan(basePackages = {"com.module1.package.*"})
public class Module1Config extends RestAppConfiguration {
    //here you can specify all your child's Beans and etc
}

//SOAP module
@ComponentScan(
    basePackages = {"com.module2.package.*"})
public class Module2Configuration extends SoapAppConfiguration {

    @Override
    @Bean(name = "service")
    public Wsdl11Definition defaultWsdl11Definition() {
        ClassPathResource wsdlRes = new ClassPathResource("wsdl/Your_WSDL.wsdl");
        return new SimpleWsdl11Definition(wsdlRes);
    }

    @Override
    protected void setupPrecondition() {
        super.setupPrecondition();
        setLogGateWay(true);
        activityIdInterceptor.setEnabled(true);
    }
}
</code>```

2.Prepare entry point and run as Boot app:
public class App {

```<code>public static void main(String[] args) throws Exception {
    Entrypoint.start("module1",args,
                     new AppModule(AppModule.AppType.REST, "module1", "/module1/*", Module1Configuration.class),
                     new AppModule(AppModule.AppType.SOAP, "module2", "module2", Module2Configuration.class)
                    );
}
</code>```

}

enjoy ^_^

Useful links:

https://dzone.com/articles/what-servlet-container

Spring: Why "root" application context and "servlet" application context are created by different parties?

Role/Purpose of ContextLoaderListener in Spring?

Body:
We had the similar issue using Boot (create a multi-servlets app with parent context) and we solved it in the following way:

1.Create your parent Spring config, which will consist all parent's beans which you want to share. Something like this:

@EnableAutoConfiguration(
    exclude = {
        //use this section if your want to exclude some autoconfigs (from Boot) for example MongoDB if you already have your own
    }
)
@Import(ParentConfig.class)//You can use here many clasess from you parent context
@PropertySource({"classpath:/properties/application.properties"})
@EnableDiscoveryClient
public class BootConfiguration {
}

2.Create type which will determine the type of your specific app module (for example ou case is REST or SOAP). Also here you can specify your required context path or another app specific data (I will show bellow how it will be used):

public final class AppModule {

    private AppType type;

    private String name;

    private String contextPath;

    private String rootPath;

    private Class<?> configurationClass;

    public AppModule() {
    }

    public AppModule(AppType type, String name, String contextPath, Class<?> configurationClass) {
        this.type = type;
        this.name = name;
        this.contextPath = contextPath;
        this.configurationClass = configurationClass;
    }

    public AppType getType() {
        return type;
    }

    public void setType(AppType type) {
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRootPath() {
        return rootPath;
    }

    public AppModule withRootPath(String rootPath) {
        this.rootPath = rootPath;
        return this;
    }

    public String getContextPath() {
        return contextPath;
    }

    public void setContextPath(String contextPath) {
        this.contextPath = contextPath;
    }

    public Class<?> getConfigurationClass() {
        return configurationClass;
    }

    public void setConfigurationClass(Class<?> configurationClass) {
        this.configurationClass = configurationClass;
    }

    public enum AppType {
        REST,
        SOAP
    }
}

3.Create Boot app initializer for your whole app:

public class BootAppContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    private List<AppModule> modules = new ArrayList<>();

    BootAppContextInitializer(List<AppModule> modules) {
        this.modules = modules;
    }

    @Override
    public void initialize(ConfigurableApplicationContext ctx) {

        for (ServletRegistrationBean bean : servletRegs(ctx)) {
            ctx.getBeanFactory()
               .registerSingleton(bean.getServletName() + "Bean", bean);
        }
    }

    private List<ServletRegistrationBean> servletRegs(ApplicationContext parentContext) {

        List<ServletRegistrationBean> beans = new ArrayList<>();

        for (AppModule module: modules) {

            ServletRegistrationBean regBean;

            switch (module.getType()) {
                case REST:
                    regBean = createRestServlet(parentContext, module);
                    break;
                case SOAP:
                    regBean = createSoapServlet(parentContext, module);
                    break;
                default:
                    throw new RuntimeException("Not supported AppType");
            }

            beans.add(regBean);
        }

        return beans;
    }

    private ServletRegistrationBean createRestServlet(ApplicationContext parentContext, AppModule module) {
        WebApplicationContext ctx = createChildContext(parentContext, module.getName(), module.getConfigurationClass());
        //Create and init MessageDispatcherServlet for REST
        //Also here you can init app specific data from AppModule, for example,
        //you  can specify context path in the follwing way
      //servletRegistrationBean.addUrlMappings(module.getContextPath() + module.getRootPath());
    }

    private ServletRegistrationBean createSoapServlet(ApplicationContext parentContext, AppModule module) {
        WebApplicationContext ctx = createChildContext(parentContext, module.getName(), module.getConfigurationClass());
        //Create and init MessageDispatcherServlet for SOAP
        //Also here you can init app specific data from AppModule, for example,
        //you  can specify context path in the follwing way
      //servletRegistrationBean.addUrlMappings(module.getContextPath() + module.getRootPath());
    }

 private WebApplicationContext createChildContext(ApplicationContext parentContext, String name,
                                                     Class<?> configuration) {
        AnnotationConfigEmbeddedWebApplicationContext ctx = new AnnotationConfigEmbeddedWebApplicationContext();
        ctx.setDisplayName(name + "Context");
        ctx.setParent(parentContext);
        ctx.register(configuration);

        Properties source = new Properties();
        source.setProperty("APP_SERVLET_NAME", name);
        PropertiesPropertySource ps = new PropertiesPropertySource("MC_ENV_PROPS", source);

        ctx.getEnvironment()
           .getPropertySources()
           .addLast(ps);

        return ctx;
    }
}

4.Create abstract config classes which will contain child-specific beans and everything that you can not or don't want share via parent context. Here you can specify all required interfaces such as WebSecurityConfigurer or EmbeddedServletContainerCustomizer for your particular app module:

/*Example for REST app*/
@EnableWebMvc
@ComponentScan(basePackages = {
    "com.company.package1",
    "com.company.web.rest"})
@Import(SomeCommonButChildSpecificConfiguration.class)
public abstract class RestAppConfiguration extends WebMvcConfigurationSupport {

    //Some custom logic for your all REST apps

    @Autowired
    private LogRawRequestInterceptor logRawRequestInterceptor;

    @Autowired
    private LogInterceptor logInterceptor;

    @Autowired
    private ErrorRegister errorRegister;

    @Autowired
    private Sender sender;

    @PostConstruct
    public void setup() {
        errorRegister.setSender(sender);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(logRawRequestInterceptor);
        registry.addInterceptor(scopeInterceptor);
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        super.setServletContext(servletContext);
    }
}

/*Example for SOAP app*/
@EnableWs
@ComponentScan(basePackages = {"com.company.web.soap"})
@Import(SomeCommonButChildSpecificConfiguration.class)
public abstract class SoapAppConfiguration implements ApplicationContextAware {

    //Some custom logic for your all SOAP apps

    private boolean logGateWay = false;

    protected ApplicationContext applicationContext;

    @Autowired
    private Sender sender;

    @Autowired
    private ErrorRegister errorRegister;

    @Autowired
    protected WsActivityIdInterceptor activityIdInterceptor;

    @Autowired
    protected WsAuthenticationInterceptor authenticationInterceptor;

    @PostConstruct
    public void setup() {
        errorRegister.setSender(sender);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * Setup preconditions e.g. interceptor deactivation
     */
    protected void setupPrecondition() {
    }

    public boolean isLogGateWay() {
        return logGateWay;
    }

    public void setLogGateWay(boolean logGateWay) {
        this.logGateWay = logGateWay;
    }

    public abstract Wsdl11Definition defaultWsdl11Definition();
}

5.Create entry point class which will compile whole our app:

public final class Entrypoint {

    public static void start(String applicationName, String[] args, AppModule... modules) {
        System.setProperty("spring.application.name", applicationName);
        build(new SpringApplicationBuilder(), modules).run(args);
    }

    private static SpringApplicationBuilder build(SpringApplicationBuilder builder, AppModule[] modules) {
        return builder
                .initializers(
                    new LoggingContextInitializer(),
                    new BootAppContextInitializer(Arrays.asList(modules))
                )
                .sources(BootConfiguration.class)
                .web(true)
                .bannerMode(Banner.Mode.OFF)
                .logStartupInfo(true);
    }
}

Now everything is ready to rocket our super multi-app boot in two steps:

1.Init your child apps, for example, REST and SOAP:

//REST module
@ComponentScan(basePackages = {"com.module1.package.*"})
public class Module1Config extends RestAppConfiguration {
    //here you can specify all your child's Beans and etc
}

//SOAP module
@ComponentScan(
    basePackages = {"com.module2.package.*"})
public class Module2Configuration extends SoapAppConfiguration {

    @Override
    @Bean(name = "service")
    public Wsdl11Definition defaultWsdl11Definition() {
        ClassPathResource wsdlRes = new ClassPathResource("wsdl/Your_WSDL.wsdl");
        return new SimpleWsdl11Definition(wsdlRes);
    }

    @Override
    protected void setupPrecondition() {
        super.setupPrecondition();
        setLogGateWay(true);
        activityIdInterceptor.setEnabled(true);
    }
}

2.Prepare entry point and run as Boot app:
public class App {

public static void main(String[] args) throws Exception {
    Entrypoint.start("module1",args,
                     new AppModule(AppModule.AppType.REST, "module1", "/module1/*", Module1Configuration.class),
                     new AppModule(AppModule.AppType.SOAP, "module2", "module2", Module2Configuration.class)
                    );
}

}

enjoy ^_^

Useful links:

https://dzone.com/articles/what-servlet-container

Spring: Why "root" application context and "servlet" application context are created by different parties?

Role/Purpose of ContextLoaderListener in Spring?


来源: stackexchange

问:
How do I execute a Java/Python program multiple times?
I am currently working on an assignment, where the task is to measure the execution time for a number of programs in both Python and Java, for the purpose of measuring and comparing performance for the two computer languages. I have 10 tests in total, in sets of 2; for every set, one test is written in Java and the corresponding one is written in Python, and so forth. I want to run every test multiple times, e.g. 100 times, and measure the time for every run. Then I'd like to compute the sum of the obtained execution time(s). How would I do this in Python/Java? I have tried writing a double for-loop like this:

```<code>for i in range(1, 100):
for j in range(1, 10000000):
# do integer division
</code>```

...but it doesn't seem to work. Also I'd like to do the same thing in Java. How would I do this?

答:
Python:

```<code>import time

meas = []
for i in range(100):
  start = time.time()
  for j in range(10000000):
    # do integer division
  meas.append(time.time() - start)
</code>```

Java:

```<code>long meas[] = new long[100];
for(int i = 0; i < 100; i++){
  long start=System.nanoTime();
  for(int j = 0; j < 10000000; j++)
    // do integer division
  }
  meas[i] = System.nanoTime()-start;
}
</code>```

In both languages you will have 100 measurements in the 'meas' arrays (units: whole nanoseconds for Java, floating point seconds for Python - so the latter has fractional part too), where each measurement run the division 10000000 times.

ContentLicense: CC BY-SA 3.0

Body:
I am currently working on an assignment, where the task is to measure the execution time for a number of programs in both Python and Java, for the purpose of measuring and comparing performance for the two computer languages. I have 10 tests in total, in sets of 2; for every set, one test is written in Java and the corresponding one is written in Python, and so forth. I want to run every test multiple times, e.g. 100 times, and measure the time for every run. Then I'd like to compute the sum of the obtained execution time(s). How would I do this in Python/Java? I have tried writing a double for-loop like this:

for i in range(1, 100):
for j in range(1, 10000000):
# do integer division

...but it doesn't seem to work. Also I'd like to do the same thing in Java. How would I do this?

Body:
Python:

import time

meas = []
for i in range(100):
  start = time.time()
  for j in range(10000000):
    # do integer division
  meas.append(time.time() - start)

Java:

long meas[] = new long[100];
for(int i = 0; i < 100; i++){
  long start=System.nanoTime();
  for(int j = 0; j < 10000000; j++)
    // do integer division
  }
  meas[i] = System.nanoTime()-start;
}

In both languages you will have 100 measurements in the 'meas' arrays (units: whole nanoseconds for Java, floating point seconds for Python - so the latter has fractional part too), where each measurement run the division 10000000 times.


问:
How to not wrap row on browser resize
I am using Bootstrap to structure the page like this. Each row has the same structure.

```<code><div class="outerDiv">
    <div class="row">
        <div class="col-md-6">
            ...
        </div>
        <div class="col-md-1">
            ...
        </div>
        <div class="col-md-1">
            ...
        </div>
        <div class="col-md-1">
            ...
        </div>
        <div class="col-md-1">
            ...
        </div>
        <div class="col-md-1">
            ...
        </div>
    </div>

    <div class="row">
        <div class="col-md-6">
            ...
        </div>
        <div class="col-md-1">
            ...
        </div>
        <div class="col-md-1">
            ...
        </div>
        <div class="col-md-1">
            ...
        </div>
        <div class="col-md-1">
            ...
        </div>
        <div class="col-md-1">
            ...
        </div>
    </div>
</div>
</code>```

This is working fine and looks like this.

```<code><------col-md-6------><-col-md-1-><-col-md-1-><-col-md-1-><-col-md-1-><-col-md-1->
<------col-md-6------><-col-md-1-><-col-md-1-><-col-md-1-><-col-md-1-><-col-md-1->
</code>```

But when the browser resizes horitontally (gets narrower). The pages becomes the following:

```<code><------col-md-6------>
<-col-md-1->
<-col-md-1->
<-col-md-1->
<-col-md-1->
<-col-md-1->
<------col-md-6------>
<-col-md-1->
<-col-md-1->
<-col-md-1->
<-col-md-1->
<-col-md-1->
</code>```

So how do I make it so that it does not stack? And have to be scrolled?

I have tried applying the following css but does not work.

```<code>.row {
    white-space: nowrap;
    min-width: 1250px;
    overflow: auto;
}
</code>```

答:
You will need to use col-xs- instead of col-md-. Your columns will get super skinny as a single column (width 12.5%) of a 300px viewport/parent element width is 37.5px (not a lot of room for content). Adding a minimum width for .row might be required depending on your needs.

When using the medium grid classes a class like .col-md-6 is set to width: 50%; for viewport sizes 992px and up. Below that the element (normally a DIV) no longer has a width applied to it and reverts to being a block level element that takes up the full width of the parent element. Hence the wrapping of your elements.

Using a smaller grid class like -xs- lowers the threshold for how small of a screen that an element will have a width set on it.

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="col-xs-6">col-xs-6</div>
  <div class="col-xs-1">col-xs-1</div>
  <div class="col-xs-1">col-xs-1</div>
  <div class="col-xs-1">col-xs-1</div>
  <div class="col-xs-1">col-xs-1</div>
  <div class="col-xs-1">col-xs-1</div>
</div>

<div class="row">
  <div class="col-xs-6">col-xs-6</div>
  <div class="col-xs-1">col-xs-1</div>
  <div class="col-xs-1">col-xs-1</div>
  <div class="col-xs-1">col-xs-1</div>
  <div class="col-xs-1">col-xs-1</div>
  <div class="col-xs-1">col-xs-1</div>
</div></code>```

Example using a horizontal scrollbar if not enough space is available for content in the columns.

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');
.fixed-container {
  overflow-x: scroll;
}

.fixed-container .row {
  min-width: 1250px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="fixed-container">

    <div class="row">
      <div class="col-xs-6">col-xs-6</div>
      <div class="col-xs-1">col-xs-1</div>
      <div class="col-xs-1">col-xs-1</div>
      <div class="col-xs-1">col-xs-1</div>
      <div class="col-xs-1">col-xs-1</div>
      <div class="col-xs-1">col-xs-1</div>
    </div>

    <div class="row">
      <div class="col-xs-6">col-xs-6</div>
      <div class="col-xs-1">col-xs-1</div>
      <div class="col-xs-1">col-xs-1</div>
      <div class="col-xs-1">col-xs-1</div>
      <div class="col-xs-1">col-xs-1</div>
      <div class="col-xs-1">col-xs-1</div>
    </div>

  </div>
</div></code>```

Title: How to not wrap row on browser resize

Body:
I am using Bootstrap to structure the page like this. Each row has the same structure.

            ...

            ...

            ...

            ...

            ...

            ...

            ...

            ...

            ...

            ...

            ...

            ...

This is working fine and looks like this.

<------col-md-6------><-col-md-1-><-col-md-1-><-col-md-1-><-col-md-1-><-col-md-1->
<------col-md-6------><-col-md-1-><-col-md-1-><-col-md-1-><-col-md-1-><-col-md-1->

But when the browser resizes horitontally (gets narrower). The pages becomes the following:

<------col-md-6------>
<-col-md-1->
<-col-md-1->
<-col-md-1->
<-col-md-1->
<-col-md-1->
<------col-md-6------>
<-col-md-1->
<-col-md-1->
<-col-md-1->
<-col-md-1->
<-col-md-1->

So how do I make it so that it does not stack? And have to be scrolled?

I have tried applying the following css but does not work.

.row {
    white-space: nowrap;
    min-width: 1250px;
    overflow: auto;
}

Body:
You will need to use col-xs- instead of col-md-. Your columns will get super skinny as a single column (width 12.5%) of a 300px viewport/parent element width is 37.5px (not a lot of room for content). Adding a minimum width for .row might be required depending on your needs.

When using the medium grid classes a class like .col-md-6 is set to width: 50%; for viewport sizes 992px and up. Below that the element (normally a DIV) no longer has a width applied to it and reverts to being a block level element that takes up the full width of the parent element. Hence the wrapping of your elements.

Using a smaller grid class like -xs- lowers the threshold for how small of a screen that an element will have a width set on it.

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');

<div class="row">
  <div class="col-xs-6">col-xs-6</div>
  <div class="col-xs-1">col-xs-1</div>
  <div class="col-xs-1">col-xs-1</div>
  <div class="col-xs-1">col-xs-1</div>
  <div class="col-xs-1">col-xs-1</div>
  <div class="col-xs-1">col-xs-1</div>
</div>

<div class="row">
  <div class="col-xs-6">col-xs-6</div>
  <div class="col-xs-1">col-xs-1</div>
  <div class="col-xs-1">col-xs-1</div>
  <div class="col-xs-1">col-xs-1</div>
  <div class="col-xs-1">col-xs-1</div>
  <div class="col-xs-1">col-xs-1</div>
</div>

Example using a horizontal scrollbar if not enough space is available for content in the columns.

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');
.fixed-container {
  overflow-x: scroll;
}

.fixed-container .row {
  min-width: 1250px;
}

<div class="container">
  <div class="fixed-container">

    <div class="row">
      <div class="col-xs-6">col-xs-6</div>
      <div class="col-xs-1">col-xs-1</div>
      <div class="col-xs-1">col-xs-1</div>
      <div class="col-xs-1">col-xs-1</div>
      <div class="col-xs-1">col-xs-1</div>
      <div class="col-xs-1">col-xs-1</div>
    </div>

    <div class="row">
      <div class="col-xs-6">col-xs-6</div>
      <div class="col-xs-1">col-xs-1</div>
      <div class="col-xs-1">col-xs-1</div>
      <div class="col-xs-1">col-xs-1</div>
      <div class="col-xs-1">col-xs-1</div>
      <div class="col-xs-1">col-xs-1</div>
    </div>

  </div>
</div>


问:
How to RSA sign using only modulus and private key exponent (d)?
I am trying to preform private key operation like RSA sign using only (n) and (d).
My system exposes an API which only (n) and (d) inputs, sadly I can't change the API itself.

Since I'm using the latest OpenSSL release I have to use the setter: RSA_set0_key which mandates providing the (n) and (e), regardless to the operation that will be made using the given RSA (private key operation in my case)

So my questions is:

Can I perform RSA signing operation using only (n) and (d)?
I don't want to guess the public exponent and I can't receive it in the process.

If the answer is NO.
Can I use arbitrary prime number as (e) for the RSA_set0_key? does the EVP/rsa_sign functions will validate that the public exponent is compatible with the private?

Thanks

答:
Strictly speaking, if you only know one exponent (d or e) and the modulus (n), you can't easily find the inverse exponent (e or d) without knowing the factors of the modulus -- that's why RSA is secure.

However, most RSA implementations use a fixed exponent for e -- generally 65537 (0x10001), so you really only need to know n.

Now your question is a bit strange, as RSA signing only uses N and D -- you need E to verify the signature.  RSA_get0_key gives you N and D and E from an RSA key object.  Perhaps you mean RSA_set0_key which is for putting values into a RSA key object?  That only requires that you provide N, though if you leave E unset you won't be able to verify signatures or encrypt data.  As long as you set D (and N), you should be able to generate signatures just fine.


问:
Swift Image Download TableView
I'm trying to fix a problem with downloading an image asynchronously in a TableView in Swift. This is my Problem: I download the image from a url asynchronously, but if I scroll quickly the TableView my pictures begin to rotate.(The images alternate until the correct one appears).

This is my Download Async Code and imageCache

```<code>let imageCache = NSCache()

//DOWNLOAD Image ASINC
extension UIImageView {

    public func imageFromServerURL(url: String){

        if(imageCache.objectForKey(url) != nil){
            self.image = imageCache.objectForKey(url) as? UIImage
        }else{

            let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
            let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
            let task = session.dataTaskWithURL(NSURL(string: url)!, completionHandler: { (data, response, error) -> Void in
                if error == nil {

                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        if let downloadedImage = UIImage(data: data!) {
                            imageCache.setObject(downloadedImage, forKey: url)
                            self.image = downloadedImage
                        }
                    })

                }
                else {
                    print(error)
                }
            })
            task.resume()
        }

    }
}
</code>```

and Which I recall in the TableView so:

```<code>func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("record_charts", forIndexPath: indexPath) as! myTableViewCell

            let url_img = "https://image/download.jpg"
            cell.immagine.imageFromServerURL(url_img)

        return cell
    }
</code>```

This is the gif to show you the problem better

答:
You need to add cancellation method in UIImageView extension, and call it or in tableView(_:willDisplay:forRowAt:) or in prepareForReuse() of UITableViewCell

or you can cancel request as in SDWebImage's web cache

Title: Swift Image Download TableView

Body:
I'm trying to fix a problem with downloading an image asynchronously in a TableView in Swift. This is my Problem: I download the image from a url asynchronously, but if I scroll quickly the TableView my pictures begin to rotate.(The images alternate until the correct one appears).

This is my Download Async Code and imageCache

let imageCache = NSCache()

//DOWNLOAD Image ASINC
extension UIImageView {

    public func imageFromServerURL(url: String){

        if(imageCache.objectForKey(url) != nil){
            self.image = imageCache.objectForKey(url) as? UIImage
        }else{

            let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
            let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
            let task = session.dataTaskWithURL(NSURL(string: url)!, completionHandler: { (data, response, error) -> Void in
                if error == nil {

                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        if let downloadedImage = UIImage(data: data!) {
                            imageCache.setObject(downloadedImage, forKey: url)
                            self.image = downloadedImage
                        }
                    })

                }
                else {
                    print(error)
                }
            })
            task.resume()
        }

    }
}

and Which I recall in the TableView so:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("record_charts", forIndexPath: indexPath) as! myTableViewCell

            let url_img = "https://image/download.jpg"
            cell.immagine.imageFromServerURL(url_img)

        return cell
    }

This is the gif to show you the problem better


问:
How to create a sub array from another array in Java?
How to create a sub-array from another array? Is there a method that takes the indexes from the first array such as:

```<code>methodName(object array, int start, int end)
</code>```

I don't want to go over making loops and making my program suffer.

I keep getting error:

cannot find symbol method copyOfRange(int[],int,int)

This is my code:

```<code>import java.util.*;

public class testing
{
    public static void main(String [] arg)
    {
        int[] src = new int[] {1, 2, 3, 4, 5};
        int b1[] = Arrays.copyOfRange(src, 0, 2);
    }
}
</code>```

答:
Yes, it's called System.arraycopy(Object, int, Object, int, int) .

It's still going to perform a loop somewhere though, unless this can get optimized into something like REP STOSW by the JIT (in which case the loop is inside the CPU).

```<code>int[] src = new int[] {1, 2, 3, 4, 5};
int[] dst = new int[3];

System.arraycopy(src, 1, dst, 0, 3); // Copies 2, 3, 4 into dst
</code>```

Body:
How to create a sub-array from another array? Is there a method that takes the indexes from the first array such as:

methodName(object array, int start, int end)

I don't want to go over making loops and making my program suffer.

I keep getting error:

cannot find symbol method copyOfRange(int[],int,int)

This is my code:

import java.util.*;

public class testing
{
    public static void main(String [] arg)
    {
        int[] src = new int[] {1, 2, 3, 4, 5};
        int b1[] = Arrays.copyOfRange(src, 0, 2);
    }
}

Body:
Yes, it's called System.arraycopy(Object, int, Object, int, int) .

It's still going to perform a loop somewhere though, unless this can get optimized into something like REP STOSW by the JIT (in which case the loop is inside the CPU).

int[] src = new int[] {1, 2, 3, 4, 5};
int[] dst = new int[3];

System.arraycopy(src, 1, dst, 0, 3); // Copies 2, 3, 4 into dst


问:
Jquery dynamically created list item not fading out
I have a code where when a checkbox is checked, the list item that the checkbox is contained in is supposed to fade out from view. Here is my current code:

```<code> $(document).on('change', '.task', function(){
var id = $(this).attr('id');
          $.ajax({
            url: '/task/'+id,
            method: 'POST',
            data: {'_method' : 'PUT'},
            dataType: 'json',
            success:function(json){

              if(json.isSent){
                alert('Task Updated Successfully!');
                $(this).closest('li').fadeOut(500);
              }

            }
          });
}
</code>```

And here is my html (Note: I am using Laravel, so some of the html contains Blade code, but it does work properly)'

```<code> @foreach ($return['Tasks'] as $task)
        <li class="list-group-item">
            <div class="form-group">
                <label class="control-label">{{ $task->name }} (Due on {{ $task->timeDue->format('l\\, F jS \\a\\t h:i:s A') }})</label>
                <div class="float-left">
                    <input type="checkbox" id="{{ $task->id }}" class="big-checkbox task" />
                </div>
            </div>
        </li>
      @endforeach
</code>```

When I check the checkbox, the "Task Updated Successfully" alert shows up, so I know that the code is running, but the fadeOut won't do anything. There are no errors in the console either to tell me what went wrong, it just won't fade out.

答:
I believe your scope is lost (this).
Try that instead</p>

```<code>$(document).on('change', '.task', function(){
      var o = $(this);
      var id = $(this).attr('id');
          $.ajax({
            url: '/task/'+id,
            method: 'POST',
            data: {'_method' : 'PUT'},
            dataType: 'json',
            success:function(json){

              if(json.isSent){
                alert('Task Updated Successfully!');
                o.closest('li').fadeOut(500);
              }

            }
          });
}
</code>```

Body:
I have a code where when a checkbox is checked, the list item that the checkbox is contained in is supposed to fade out from view. Here is my current code:

 $(document).on('change', '.task', function(){
var id = $(this).attr('id');
          $.ajax({
            url: '/task/'+id,
            method: 'POST',
            data: {'_method' : 'PUT'},
            dataType: 'json',
            success:function(json){

              if(json.isSent){
                alert('Task Updated Successfully!');
                $(this).closest('li').fadeOut(500);
              }

            }
          });
}

And here is my html (Note: I am using Laravel, so some of the html contains Blade code, but it does work properly)'

 @foreach ($return['Tasks'] as $task)

                {{ $task->name }} (Due on {{ $task->timeDue->format('l\\, F jS \\a\\t h:i:s A') }})

                    <input type="checkbox" id="{{ $task->id }}" class="big-checkbox task" />

      @endforeach

When I check the checkbox, the "Task Updated Successfully" alert shows up, so I know that the code is running, but the fadeOut won't do anything. There are no errors in the console either to tell me what went wrong, it just won't fade out.

Body:
I believe your scope is lost (this).
Try that instead

$(document).on('change', '.task', function(){
      var o = $(this);
      var id = $(this).attr('id');
          $.ajax({
            url: '/task/'+id,
            method: 'POST',
            data: {'_method' : 'PUT'},
            dataType: 'json',
            success:function(json){

              if(json.isSent){
                alert('Task Updated Successfully!');
                o.closest('li').fadeOut(500);
              }

            }
          });
}


问:
Oracle query looking for particular string format
Am working with an Oracle 11g db in which I need to run a query that returns all rows with values in a specific format.

I.e., I need to find all rows with a value like 'abc1234'. The actual values aren't important....what I need is to find all rows with the first 3 characters being alpha and the subsequent 4 characters all being numeric.

Any input would be much appreciated.

答:
```<code>Try it this will work definitely:

Let's take a sample example:

For example, create a sample table

CREATE TABLE bob (
         empno      VARCHAR2(10) NOT NULL,
         ename      VARCHAR2(15) NOT NULL,
         ssn        VARCHAR2(10) NOT NULL);

Insert data into that table

Insert into bob ( empno,ename,ssn) values ('abC0123458','zXe5378023','0pl4783202');
Insert into bob ( empno,ename,ssn) values ('0123abcdef','a12dldfddd','Rns0101010');

Query to select the all the columns

select * from bob
where   length(trim(translate(substr(empno,1,3),'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',' '))) IS NULL
AND
length(trim(translate(substr(empno,4,4),'0123456789',' '))) IS NULL;

To do the same thing on multiple columns use union operator

select * from bob
where   length(trim(translate(substr(empno,1,3),'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',' '))) IS NULL
AND
length(trim(translate(substr(empno,4,4),'0123456789',' '))) IS NULL;
union
select * from bob
where   length(trim(translate(substr(ename,1,3),'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',' '))) IS NULL
AND
length(trim(translate(substr(ename,4,4),'0123456789',' '))) IS NULL;
</code>```

ContentLicense: CC BY-SA 4.0


问:
Unable to merge android manifests. See the Console for more details
I got following error while making apk file from unity. I set minimum API level=19 and target 24. because I build a apk for Gear VR and I have Samsung S7 Edge.

CommandInvokationFailure: Unable to merge android manifests. See the
  Console for more details.  C:/Program
  Files/Java/jdk1.8.0_131\bin\java.exe -Xmx2048M
  -Dcom.android.sdkmanager.toolsdir="C:/Android/sdk\tools" -Dfile.encoding=UTF8 -jar "C:\Users\saad asghar\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" -

stderr[ Error:Invalid command manifmerger ] stdout[

] exit code: 64 UnityEditor.Android.Command.Run
  (System.Diagnostics.ProcessStartInfo psi,
  UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit,
  System.String errorMsg)
  UnityEditor.Android.AndroidSDKTools.RunCommandInternal (System.String
  javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand,
  Int32 memoryMB, System.String workingdir,
  UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit,
  System.String errorMsg)
  UnityEditor.Android.AndroidSDKTools.RunCommandSafe (System.String
  javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand,
  Int32 memoryMB, System.String workingdir,
  UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit,
  System.String errorMsg) UnityEditor.HostView:OnGUI()

答:
thank you so much guys for help!

finally i make apk file by doing the following steps.

1 just open https://developer.android.com/studio/index.html
2 scroll down to the bottom of that page
go to downloads
scroll down to the bottom of that page
3 find Windows "tools_r25.2.3-windows.zip" download and unzip it
4 or, on mac: find MacOSX "tools_r25.2.3-macosx.zip" download and unzip it.
5 In the SDK path replace the tools folder.


问:
Using QFileSystemModel to display only one directory
Is it possible to use QFileSystemModel to list only one directory contents instead of all drives in my computer (in Windows)?

答:
That would be a function of your view, not your model:

 http://doc.trolltech.com/latest/qabstractitemview.html#setRootIndex

Update:

No more Trolltech links,
the updated link is QAbstractItemView Class

ContentLicense: CC BY-SA 2.5


问:
Javascript find a position of a word in a string containing HTML
I got the following HTML:

```<code><div id="editable_phrase">
   My
   <span style="background-color: #19FC49;"> first</span>
   <span style="background-color: #09AC20;"> first</span> //note 2 firsts here
   <span style="background-color: #D2C3EA;"> phrase</span>
</div>
</code>```

And the original phrase that is - My first phrase

I need to find a position of a first letter of a selected word in my original phrase. So if I select (highlight with a mouse) phrase, I need to get 10 (or whatever it is). I tried to use charAt() or window.getSelection but still getting wrong results.

Moreover, if I select the same word but in different positions (like inm my example above where there are 2 first words) I get the same result as it finds the position of the first word while I need the second one.

I can use jQuery. Any ideas would be welcome. Thank you.

答:
As you've said you've already got a function to get selection of words, it's as simple as indexOf() - just replace the selectedText below with the word your function returns, and do the action after the text was selected:

let el = document.getElementById('editable_phrase');

let selectedText = "phrase";
let originalPhrase = el.innerText;

console.log(originalPhrase.indexOf(selectedText));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="editable_phrase">
  My
  <span style="background-color: #19FC49;"> first</span>
  <span style="background-color: #D2C3EA;"> phrase</span>
</div></code>```

Body:
I got the following HTML:

   My
    first
    first //note 2 firsts here
    phrase

And the original phrase that is - My first phrase

I need to find a position of a first letter of a selected word in my original phrase. So if I select (highlight with a mouse) phrase, I need to get 10 (or whatever it is). I tried to use charAt() or window.getSelection but still getting wrong results.

Moreover, if I select the same word but in different positions (like inm my example above where there are 2 first words) I get the same result as it finds the position of the first word while I need the second one.

I can use jQuery. Any ideas would be welcome. Thank you.

Body:
As you've said you've already got a function to get selection of words, it's as simple as indexOf() - just replace the selectedText below with the word your function returns, and do the action after the text was selected:

let el = document.getElementById('editable_phrase');

let selectedText = "phrase";
let originalPhrase = el.innerText;

console.log(originalPhrase.indexOf(selectedText));

<div id="editable_phrase">
  My
  <span style="background-color: #19FC49;"> first</span>
  <span style="background-color: #D2C3EA;"> phrase</span>
</div>


问:
Django/React Native/OAuth: Best way to handle Auth flow?
So I'm trying to integrate a Django/Python backend framework with a React Native frontend, and I was wondering if there are any good resources/answers out there to handle OAuth flow?

I've tried a lot of different aspects, and from the server side at least, the best thing that possibly worked is OAuth Toolkit. I also want to use Django REST framework to exchange data between server/client.

However, I am confused about the flow of authentication between the app and the server and would appreciate a better understanding. Thanks!

答:
The Django OAuth Toolkit documentation has a good tutorial on how to get started:

OAuth Toolkit Tutorial

A basic summary of the authentication flow:

Login with credentials (Post request to server with username/password)

Server returns an auth token to React-Native client application to use. You should store this somehow in the react-native app, such as a cookie

When performing an API request, provide the token in the request header like so:

Authorization: "Bearer TOKEN_VALUE_RETURNED_FROM_SERVER"


问:
How to add go code into an existing project
I am pretty new to go. We are currently splitting some microservices off of our monolithic Django+python web app and we have decided to do at least some of them in go. The problem is that the sources for the services are supposed to live in the same repo as the main app. So I have all the python code in ~/GloriousMomolith/thedjangoapp and split off services in ~/GloriousMomolith/services/some-service-name.

I could move ~/GloriousMonolith under ~/src (I have $GOPATH set to $HOME), but then every time I refer to a go package I create I would have to do import GloriousMomolith/services/someservice/somepackage. I want to avoid that. At the very least, I want to avoid having GloriousMomolith part hard-coded anywhere. Any suggestions?

答:
You can add a Go source directory to your project.  For example:

```<code>~/
   GloriousMomolith/
      thedjangoapp/
      src/
         services/
            someservice/
               service.go
</code>```

Set GOPATH to $HOME/GloriousMomolith:$HOME.

You can now import relative to the the src directory:

```<code>import (
   "services/someservice"
)
</code>```

Body:
You can add a Go source directory to your project.  For example:

~/
   GloriousMomolith/
      thedjangoapp/
      src/
         services/
            someservice/
               service.go

Set GOPATH to $HOME/GloriousMomolith:$HOME.

You can now import relative to the the src directory:

import (
   "services/someservice"
)


问:
How to data bind a nested button inside a mapFragment
I am trying to bind a button which i have put inside a MapFragment
I want my map to have a button which acts like a  menu button

this is my fragment

```<code>public class MapFragment extends Fragment implements
    OnMapReadyCallback,
    View.OnClickListener{

public SupportMapFragment mapFragment;
private GoogleMap mMap;
FragmentMapBinding fragmentMapBinding;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    fragmentMapBinding = DataBindingUtil.inflate(inflater,R.layout.fragment_map,container,false);

    View rootView = fragmentMapBinding.getRoot();
    fragmentMapBinding.setHandler(this);
    mapFragment = (SupportMapFragment) getChildFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    return rootView;
}
}
</code>```

this is the .xml of the fragment

```<code><layout xmlns:android="http://schemas.android.com/apk/res/android">

<data>
    <variable
        name="handler"
        type="com.plotalong.android.activity.fragment.MapFragment"/>
</data>

<fragment xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.plotalong.android.activity.MapsActivity" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TEST"
        android:onClick="@{() -> handler.menuButtonClick()}"
        />
</fragment>
</code>```

and this is the error log I get

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.plotalong.android/com.plotalong.android.activity.MainActivity}: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
                                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2338)
                                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
                                                                       at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:110)
                                                                       at android.os.Looper.loop(Looper.java:193)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5292)
                                                                       at java.lang.reflect.Method.invokeNative(Native Method)
                                                                       at java.lang.reflect.Method.invoke(Method.java:515)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
                                                                       at dalvik.system.NativeStart.main(Native Method)
                                                                    Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
                                                                       at android.databinding.ViewDataBinding.mapBindings(ViewDataBinding.java:1092)
                                                                       at android.databinding.ViewDataBinding.mapBindings(ViewDataBinding.java:1149)
                                                                       at android.databinding.ViewDataBinding.mapBindings(ViewDataBinding.java:600)
                                                                       at com.plotalong.android.databinding.FragmentMapBinding.<init>(FragmentMapBinding.java:24)
                                                                       at com.plotalong.android.databinding.FragmentMapBinding.bind(FragmentMapBinding.java:134)
                                                                       at android.databinding.DataBinderMapper.getDataBinder(DataBinderMapper.java:15)
                                                                       at android.databinding.DataBindingUtil.bind(DataBindingUtil.java:185)
                                                                       at android.databinding.DataBindingUtil.inflate(DataBindingUtil.java:120)
                                                                       at android.databinding.DataBindingUtil.inflate(DataBindingUtil.java:88)
                                                                       at com.plotalong.android.activity.fragment.MapFragment.onCreateView(MapFragment.java:66)
                                                                       at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
                                                                       at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
                                                                       at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
                                                                       at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
                                                                       at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
                                                                       at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
                                                                       at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
                                                                       at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
                                                                       at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
                                                                       at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:388)
                                                                       at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:607)
                                                                       at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1174)
                                                                       at android.app.Activity.performStart(Activity.java:5274)
                                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
                                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
                                                                       at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:110)
                                                                       at android.os.Looper.loop(Looper.java:193)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5292)
                                                                       at java.lang.reflect.Method.invokeNative(Native Method)
                                                                       at java.lang.reflect.Method.invoke(Method.java:515)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
                                                                       at dalvik.system.NativeStart.main(Native Method)
</code>```

What could be the problem with the code??

答: The problem is that you can't stick a <Button> (or any other <View>) inside a <fragment> tag. In general you should not attempt to modify what's inside SupportMapFragment, that's private to SupportMapFragment itself. You could place a Button above or below SupportMapFragment, though. (outside of SupportMapFragment)

Body:
I am trying to bind a button which i have put inside a MapFragment
I want my map to have a button which acts like a  menu button

this is my fragment

public class MapFragment extends Fragment implements
    OnMapReadyCallback,
    View.OnClickListener{

public SupportMapFragment mapFragment;
private GoogleMap mMap;
FragmentMapBinding fragmentMapBinding;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    fragmentMapBinding = DataBindingUtil.inflate(inflater,R.layout.fragment_map,container,false);

    View rootView = fragmentMapBinding.getRoot();
    fragmentMapBinding.setHandler(this);
    mapFragment = (SupportMapFragment) getChildFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    return rootView;
}
}

this is the .xml of the fragment

<layout xmlns:android="http://schemas.android.com/apk/res/android">

<data>
    <variable
        name="handler"
        type="com.plotalong.android.activity.fragment.MapFragment"/>
</data>

<fragment xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.plotalong.android.activity.MapsActivity" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TEST"
        android:onClick="@{() -> handler.menuButtonClick()}"
        />
</fragment>

and this is the error log I get

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.plotalong.android/com.plotalong.android.activity.MainActivity}: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
                                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2338)
                                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
                                                                       at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:110)
                                                                       at android.os.Looper.loop(Looper.java:193)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5292)
                                                                       at java.lang.reflect.Method.invokeNative(Native Method)
                                                                       at java.lang.reflect.Method.invoke(Method.java:515)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
                                                                       at dalvik.system.NativeStart.main(Native Method)
                                                                    Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
                                                                       at android.databinding.ViewDataBinding.mapBindings(ViewDataBinding.java:1092)
                                                                       at android.databinding.ViewDataBinding.mapBindings(ViewDataBinding.java:1149)
                                                                       at android.databinding.ViewDataBinding.mapBindings(ViewDataBinding.java:600)
                                                                       at com.plotalong.android.databinding.FragmentMapBinding.<init>(FragmentMapBinding.java:24)
                                                                       at com.plotalong.android.databinding.FragmentMapBinding.bind(FragmentMapBinding.java:134)
                                                                       at android.databinding.DataBinderMapper.getDataBinder(DataBinderMapper.java:15)
                                                                       at android.databinding.DataBindingUtil.bind(DataBindingUtil.java:185)
                                                                       at android.databinding.DataBindingUtil.inflate(DataBindingUtil.java:120)
                                                                       at android.databinding.DataBindingUtil.inflate(DataBindingUtil.java:88)
                                                                       at com.plotalong.android.activity.fragment.MapFragment.onCreateView(MapFragment.java:66)
                                                                       at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
                                                                       at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
                                                                       at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
                                                                       at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
                                                                       at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
                                                                       at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
                                                                       at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
                                                                       at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
                                                                       at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
                                                                       at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:388)
                                                                       at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:607)
                                                                       at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1174)
                                                                       at android.app.Activity.performStart(Activity.java:5274)
                                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
                                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
                                                                       at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:110)
                                                                       at android.os.Looper.loop(Looper.java:193)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5292)
                                                                       at java.lang.reflect.Method.invokeNative(Native Method)
                                                                       at java.lang.reflect.Method.invoke(Method.java:515)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
                                                                       at dalvik.system.NativeStart.main(Native Method)

What could be the problem with the code??