问:
unable to start embedded container maven spring boot
I have a problem with running the spring boot project. it failed to run. the error showing:

```<code>2017-12-07 13:55:54.639  INFO 8624 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2a5c8d3f: startup date [Thu Dec 07 13:55:54 ICT 2017]; root of context hierarchy
2017-12-07 13:55:54.842  INFO 8624 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2017-12-07 13:55:54.881  INFO 8624 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$f3f6c3e5] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.6.RELEASE)

2017-12-07 13:55:55.240  INFO 8624 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at: http://localhost:8888
2017-12-07 13:55:56.317  WARN 8624 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Could not locate PropertySource: I/O error on GET request for "http://localhost:8888/hpx-delivery-report/default": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
2017-12-07 13:55:56.318  INFO 8624 --- [           main] c.p.i.m.s.b.uniqueid.EPolicyApplication  : No active profile set, falling back to default profiles: default
2017-12-07 13:55:56.327  INFO 8624 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3dd1dc90: startup date [Thu Dec 07 13:55:56 ICT 2017]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@2a5c8d3f
2017-12-07 13:55:57.518  INFO 8624 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=781352cf-bed8-31d9-a952-be1fa48d68a0
2017-12-07 13:55:57.537  INFO 8624 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2017-12-07 13:55:57.635  INFO 8624 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$d7dcc0e8] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-12-07 13:55:57.671  INFO 8624 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$f3f6c3e5] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-12-07 13:55:57.676  WARN 8624 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
2017-12-07 13:55:57.683  INFO 8624 --- [           main] utoConfigurationReportLoggingInitializer :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-12-07 13:55:57.690 ERROR 8624 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537) ~[spring-context-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at com.prudential.integration.middleware.spring.boot.uniqueid.EPolicyApplication.main(EPolicyApplication.java:10) [classes/:na]
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:189) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:162) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:134) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    ... 8 common frames omitted
</code>```

before it, I have javax.servlet.api dependency but I think this is the problem, so I remove that dependencies but when I try to run spring boot project, still failed. I also exclude starter tomcat dependencies but still failed. I also see the solution with same problem in stackoverflow too but I can't find the solution.

my pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.prudential.integration.middleware.spring.boot</groupId>
    <artifactId>hpx-aws-letter-unique-id</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>hpx-aws-letter-unique-id</name>
    <description>Hpx Aws Letter Unique Id Service Spring Boot</description>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.6.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <swagger.version>2.7.0</swagger.version>
        <jboss.home>${env.JBOSS_HOME}</jboss.home>
        <config.server>http://10.170.49.103/configserver</config.server>
        <spring-cloud.version>1.3.2.RELEASE</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- QueryDSL -->
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-apt</artifactId>
        </dependency>
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-jpa</artifactId>
        </dependency>

        <!-- Swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.github.jmnarloch</groupId>
            <artifactId>modelmapper-spring-boot-starter</artifactId>
            <version>1.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.15</version>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6.12</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.6</version>
        </dependency>

        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.54</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.3</version>
    </dependency>

    <dependency>
    <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20171018</version>
    </dependency>

        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.9</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>${project.name}-${project.version}</finalName>
        <plugins>

            <!-- JBOSS maven plugin to simulate deployment to JBOSS -->
            <plugin>
                <groupId>org.jboss.as.plugins</groupId>
                <artifactId>jboss-as-maven-plugin</artifactId>
                <version>7.9.Final</version>
                <configuration>
                    <jbossHome>${jboss.home}</jbossHome>
                    <serverArgs>
                        <serverArg>-Dspring.profiles.active=${run.profiles}</serverArg>
                        <serverArg>-Dspring.cloud.config.uri=${config.server}</serverArg>
                    </serverArgs>
                </configuration>
            </plugin>

            <!-- QueryDSL Generator -->
            <plugin>
                <groupId>com.mysema.maven</groupId>
                <artifactId>apt-maven-plugin</artifactId>
                <version>1.1.3</version>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <skipTests>true</skipTests>
                </configuration>
            </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>1.5.9.RELEASE</version>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        </plugins>
    </build>
</project>
</code>```

my controller:

```<code>@RestController
@RequestMapping("/hpx")
@Api(value="hpx", description="HPX Web Service")
public class HPXController {

    final static Logger logger = Logger.getLogger(HPXController.class);

    @RequestMapping(value = "/testing", method = RequestMethod.POST)
    public String tesMethod(){
        return "testing method";
    }
}
</code>```

my configuration:

```<code>@SpringBootApplication
public class EPolicyApplication {

    public static void main(String[] args) {
        SpringApplication.run(EPolicyApplication.class, args);
    }
}
</code>```

servlet:

```<code>public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(EPolicyApplication.class);
    }

}
</code>```

答:
You need spring boot maven plugin to run it using mvn spring-boot:run. Please add below plugin to your pom.xml.

```<code><plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
      <version>1.5.9.RELEASE</version>
      <executions>
        <execution>
          <goals>
            <goal>repackage</goal>
          </goals>
        </execution>
      </executions>
</plugin>
</code>```

Also make the tomcat dependency as provided so that it wont be added in the war.

```<code>    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
</code>```

You can modify the goal as per your requirement or remove it.
Then with embedded tomcat you test your application with above commands. To deploy it to external app server you need to package it as a war and copy it to specific directory of your App server (i.e. Jboss EAP).

Body:
I have a problem with running the spring boot project. it failed to run. the error showing:

2017-12-07 13:55:54.639  INFO 8624 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2a5c8d3f: startup date [Thu Dec 07 13:55:54 ICT 2017]; root of context hierarchy
2017-12-07 13:55:54.842  INFO 8624 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2017-12-07 13:55:54.881  INFO 8624 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$f3f6c3e5] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.6.RELEASE)

2017-12-07 13:55:55.240  INFO 8624 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at: http://localhost:8888
2017-12-07 13:55:56.317  WARN 8624 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Could not locate PropertySource: I/O error on GET request for "http://localhost:8888/hpx-delivery-report/default": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
2017-12-07 13:55:56.318  INFO 8624 --- [           main] c.p.i.m.s.b.uniqueid.EPolicyApplication  : No active profile set, falling back to default profiles: default
2017-12-07 13:55:56.327  INFO 8624 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3dd1dc90: startup date [Thu Dec 07 13:55:56 ICT 2017]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@2a5c8d3f
2017-12-07 13:55:57.518  INFO 8624 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=781352cf-bed8-31d9-a952-be1fa48d68a0
2017-12-07 13:55:57.537  INFO 8624 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2017-12-07 13:55:57.635  INFO 8624 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$d7dcc0e8] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-12-07 13:55:57.671  INFO 8624 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$f3f6c3e5] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-12-07 13:55:57.676  WARN 8624 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
2017-12-07 13:55:57.683  INFO 8624 --- [           main] utoConfigurationReportLoggingInitializer :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-12-07 13:55:57.690 ERROR 8624 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537) ~[spring-context-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at com.prudential.integration.middleware.spring.boot.uniqueid.EPolicyApplication.main(EPolicyApplication.java:10) [classes/:na]
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:189) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:162) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:134) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    ... 8 common frames omitted

before it, I have javax.servlet.api dependency but I think this is the problem, so I remove that dependencies but when I try to run spring boot project, still failed. I also exclude starter tomcat dependencies but still failed. I also see the solution with same problem in stackoverflow too but I can't find the solution.

my pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.prudential.integration.middleware.spring.boot</groupId>
    <artifactId>hpx-aws-letter-unique-id</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>hpx-aws-letter-unique-id</name>
    <description>Hpx Aws Letter Unique Id Service Spring Boot</description>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.6.RELEASE</version>
        <relativePath />
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <swagger.version>2.7.0</swagger.version>
        <jboss.home>${env.JBOSS_HOME}</jboss.home>
        <config.server>http://10.170.49.103/configserver</config.server>
        <spring-cloud.version>1.3.2.RELEASE</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-apt</artifactId>
        </dependency>
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.github.jmnarloch</groupId>
            <artifactId>modelmapper-spring-boot-starter</artifactId>
            <version>1.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.15</version>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6.12</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.6</version>
        </dependency>

        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.54</version>
        </dependency>

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.3</version>
    </dependency>

    <dependency>
    <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20171018</version>
    </dependency>

        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.9</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>${project.name}-${project.version}</finalName>
        <plugins>

            <plugin>
                <groupId>org.jboss.as.plugins</groupId>
                <artifactId>jboss-as-maven-plugin</artifactId>
                <version>7.9.Final</version>
                <configuration>
                    <jbossHome>${jboss.home}</jbossHome>
                    <serverArgs>
                        <serverArg>-Dspring.profiles.active=${run.profiles}</serverArg>
                        <serverArg>-Dspring.cloud.config.uri=${config.server}</serverArg>
                    </serverArgs>
                </configuration>
            </plugin>

            <plugin>
                <groupId>com.mysema.maven</groupId>
                <artifactId>apt-maven-plugin</artifactId>
                <version>1.1.3</version>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <skipTests>true</skipTests>
                </configuration>
            </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>1.5.9.RELEASE</version>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        </plugins>
    </build>
</project>

my controller:

@RestController
@RequestMapping("/hpx")
@Api(value="hpx", description="HPX Web Service")
public class HPXController {

    final static Logger logger = Logger.getLogger(HPXController.class);

    @RequestMapping(value = "/testing", method = RequestMethod.POST)
    public String tesMethod(){
        return "testing method";
    }
}

my configuration:

@SpringBootApplication
public class EPolicyApplication {

    public static void main(String[] args) {
        SpringApplication.run(EPolicyApplication.class, args);
    }
}

servlet:

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(EPolicyApplication.class);
    }

}

Body:
You need spring boot maven plugin to run it using mvn spring-boot:run. Please add below plugin to your pom.xml.

<plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
      <version>1.5.9.RELEASE</version>
      <executions>
        <execution>
          <goals>
            <goal>repackage</goal>
          </goals>
        </execution>
      </executions>
</plugin>

Also make the tomcat dependency as provided so that it wont be added in the war.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

You can modify the goal as per your requirement or remove it.
Then with embedded tomcat you test your application with above commands. To deploy it to external app server you need to package it as a war and copy it to specific directory of your App server (i.e. Jboss EAP).


来源: stackexchange

问:
Learning Python from Ruby; Differences and Similarities
I know Ruby very well. I believe that I may need to learn Python presently. For those who know both, what concepts are similar between the two, and what are different?

I'm looking for a list similar to a primer I wrote for Learning Lua for JavaScripters: simple things like whitespace significance and looping constructs; the name of nil in Python, and what values are considered "truthy"; is it idiomatic to use the equivalent of map and each, or are mumble somethingaboutlistcomprehensions mumble the norm?

If I get a good variety of answers I'm happy to aggregate them into a community wiki. Or else  you all can fight and crib from each other to try to create the one true comprehensive list.

Edit: To be clear, my goal is "proper" and idiomatic Python. If there is a Python equivalent of inject, but nobody uses it because there is a better/different way to achieve the common functionality of iterating a list and accumulating a result along the way, I want to know how you do things. Perhaps I'll update this question with a list of common goals, how you achieve them in Ruby, and ask what the equivalent is in Python.

答:
Here are some key differences to me:

Ruby has blocks; Python does not.

Python has functions; Ruby does not.  In Python, you can take any function or method and pass it to another function.  In Ruby, everything is a method, and methods can't be directly passed.  Instead, you have to wrap them in Proc's to pass them.

Ruby and Python both support closures, but in different ways.  In Python, you can define a function inside another function.  The inner function has read access to variables from the outer function, but not write access.  In Ruby, you define closures using blocks.  The closures have full read and write access to variables from the outer scope.

Python has list comprehensions, which are pretty expressive.  For example, if you have a list of numbers, you can write

```<code>[x*x for x in values if x > 15]
</code>```

to get a new list of the squares of all values greater than 15.  In Ruby, you'd have to write the following:

```<code>values.select {|v| v > 15}.map {|v| v * v}
</code>```

The Ruby code doesn't feel as compact.  It's also not as efficient since it first converts the values array into a shorter intermediate array containing the values greater than 15.  Then, it takes the intermediate array and generates a final array containing the squares of the intermediates.  The intermediate array is then thrown out.  So, Ruby ends up with 3 arrays in memory during the computation; Python only needs the input list and the resulting list.

Python also supplies similar map comprehensions.

Python supports tuples; Ruby doesn't.  In Ruby, you have to use arrays to simulate tuples.

Ruby supports switch/case statements; Python does not.

Ruby supports the standard expr ? val1 : val2 ternary operator; Python does not.

Ruby supports only single inheritance.  If you need to mimic multiple inheritance, you can define modules and use mix-ins to pull the module methods into classes.  Python supports multiple inheritance rather than module mix-ins.

Python supports only single-line lambda functions.  Ruby blocks, which are kind of/sort of lambda functions, can be arbitrarily big.  Because of this, Ruby code is typically written in a more functional style than Python code.  For example, to loop over a list in Ruby, you typically do

```<code>collection.each do |value|
  ...
end
</code>```

The block works very much like a function being passed to collection.each.  If you were to do the same thing in Python, you'd have to define a named inner function and then pass that to the collection each method (if list supported this method):

```<code>def some_operation(value):
  ...

collection.each(some_operation)
</code>```

That doesn't flow very nicely.  So, typically the following non-functional approach would be used in Python:

```<code>for value in collection:
  ...
</code>```

Using resources in a safe way is quite different between the two languages.  Here, the problem is that you want to allocate some resource (open a file, obtain a database cursor, etc), perform some arbitrary operation on it, and then close it in a safe manner even if an exception occurs.

In Ruby, because blocks are so easy to use (see #9), you would typically code this pattern as a method that takes a block for the arbitrary operation to perform on the resource.

In Python, passing in a function for the arbitrary action is a little clunkier since you have to write a named, inner function (see #9).  Instead, Python uses a with statement for safe resource handling.  See How do I correctly clean up a Python object? for more details.

ContentLicense: CC BY-SA 2.5

Body:
Here are some key differences to me:

Ruby has blocks; Python does not.

Python has functions; Ruby does not.  In Python, you can take any function or method and pass it to another function.  In Ruby, everything is a method, and methods can't be directly passed.  Instead, you have to wrap them in Proc's to pass them.

Ruby and Python both support closures, but in different ways.  In Python, you can define a function inside another function.  The inner function has read access to variables from the outer function, but not write access.  In Ruby, you define closures using blocks.  The closures have full read and write access to variables from the outer scope.

Python has list comprehensions, which are pretty expressive.  For example, if you have a list of numbers, you can write

[x*x for x in values if x > 15]

to get a new list of the squares of all values greater than 15.  In Ruby, you'd have to write the following:

values.select {|v| v > 15}.map {|v| v * v}

The Ruby code doesn't feel as compact.  It's also not as efficient since it first converts the values array into a shorter intermediate array containing the values greater than 15.  Then, it takes the intermediate array and generates a final array containing the squares of the intermediates.  The intermediate array is then thrown out.  So, Ruby ends up with 3 arrays in memory during the computation; Python only needs the input list and the resulting list.

Python also supplies similar map comprehensions.

Python supports tuples; Ruby doesn't.  In Ruby, you have to use arrays to simulate tuples.

Ruby supports switch/case statements; Python does not.

Ruby supports the standard expr ? val1 : val2 ternary operator; Python does not.

Ruby supports only single inheritance.  If you need to mimic multiple inheritance, you can define modules and use mix-ins to pull the module methods into classes.  Python supports multiple inheritance rather than module mix-ins.

Python supports only single-line lambda functions.  Ruby blocks, which are kind of/sort of lambda functions, can be arbitrarily big.  Because of this, Ruby code is typically written in a more functional style than Python code.  For example, to loop over a list in Ruby, you typically do

collection.each do |value|
  ...
end

The block works very much like a function being passed to collection.each.  If you were to do the same thing in Python, you'd have to define a named inner function and then pass that to the collection each method (if list supported this method):

def some_operation(value):
  ...

collection.each(some_operation)

That doesn't flow very nicely.  So, typically the following non-functional approach would be used in Python:

for value in collection:
  ...

Using resources in a safe way is quite different between the two languages.  Here, the problem is that you want to allocate some resource (open a file, obtain a database cursor, etc), perform some arbitrary operation on it, and then close it in a safe manner even if an exception occurs.

In Ruby, because blocks are so easy to use (see #9), you would typically code this pattern as a method that takes a block for the arbitrary operation to perform on the resource.

In Python, passing in a function for the arbitrary action is a little clunkier since you have to write a named, inner function (see #9).  Instead, Python uses a with statement for safe resource handling.  See How do I correctly clean up a Python object? for more details.

ContentLicense: CC BY-SA 3.0


问:
How to set the value and text in a Spinner from a string list?
i am working on android spinner control. i already have populate list of string to show in spinner like

```<code>String[] items = new String[]{ "Office", "Home", "College", "Uncle's Home", "CoDebuggers"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
        SpinnerName.setAdapter(adapter);
</code>```

this is working well but i need to add unique id for my list like

Office = 4

Home = 8

College = 9

Uncle's Home = 10

CoDebiggers = 55

how can i set there value with String list?
and how can i get these values by selected item change?

答:
You have to create two array, one for the items and second for the item's value.

```<code>String[] items = new String[]{ "Office", "Home", "College", "Uncle's Home", "CoDebuggers"};
int[] items_value = new String[]{ 4, 8, 9, 10, 55};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
SpinnerName.setAdapter(adapter);
</code>```

Get spinner selected item respective value from value array:

int value = items_value[SpinnerName.getSelectedItemPosition()];

Body:
i am working on android spinner control. i already have populate list of string to show in spinner like

String[] items = new String[]{ "Office", "Home", "College", "Uncle's Home", "CoDebuggers"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
        SpinnerName.setAdapter(adapter);

this is working well but i need to add unique id for my list like

Office = 4

Home = 8

College = 9

Uncle's Home = 10

CoDebiggers = 55

how can i set there value with String list?
and how can i get these values by selected item change?

Body:
You have to create two array, one for the items and second for the item's value.

String[] items = new String[]{ "Office", "Home", "College", "Uncle's Home", "CoDebuggers"};
int[] items_value = new String[]{ 4, 8, 9, 10, 55};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
SpinnerName.setAdapter(adapter);

Get spinner selected item respective value from value array:

int value = items_value[SpinnerName.getSelectedItemPosition()];


问:
Git: get number of changed lines per day
I'd like to make a diagram of added/removed/changed lines in a git repository per day and/or week. I do not want to count the number of commits.

Is there a tool that can produce such charts (gitstats does not)? Or, with which git command I can produce an output which i could parse easily?

Thank you!

答:
My version of above scripts, for stats per days, with nice formatted output ...</p>

```<code>#!/bin/bash
# Calculate num of changed, new lines on git per days (show your productivity)

ds() {
  date --date="$1 days ago" +%Y-%m-%d
}

echo "GIT changes stat: Date, Total lines modified (New added, Changed)"
for week in {13..0}
do
  # git log outputs lines like:
  # 11        10      path/to/your/file.java
  #  => add first two columns with awk
  lines_all=$(git --no-pager log --after=$(ds $week) --before=$(ds $(($week - 1))) --format=format: --numstat | awk '{s+=$1; s+=$2} END {print s/1}')
  lines_chg=$(git --no-pager log --after=$(ds $week) --before=$(ds $(($week - 1))) --format=format: --numstat | awk '{s+=$1;} END {print s/1}')
  lines_new=$(git --no-pager log --after=$(ds $week) --before=$(ds $(($week - 1))) --format=format: --numstat | awk '{s+=$2}  END {print s/1}')
  #echo -e "$(ds $week): $lines_all \t\t(new: $lines_new, \tchanged: $lines_chg)"
  printf "%10s: %10s \t\t(new: %10s, \tchanged: %10s)\n" $(ds $week) $lines_all $lines_new $lines_chg
done
</code>```

Body:
My version of above scripts, for stats per days, with nice formatted output ...

#!/bin/bash
# Calculate num of changed, new lines on git per days (show your productivity)

ds() {
  date --date="$1 days ago" +%Y-%m-%d
}

echo "GIT changes stat: Date, Total lines modified (New added, Changed)"
for week in {13..0}
do
  # git log outputs lines like:
  # 11        10      path/to/your/file.java
  #  => add first two columns with awk
  lines_all=$(git --no-pager log --after=$(ds $week) --before=$(ds $(($week - 1))) --format=format: --numstat | awk '{s+=$1; s+=$2} END {print s/1}')
  lines_chg=$(git --no-pager log --after=$(ds $week) --before=$(ds $(($week - 1))) --format=format: --numstat | awk '{s+=$1;} END {print s/1}')
  lines_new=$(git --no-pager log --after=$(ds $week) --before=$(ds $(($week - 1))) --format=format: --numstat | awk '{s+=$2}  END {print s/1}')
  #echo -e "$(ds $week): $lines_all \t\t(new: $lines_new, \tchanged: $lines_chg)"
  printf "%10s: %10s \t\t(new: %10s, \tchanged: %10s)\n" $(ds $week) $lines_all $lines_new $lines_chg
done


问:
How to use a fixed point sin function in Vivado HLS
I am calculating the intersection point of two lines given in the polar coordinate system:

typedef ap_fixed<16,3,AP_RND> t_lines_angle;
typedef ap_fixed<16,14,AP_RND> t_lines_rho;

bool get_intersection(
        hls::Polar_< t_lines_angle, t_lines_rho>* lineOne,
        hls::Polar_< t_lines_angle, t_lines_rho>* lineTwo,
        Point* point)
{
    float angleL1 = lineOne->angle.to_float();
    float angleL2 = lineTwo->angle.to_float();
    t_lines_angle rhoL1 = lineOne->rho.to_float();
    t_lines_angle rhoL2 = lineTwo->rho.to_float();
    t_lines_angle ct1=cosf(angleL1);
    t_lines_angle st1=sinf(angleL1);
    t_lines_angle ct2=cosf(angleL2);
    t_lines_angle st2=sinf(angleL2);
    t_lines_angle d=ct1*st2-st1*ct2;

    // we make sure that the lines intersect
    // which means that parallel lines are not possible
    point->X = (int)((st2*rhoL1-st1*rhoL2)/d);
    point->Y = (int)((-ct2*rhoL1+ct1*rhoL2)/d);

    return true;
}
```

After synthesis for our FPGA I saw that the 4 implementations of the float sine (and cos) take 4800 LUTs per implementation, which sums up to 19000 LUTs for these 4 functions. I want to reduce the LUT count by using a fixed point sine. I already found a implementation of CORDIC but I am not sure how to use it. The input of the function is an integer but i have a ap_fixed datatype. How can I map this ap_fixed to integer? and how can I map my 3.13 fixed point to the required 2.14 fixed point?

答:
With the help of one of my colleagues I figured out a quite easy solution that does not require any hand written implementations or manipulation of the fixed point data:

use #include "hls_math.h" and the hls::sinf() and hls::cosf() functions.

It is important to say that the input of the functions should be ap_fixed<32, I> where I <= 32. The output of the functions can be assigned to different types e.g., ap_fixed<16, I>

Example:

```<code>void CalculateSomeTrig(ap_fixed<16,5>* angle, ap_fixed<16,5>* output)
{
    ap_fixed<32,5> functionInput = *angle;
    *output = hls::sinf(functionInput);
}
</code>```

LUT consumption:

In my case the consumption of LUT was reduced to 400 LUTs for each implementation of the function.

Body:
I am calculating the intersection point of two lines given in the polar coordinate system:

typedef ap_fixed<16,3,AP_RND> t_lines_angle;
typedef ap_fixed<16,14,AP_RND> t_lines_rho;

bool get_intersection(
        hls::Polar_< t_lines_angle, t_lines_rho>* lineOne,
        hls::Polar_< t_lines_angle, t_lines_rho>* lineTwo,
        Point* point)
{
    float angleL1 = lineOne->angle.to_float();
    float angleL2 = lineTwo->angle.to_float();
    t_lines_angle rhoL1 = lineOne->rho.to_float();
    t_lines_angle rhoL2 = lineTwo->rho.to_float();
    t_lines_angle ct1=cosf(angleL1);
    t_lines_angle st1=sinf(angleL1);
    t_lines_angle ct2=cosf(angleL2);
    t_lines_angle st2=sinf(angleL2);
    t_lines_angle d=ct1*st2-st1*ct2;

    // we make sure that the lines intersect
    // which means that parallel lines are not possible
    point->X = (int)((st2*rhoL1-st1*rhoL2)/d);
    point->Y = (int)((-ct2*rhoL1+ct1*rhoL2)/d);

    return true;
}

After synthesis for our FPGA I saw that the 4 implementations of the float sine (and cos) take 4800 LUTs per implementation, which sums up to 19000 LUTs for these 4 functions. I want to reduce the LUT count by using a fixed point sine. I already found a implementation of CORDIC but I am not sure how to use it. The input of the function is an integer but i have a ap_fixed datatype. How can I map this ap_fixed to integer? and how can I map my 3.13 fixed point to the required 2.14 fixed point?

Body:
With the help of one of my colleagues I figured out a quite easy solution that does not require any hand written implementations or manipulation of the fixed point data:

use #include "hls_math.h" and the hls::sinf() and hls::cosf() functions.

It is important to say that the input of the functions should be ap_fixed<32, I> where I <= 32. The output of the functions can be assigned to different types e.g., ap_fixed<16, I>

Example:

void CalculateSomeTrig(ap_fixed<16,5>* angle, ap_fixed<16,5>* output)
{
    ap_fixed<32,5> functionInput = *angle;
    *output = hls::sinf(functionInput);
}

LUT consumption:

In my case the consumption of LUT was reduced to 400 LUTs for each implementation of the function.


问:
How to delete a node that has been found
I'm working on a binary search tree where i have to delete a node. The node has already been found, so i don't need to traverse and find the specific node. All i need is to delete a node, which is taken as an arguement.

I have started the the node remove method and currently only done how to delete a node if it has no children or is a leaf node. How do i implement a java code which will delete if it has 1 children or a parent?

my current remove method:

```<code>public void removeHelper(Node focus){

        if(focus.leftChild == null && focus.rightChild == null){
            focus = null;
        }

        // if the node has 1 child

        // if the node has 2 children

    }
</code>```

答:
You need to travel down the tree, because you will need to replace the root field, or either the leftChild or rightChild of the parent node.

To remove a node that has both leftChild and rightChild not null, you can replace the node with either the rightmost node of the left subtree, or the leftmost node of the right subtree.

In this example, I assume that the methods are in a class (Tree?) that have a Node field called root, and that the Nodes have a field value that is a Comparable:

```<code>public void remove(Node focus) {
    root = removeHelper(root, focus);
}

public static Node removeHelper(Node root, Node focus) {
    if (root == null) {
        return null;
    } else if (root == focus) {
        if (focus.leftChild == null) {
            return focus.rightChild;
        } else if (focus.rightChild == null) {
            return focus.leftChild;
        } else {
            Node node = removeLeftMostOfRight(focus);
            node.leftChild = focus.leftChild;
            node.rightChild = focus.rightChild;
            return node;
        }
    } else {
        int r = focus.value.compareTo(root.value);
        if (r < 0) {
            root.leftChild = removeHelper(root.leftChild, focus);
        } else {
            root.rightChild = removeHelper(root.rightChild, focus);
        }
        return root;
    }
}

private static Node removeLeftMostOfRight(Node focus) {
    Node node = focus.rightChild;
    if (node.leftChild == null) {
        focus.rightChild = node.rightChild;
    } else {
        Node prev;
        do {
            prev = node;
            node = node.leftChild;
        } while (node.leftChild != null);
        prev.leftChild = node.rightChild;
    }
    return node;
}
</code>```

Note that in languages like C/C++ you can have pointers to pointer, that allow a much simpler and more efficient implementation of binary trees.

Body:
I'm working on a binary search tree where i have to delete a node. The node has already been found, so i don't need to traverse and find the specific node. All i need is to delete a node, which is taken as an arguement.

I have started the the node remove method and currently only done how to delete a node if it has no children or is a leaf node. How do i implement a java code which will delete if it has 1 children or a parent?

my current remove method:

public void removeHelper(Node focus){

        if(focus.leftChild == null && focus.rightChild == null){
            focus = null;
        }

        // if the node has 1 child

        // if the node has 2 children

    }

Body:
You need to travel down the tree, because you will need to replace the root field, or either the leftChild or rightChild of the parent node.

To remove a node that has both leftChild and rightChild not null, you can replace the node with either the rightmost node of the left subtree, or the leftmost node of the right subtree.

In this example, I assume that the methods are in a class (Tree?) that have a Node field called root, and that the Nodes have a field value that is a Comparable:

public void remove(Node focus) {
    root = removeHelper(root, focus);
}

public static Node removeHelper(Node root, Node focus) {
    if (root == null) {
        return null;
    } else if (root == focus) {
        if (focus.leftChild == null) {
            return focus.rightChild;
        } else if (focus.rightChild == null) {
            return focus.leftChild;
        } else {
            Node node = removeLeftMostOfRight(focus);
            node.leftChild = focus.leftChild;
            node.rightChild = focus.rightChild;
            return node;
        }
    } else {
        int r = focus.value.compareTo(root.value);
        if (r < 0) {
            root.leftChild = removeHelper(root.leftChild, focus);
        } else {
            root.rightChild = removeHelper(root.rightChild, focus);
        }
        return root;
    }
}

private static Node removeLeftMostOfRight(Node focus) {
    Node node = focus.rightChild;
    if (node.leftChild == null) {
        focus.rightChild = node.rightChild;
    } else {
        Node prev;
        do {
            prev = node;
            node = node.leftChild;
        } while (node.leftChild != null);
        prev.leftChild = node.rightChild;
    }
    return node;
}

Note that in languages like C/C++ you can have pointers to pointer, that allow a much simpler and more efficient implementation of binary trees.


问:
ASP.Net - Masked first 6 character on a string with dynamic length
is it possible to masked a first 6 characters on a string if the string is dynamics on it's length?

Example, I have a string "test123456789" and I want a result of "******3456789" or a string of "1234test" and I want a result of "******st". All I'm seeing sample codes here in masking are strings with a static length. Can anyone kindly help me with this? Thank you so much in advance.

答:
Yes, it's possible, and even quite easy, using simple string concatenation and SubString:

```<code>var original = "Some string here";
var target = "******" + ((original.Length > 6) ? original.Substring(6) : "") ;
</code>```

If you want shorter strings to mask all characters but keep original length, you can do it like this:

```<code>var target = new string('*', Math.Min(original.Length, 6)) + ((original.Length > 6) ? original.Substring(6) : "") ;
</code>```

This way, an input of "123" would return 3 asterisks ("***"). The first code I've shown will return 6 asterisks ("******")

Body:
Yes, it's possible, and even quite easy, using simple string concatenation and SubString:

var original = "Some string here";
var target = "******" + ((original.Length > 6) ? original.Substring(6) : "") ;

If you want shorter strings to mask all characters but keep original length, you can do it like this:

var target = new string('*', Math.Min(original.Length, 6)) + ((original.Length > 6) ? original.Substring(6) : "") ;

This way, an input of "123" would return 3 asterisks ("***"). The first code I've shown will return 6 asterisks ("******")


问:
Python Web Scrape Unknown Number of Pages
I have working code that scrapes a single Craigslist page for specific information, but what would I need to add in order to grab the data from ALL of the pages (not knowing how many pages ahead of time)?</p>

```<code>from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url="https://portland.craigslist.org/search/sss?query=electronics&sort=date"
uClient=uReq(my_url) #sends GET request to URL
page_html=uClient.read() #reads returned data and puts it in a variable
uClient.close() #close the connection

#create a file that we will want later to write parsed data to
filename="ScrapedData.csv"
f=open(filename, 'w')
headers="date, location, title, price\n"
f.write(headers)

#use BS to parse the webpage
page_soup=soup(page_html,'html.parser') #applying BS to the obtained html
containers=page_soup.findAll('p',{'class','result-info'})

for container in containers:
    container_date=container.findAll('time',{'class','result-date'})
    date=container_date[0].text
    try:
        container_location=container.findAll('span',{'class','result-hood'})
        location=container_location[0].text
    except:
        try:
            container_location=container.findAll('span',{'class','nearby'})
            location=container_location[0].text
        except:
            location='NULL'
    container_title=container.findAll('a',{'class','result-title'})
    title=container_title[0].text
    try:
        container_price=container.findAll('span',{'class','result-price'})
        price=container_price[0].text
    except:
        price='NULL'

    #to print to screen
    print('date:'+date)
    print('location:'+location)
    print('title:'+title)
    print('price:'+price)
    #to write to csv
    f.write(date+','+location.replace(",","-")+','+title.replace(","," ")+','+price+'\n')

f.close()
</code>```

答:
You can try to loop through all pages by handling "s" parameter in URL until you find page with no results (page with text "search and you will find"):

```<code>import requests

results_counter = 0
while True:
    my_url="https://portland.craigslist.org/search/sss?query=electronics&sort=date&s=%d" % results_counter
    page_html = requests.get(my_url).text
    if "search and you will find" in page_html:
        break
    else:
        results_counter += 120

        filename="ScrapedData.csv"
        f=open(filename, 'w')
        headers="date, location, title, price\n"
        f.write(headers)

        page_soup=soup(page_html,'html.parser') #applying BS to the obtained html
        containers=page_soup.findAll('p',{'class','result-info'})
        ...
</code>```

Body:
I have working code that scrapes a single Craigslist page for specific information, but what would I need to add in order to grab the data from ALL of the pages (not knowing how many pages ahead of time)?

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url="https://portland.craigslist.org/search/sss?query=electronics&sort=date"
uClient=uReq(my_url) #sends GET request to URL
page_html=uClient.read() #reads returned data and puts it in a variable
uClient.close() #close the connection

#create a file that we will want later to write parsed data to
filename="ScrapedData.csv"
f=open(filename, 'w')
headers="date, location, title, price\n"
f.write(headers)

#use BS to parse the webpage
page_soup=soup(page_html,'html.parser') #applying BS to the obtained html
containers=page_soup.findAll('p',{'class','result-info'})

for container in containers:
    container_date=container.findAll('time',{'class','result-date'})
    date=container_date[0].text
    try:
        container_location=container.findAll('span',{'class','result-hood'})
        location=container_location[0].text
    except:
        try:
            container_location=container.findAll('span',{'class','nearby'})
            location=container_location[0].text
        except:
            location='NULL'
    container_title=container.findAll('a',{'class','result-title'})
    title=container_title[0].text
    try:
        container_price=container.findAll('span',{'class','result-price'})
        price=container_price[0].text
    except:
        price='NULL'

    #to print to screen
    print('date:'+date)
    print('location:'+location)
    print('title:'+title)
    print('price:'+price)
    #to write to csv
    f.write(date+','+location.replace(",","-")+','+title.replace(","," ")+','+price+'\n')

f.close()

Body:
You can try to loop through all pages by handling "s" parameter in URL until you find page with no results (page with text "search and you will find"):

import requests

results_counter = 0
while True:
    my_url="https://portland.craigslist.org/search/sss?query=electronics&sort=date&s=%d" % results_counter
    page_html = requests.get(my_url).text
    if "search and you will find" in page_html:
        break
    else:
        results_counter += 120

        filename="ScrapedData.csv"
        f=open(filename, 'w')
        headers="date, location, title, price\n"
        f.write(headers)

        page_soup=soup(page_html,'html.parser') #applying BS to the obtained html
        containers=page_soup.findAll('p',{'class','result-info'})
        ...


问:
ST_contains taking too much time
I am trying to match latitude/longitude to a particular neighbor location using below query

```<code>create table address_classification as (
select distinct buildingid,street,city,state,neighborhood,borough
from master_data
join
Borough_GEOM
on st_contains(st_astext(geom),coordinates) = 'true'
);
</code>```

In this, coordinates is of below format

```<code>ST_GeometryFromText('POINT('||longitude||' '||latitude||')') as coordinates
</code>```

and geom is of column type geometry.

i have already created indexes as below

```<code>CREATE INDEX coordinates_gix ON master_data USING GIST (coordinates);
CREATE INDEX boro_geom_indx ON Borough_GEOM USING gist(geom);
</code>```

I have almost 3 million records in the main table and 200 geometric information in the GEOM table. Explain analyze of the query is taking so much time (2 hrs).
Please let me know, how can i optimize this query.

Thanks in advance.

答:
As mentioned in the comments, don't use ST_AsText(): that doesn't belong there. It's casting the geom to text, and then going back to geom. But, more importantly, that process is likely to fumble the index.

If you're unique on only column then use DISTINCT ON, no need to compare the others.

If you're unique on the ID column and your only joining to add selectivity then consider using EXISTS. Do any of these columns come from the borough_GEOM other than geom?

I'd start with something like this,

```<code>CREATE TABLE address_classification AS
  SELECT DISTINCT ON (buildingid),
    buildingid,
    street,
    city,
    state,
    neighborhood,
    borough
  FROM master_data
  JOIN borough_GEOM
    ON ST_Contains(geom,coordinates);
</code>```

Title: ST_contains taking too much time

Body:
I am trying to match latitude/longitude to a particular neighbor location using below query

create table address_classification as (
select distinct buildingid,street,city,state,neighborhood,borough
from master_data
join
Borough_GEOM
on st_contains(st_astext(geom),coordinates) = 'true'
);

In this, coordinates is of below format

ST_GeometryFromText('POINT('||longitude||' '||latitude||')') as coordinates

and geom is of column type geometry.

i have already created indexes as below

CREATE INDEX coordinates_gix ON master_data USING GIST (coordinates);
CREATE INDEX boro_geom_indx ON Borough_GEOM USING gist(geom);

I have almost 3 million records in the main table and 200 geometric information in the GEOM table. Explain analyze of the query is taking so much time (2 hrs).
Please let me know, how can i optimize this query.

Thanks in advance.

Body:
As mentioned in the comments, don't use ST_AsText(): that doesn't belong there. It's casting the geom to text, and then going back to geom. But, more importantly, that process is likely to fumble the index.

If you're unique on only column then use DISTINCT ON, no need to compare the others.

If you're unique on the ID column and your only joining to add selectivity then consider using EXISTS. Do any of these columns come from the borough_GEOM other than geom?

I'd start with something like this,

CREATE TABLE address_classification AS
  SELECT DISTINCT ON (buildingid),
    buildingid,
    street,
    city,
    state,
    neighborhood,
    borough
  FROM master_data
  JOIN borough_GEOM
    ON ST_Contains(geom,coordinates);


问:
How to hide textarea if input is empty
How do I use jQuery to hide textarea if input text is empty?

My attempt:

```<code>jQuery(document).chnage(function($) {
    var value=$.trim($('input').val());

    if (value.length < 0) {
        $('textarea[name="your-message"]').hide();
    }
});
</code>```

答:
Your real problem is that you redefine $ with another value:

```<code>jQuery(document).change(function($) {
   // remove this bad boy -------^
   // $ is jQuery.Event object here
});
</code>```

The first parameter to event handler is going to be jQuery.Event object, not jQuery itself.

Remove $ from parameter list and use value.length == 0 it will work.

Title: How to hide textarea if input is empty

Body:
How do I use jQuery to hide textarea if input text is empty?

My attempt:

jQuery(document).chnage(function($) {
    var value=$.trim($('input').val());

    if (value.length < 0) {
        $('textarea[name="your-message"]').hide();
    }
});

Body:
Your real problem is that you redefine $ with another value:

jQuery(document).change(function($) {
   // remove this bad boy -------^
   // $ is jQuery.Event object here
});

The first parameter to event handler is going to be jQuery.Event object, not jQuery itself.

Remove $ from parameter list and use value.length == 0 it will work.


问:
Is it possible to save HTML page as PDF using JavaScript or jquery?
Is it possible to save HTML page as PDF using JavaScript or jquery?

In Detail:

I generated one HTML Page which contains a table . It has one button 'save as PDF'. If user clicks that button then that HTML page has to convert as PDF file.

Is it possible using JavaScript or jquery?

答:
$('#cmd2').click(function() {
   var options = {
  //'width': 800,
   };
   var pdf = new jsPDF('p', 'pt', 'a4');
   pdf.addHTML($("#content2"), -1, 220, options, function() {
     pdf.save('admit_card.pdf');
   });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>

<div id="content2" style="background: #fff;border-bottom: 1px solid #ffffff;">
                     <div class="tokenDet" style="padding: 15px;border: 1px solid #000;width: 80%;margin: 0 auto;position: relative;overflow: hidden;">
                         <div class="title" style="text-align: center;border-bottom: 1px solid #000;margin-bottom: 15px;">
                             <h2>Entrance Exam Hall Ticket</h2>
                            </div>
                            <div class="parentdiv" style="display: inline-block;width: 100%;position: relative;">
                             <div class="innerdiv" style="width: 80%;float: left;">
                              <div class="restDet">
                                        <div class="div">
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>Name</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>Santanu Patra</span>
                                            </div>
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>D.O.B.</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>17th April, 1995</span>
                                            </div>
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>Address</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>P.S. Srijan Corporate Park, Saltlake, Sector 5, Kolkata-91</span>
                                            </div>
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>Contact Number</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>9874563210</span>
                                            </div>
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>Email Id</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>santanu@macallied.com</span>
                                            </div>
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>Parent(s) Name</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>S. Patra</span><br /><span>7896541230</span>
                                            </div>
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>Exam Center</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>Institute of Engineering & Management</span>
                                            </div>
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>Hall Number</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>COM-32</span>
                                            </div>
                                        </div>
                                    </div>
                             </div>
                                <div class="sideDiv" style="width: 20%;float: left;">
                                 <div class="atts" style="float: left;width: 100%;">
                                     <div class="photo" style="width: 115px;height: 150px;float: right;">
                                         <img src="images/candidateImg.gif" style="width: 100%;"/>
                                        </div>
                                        <div class="sign" style="position: absolute;bottom: 0;right: 0;border-top: 1px dashed #000;left: 80%;text-align: right;">
                                         <small>Self Attested</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <button class="btn btn-info" id="cmd2">Download Token</button></code>```

Body:
$('#cmd2').click(function() {
   var options = {
  //'width': 800,
   };
   var pdf = new jsPDF('p', 'pt', 'a4');
   pdf.addHTML($("#content2"), -1, 220, options, function() {
     pdf.save('admit_card.pdf');
   });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>

<div id="content2" style="background: #fff;border-bottom: 1px solid #ffffff;">
                     <div class="tokenDet" style="padding: 15px;border: 1px solid #000;width: 80%;margin: 0 auto;position: relative;overflow: hidden;">
                         <div class="title" style="text-align: center;border-bottom: 1px solid #000;margin-bottom: 15px;">
                             <h2>Entrance Exam Hall Ticket</h2>
                            </div>
                            <div class="parentdiv" style="display: inline-block;width: 100%;position: relative;">
                             <div class="innerdiv" style="width: 80%;float: left;">
                              <div class="restDet">
                                        <div class="div">
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>Name</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>Santanu Patra</span>
                                            </div>
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>D.O.B.</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>17th April, 1995</span>
                                            </div>
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>Address</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>P.S. Srijan Corporate Park, Saltlake, Sector 5, Kolkata-91</span>
                                            </div>
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>Contact Number</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>9874563210</span>
                                            </div>
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>Email Id</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>santanu@macallied.com</span>
                                            </div>
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>Parent(s) Name</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>S. Patra</span><br /><span>7896541230</span>
                                            </div>
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>Exam Center</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>Institute of Engineering & Management</span>
                                            </div>
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>Hall Number</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>COM-32</span>
                                            </div>
                                        </div>
                                    </div>
                             </div>
                                <div class="sideDiv" style="width: 20%;float: left;">
                                 <div class="atts" style="float: left;width: 100%;">
                                     <div class="photo" style="width: 115px;height: 150px;float: right;">
                                         <img src="images/candidateImg.gif" style="width: 100%;"/>
                                        </div>
                                        <div class="sign" style="position: absolute;bottom: 0;right: 0;border-top: 1px dashed #000;left: 80%;text-align: right;">
                                         <small>Self Attested</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <button class="btn btn-info" id="cmd2">Download Token</button>


问:
How to populate Dropdownlist with server Folder Filenames
I have added a folder in My project With Name (ReportFile) and I am saving xml Files in that Folder.

i want to Show all Xml File Name in a DropDownList
(that are stored in that folder)

My DropDown:

```<code>    <asp:DropDownList ID="ddlReportTemplate" runat="server" AutoPostBack="True">
 </asp:DropDownList>
</code>```

答:
In the Page_Load of the code behind</p>

```<code>    protected void Page_Load(object sender, EventArgs e)
    {
        var reportFolderPath = Server.MapPath("~/Reports"); //change the "~/Reports" to your report folder name

        IEnumerable<string> xmlFiles = Directory.GetFiles(reportFolderPath, "*.xml");

        //As a common practice server file path should not be shown to the client, use file name instead
        xmlFiles = xmlFiles.Select(o => Path.GetFileNameWithoutExtension(o)).Where(o => o.Contains("Arun"));;

        ddlReportTemplate.DataSource = xmlFiles;
        ddlReportTemplate.DataBind();
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have added a folder in My project With Name (ReportFile) and I am saving xml Files in that Folder.

i want to Show all Xml File Name in a DropDownList
(that are stored in that folder)

My DropDown:

    <asp:DropDownList ID="ddlReportTemplate" runat="server" AutoPostBack="True">
 </asp:DropDownList>

Body:
In the Page_Load of the code behind

    protected void Page_Load(object sender, EventArgs e)
    {
        var reportFolderPath = Server.MapPath("~/Reports"); //change the "~/Reports" to your report folder name

        IEnumerable<string> xmlFiles = Directory.GetFiles(reportFolderPath, "*.xml");

        //As a common practice server file path should not be shown to the client, use file name instead
        xmlFiles = xmlFiles.Select(o => Path.GetFileNameWithoutExtension(o)).Where(o => o.Contains("Arun"));;

        ddlReportTemplate.DataSource = xmlFiles;
        ddlReportTemplate.DataBind();
    }


答:
You can substring and mask it. Make sure to check if the input string is lower than 6 as below sample</p>

```<code>    string str = "123456789345798";
    var strResult = "******"+str.Substring(6, str.Length - 6);
    Console.WriteLine("strResult :" + strResult);
</code>```

Title: ASP.Net - Masked first 6 character on a string with dynamic length

Body:
is it possible to masked a first 6 characters on a string if the string is dynamics on it's length?

Example, I have a string "test123456789" and I want a result of "******3456789" or a string of "1234test" and I want a result of "******st". All I'm seeing sample codes here in masking are strings with a static length. Can anyone kindly help me with this? Thank you so much in advance.

Body:
You can substring and mask it. Make sure to check if the input string is lower than 6 as below sample

    string str = "123456789345798";
    var strResult = "******"+str.Substring(6, str.Length - 6);
    Console.WriteLine("strResult :" + strResult);


问:
Wordpress using index.php instead of archive.php
My understanding from reading the WP template hierachy was that when I set my a page as my posts page in settings > reading settings that Wordpress should use archive.php. Instead it uses index.php.

Obviously I could just put my code in index.php and my site will work. But it doesn't seem like best practice, and I can't find any documentation of best (or good) practice.

Why doesn't Wordpress use archive.php in this circumstance?

And would using index.php as my posts page have unintended consequences?

Note: I've been using the _s theme as a base, but I've had the same problem with no theme base or parent.

答: you want to use home.php instead of archive.php as it is blog posts index page (set in WordPress Settings -> Reading). It is also in hierarchy on the third position from bottom.


问:
Why are functions like "Point" / "Rect" / "Bounds" (etc) declared both in Classes and in Types unit?
I have noticed that in Delphi 7 functions like Point / Rect / Bounds (etc) are declared and implemented both in Classes and in system Types unit.

Is there a reason for that? is it also true for newer Delphi versions?

(My guess is that one could use Types unit to avoid the Classes overhead when needed)

答:
In older versions these types and functions were declared in Classes. As the RTL was developed, especially to support cross-platform, it became desirable for the these types to be available to units that did not include Classes.

The Types unit was introduced to enable that. The Types unit has no uses dependencies so can safely be used by any other unit, no matter how low level.

The master declarations were moved to Types, and Classes re-exports these types and functions for the benefit of existing code that imports from Classes. So for instance, SysUtils uses Types, but is not permitted to use Classes. Moving these types and functions to a dependency free unit like Types enables that.

This change was made between Delphi 5 and Delphi 6, which was the start of the Delphi cross-platform developments. In that instance it was Kylix, but the restructuring of the RTL benefited the future cross-platform developments, even though Kylix was abandoned.


问:
Sharepoint Foundation 2013, Azure
I have been trying to install Sharepoint Foundation 2013 in Azure.Its been two days and i have been unable to do so.I could find no tutorials for it that do so via azure.Can someone show me any tutorials?I am trying to install sharepoint foundation in a vm(Microsoft Server 2012).I am just a beginner.Thanks in advance.</p>

答:
Try this tutorial for better understanding and step-by-step configuration

https://absolute-sharepoint.com/2014/10/create-sharepoint-2013-farm-in-azure-step-step.html

Title: Sharepoint Foundation 2013, Azure


问:
Iterate through ObservableCollection of class
I'm assigning values to a class by using ObservableCollection.Class contains MainItems and it's SubItems. Now how can I read all SubItems for each input of MainItem?</p>

```<code> public class MainItems
   {
    public string ItemName { get; set; }
    public ObservableCollection<SubItems> SubItemsList { get; set; }
   }
   public class SubItems
   {
    public string SubItemName { get; set; }
   }

  ObservableCollection<MainItems> _data = new   ObservableCollection<MainItems>();
        for (int i = 1; i <= 5; i++)
        {
            MainItems _mainItems = new MainItems();
            _mainItems.ItemName = "Main" + i.ToString();
            _mainItems.SubItemsList = new ObservableCollection<SubItems>();
            for (int j = 1; j <= 3; j++)
            {
                SubItems _subItems = new SubItems()
                {
                    SubItemName = "SubItem" + i.ToString()
                };
                _mainItems.SubItemsList.Add(_subItems);
            }
            _data.Add(_mainItems);
        }
</code>```

答:
The foreach loop alway honors the collections(List, Array, Dictionary(special), ...) boundaries and iterates over all Elements, so its the shortest way to achieve what you want. It disallows you to add/remove elements from the currently iterated collection. In this case the classic for loop is your friend.

Full description from Microsoft:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/foreach-in

Based on Fangs comment:

```<code>// foreach Version
foreach (MainItems mainItem in _data)
{
    foreach (SubItems subItems in mainItem.SubItemsList)
    {
        Console.WriteLine($"{mainItem.ItemName} has a child {subItems.SubItemName}!");
    }
}

// for Version
for (int i = 0; i < _data.Count; i++)
{
    MainItems mainItem = _data[i];
    for (int k = 0; k < mainItem.SubItemsList.Count; k++)
    {
        SubItems subItem = mainItem.SubItemsList[k];
        Console.WriteLine($"{mainItem.ItemName} has a child {subItem.SubItemName}!");
    }
}
</code>```

Body:
I'm assigning values to a class by using ObservableCollection.Class contains MainItems and it's SubItems. Now how can I read all SubItems for each input of MainItem?

 public class MainItems
   {
    public string ItemName { get; set; }
    public ObservableCollection<SubItems> SubItemsList { get; set; }
   }
   public class SubItems
   {
    public string SubItemName { get; set; }
   }

  ObservableCollection<MainItems> _data = new   ObservableCollection<MainItems>();
        for (int i = 1; i <= 5; i++)
        {
            MainItems _mainItems = new MainItems();
            _mainItems.ItemName = "Main" + i.ToString();
            _mainItems.SubItemsList = new ObservableCollection<SubItems>();
            for (int j = 1; j <= 3; j++)
            {
                SubItems _subItems = new SubItems()
                {
                    SubItemName = "SubItem" + i.ToString()
                };
                _mainItems.SubItemsList.Add(_subItems);
            }
            _data.Add(_mainItems);
        }

Body:
The foreach loop alway honors the collections(List, Array, Dictionary(special), ...) boundaries and iterates over all Elements, so its the shortest way to achieve what you want. It disallows you to add/remove elements from the currently iterated collection. In this case the classic for loop is your friend.

Full description from Microsoft:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/foreach-in

Based on Fangs comment:

// foreach Version
foreach (MainItems mainItem in _data)
{
    foreach (SubItems subItems in mainItem.SubItemsList)
    {
        Console.WriteLine($"{mainItem.ItemName} has a child {subItems.SubItemName}!");
    }
}

// for Version
for (int i = 0; i < _data.Count; i++)
{
    MainItems mainItem = _data[i];
    for (int k = 0; k < mainItem.SubItemsList.Count; k++)
    {
        SubItems subItem = mainItem.SubItemsList[k];
        Console.WriteLine($"{mainItem.ItemName} has a child {subItem.SubItemName}!");
    }
}


问:
ASP.NET MVC CSS fails
CSS wizards, show me the light please. Trying to apply my own stylesheet (table formatting) in an MVC project but I think I'm missing something as nothing happens.

index.html:

```<code><link rel="stylesheet" href="~/Content/mystuff.css">
</code>```

BundleConfig:

```<code>bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css",
                      "~/Content/mystuff.css"));
</code>```

Despite this setup, bootstrap still seems to override my own settings. Am I missing any reference? Thanks a bunch

答:
You must Render this bundle inside the View.
 @Styles.Render("~/Content/css")

You can also use dev tools that mozilla offers and see each element in order to understand where Override can happen.

If you want to override bootstrap, use media queries (selectors). Example:

```<code>@media (min-width: 768px) {
  .navbar-header {
    float: right;
  }
}
</code>```

Title: ASP.NET MVC CSS fails

Body:
CSS wizards, show me the light please. Trying to apply my own stylesheet (table formatting) in an MVC project but I think I'm missing something as nothing happens.

index.html:

<link rel="stylesheet" href="~/Content/mystuff.css">

BundleConfig:

bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css",
                      "~/Content/mystuff.css"));

Despite this setup, bootstrap still seems to override my own settings. Am I missing any reference? Thanks a bunch

Body:
You must Render this bundle inside the View.
 @Styles.Render("~/Content/css")

You can also use dev tools that mozilla offers and see each element in order to understand where Override can happen.

If you want to override bootstrap, use media queries (selectors). Example:

@media (min-width: 768px) {
  .navbar-header {
    float: right;
  }
}


问:
Reducing amount of if/if code (C++)
In my program I have to create an object, which looks like that:

Library::Param1<Library::Param2>::Param3 (don't know how to name Param, types maybe?)
Similar to std::vector<std::string>::iterator.

So, these Param's need to be changed by strings. For example:

```<code>if(param1 == "1_VALUE1")
{
    if(param2 == "2_VALUE1")
    {
        MyLib::1_VALUE1<MyLib::2_VALUE1>::Param3 obj;
        //Obj is used
    }
    //15+ similar if-statements, where only 2_VALUE1 changes
}
/*15+ similar if-statements, where only 1_VALUE1 changes,
  but the contents remain same (again 15+ if-statements)*/
</code>```

using namespace MyLib; is not neseccary.

So, I need to reduce amount of those if-statements, but I do not know the way to do it. I think it could be done with templates, but I am not familiar with them, so, I guess, I would need a code sample.

Sorry for the bad english, if any more info is needed - let me know. Thank you.

--- EDIT: Library (CryptoPP) type-definitions:

Since errors are only on Param1, posting one variation of it:

```<code>//! CBC mode with ciphertext stealing
template <class CIPHER>
struct CBC_CTS_Mode : public CipherModeDocumentation
{
 typedef CipherModeFinalTemplate_CipherHolder<CPP_TYPENAME CIPHER::Encryption, CBC_CTS_Encryption> Encryption;
 typedef CipherModeFinalTemplate_CipherHolder<CPP_TYPENAME CIPHER::Decryption, CBC_CTS_Decryption> Decryption;
};
</code>```

答:
Instead of changing the type dynamically using if statements like that, which isn't well supported by C++, consider using something like a factory pattern instead.

Basically you set up a hierarchy of classes that have virtual methods that implement what you're trying to do in the if cases. You then make a function that creates the appropriate child class from a set of strings, and then you call go or whatever on the created instance.

Title: Reducing amount of if/if code (C++)

Body:
In my program I have to create an object, which looks like that:

Library::Param1<Library::Param2>::Param3 (don't know how to name Param, types maybe?)
Similar to std::vector<std::string>::iterator.

So, these Param's need to be changed by strings. For example:

if(param1 == "1_VALUE1")
{
    if(param2 == "2_VALUE1")
    {
        MyLib::1_VALUE1<MyLib::2_VALUE1>::Param3 obj;
        //Obj is used
    }
    //15+ similar if-statements, where only 2_VALUE1 changes
}
/*15+ similar if-statements, where only 1_VALUE1 changes,
  but the contents remain same (again 15+ if-statements)*/

using namespace MyLib; is not neseccary.

So, I need to reduce amount of those if-statements, but I do not know the way to do it. I think it could be done with templates, but I am not familiar with them, so, I guess, I would need a code sample.

Sorry for the bad english, if any more info is needed - let me know. Thank you.

--- EDIT: Library (CryptoPP) type-definitions:

Since errors are only on Param1, posting one variation of it:

//! CBC mode with ciphertext stealing
template <class CIPHER>
struct CBC_CTS_Mode : public CipherModeDocumentation
{
 typedef CipherModeFinalTemplate_CipherHolder<CPP_TYPENAME CIPHER::Encryption, CBC_CTS_Encryption> Encryption;
 typedef CipherModeFinalTemplate_CipherHolder<CPP_TYPENAME CIPHER::Decryption, CBC_CTS_Decryption> Decryption;
};


问:
app:transformDexArchiveWithExternalLibsDexMergerForDebug'. > com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
This is my 'build.gradle'

```<code>apply plugin: 'com.android.application'
android {
compileSdkVersion 26
useLibrary 'org.apache.http.legacy'
defaultConfig {
    applicationId "ksmk.sahip.com.masjid"
    minSdkVersion 22
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
   compile fileTree(include: ['*.jar'], dir: 'libs')
   implementation 'com.android.support:appcompat-v7:26.1.0'
   implementation 'com.android.support.constraint:constraint-layout:1.0.2'
   testImplementation 'junit:junit:4.12'
   compile 'com.android.support:multidex:1.0.2'
   compile 'com.android.volley:volley:1.0.0'
   compile 'com.android.support:design:26.1.0'
   androidTestImplementation 'com.android.support.test:runner:1.0.1'
   androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
   implementation files('libs/activation.jar')
   implementation files('libs/additionnal.jar')
   implementation files('libs/mail.jar')
}
</code>```

I've checked most of the SO answers for this issue, but nothing worked for me.

I've already tried the following:

1. clean and rebuild the project.

2. MultidexEnable is already true.

3. Invalidate cache and restart the Android studio.

答:
Try this may be solve your problem

android:largeHeap="true"

add this in manifest

```<code><application
    android:name=".MyApp"
    android:allowBackup="true"
    android:icon="@drawable/app_icon_rounded"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:supportsRtl="true"
    android:theme="@style/AppTheme.NoActionBar">
</code>```

Body:
This is my 'build.gradle'

apply plugin: 'com.android.application'
android {
compileSdkVersion 26
useLibrary 'org.apache.http.legacy'
defaultConfig {
    applicationId "ksmk.sahip.com.masjid"
    minSdkVersion 22
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
   compile fileTree(include: ['*.jar'], dir: 'libs')
   implementation 'com.android.support:appcompat-v7:26.1.0'
   implementation 'com.android.support.constraint:constraint-layout:1.0.2'
   testImplementation 'junit:junit:4.12'
   compile 'com.android.support:multidex:1.0.2'
   compile 'com.android.volley:volley:1.0.0'
   compile 'com.android.support:design:26.1.0'
   androidTestImplementation 'com.android.support.test:runner:1.0.1'
   androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
   implementation files('libs/activation.jar')
   implementation files('libs/additionnal.jar')
   implementation files('libs/mail.jar')
}

I've checked most of the SO answers for this issue, but nothing worked for me.

I've already tried the following:

1. clean and rebuild the project.

2. MultidexEnable is already true.

3. Invalidate cache and restart the Android studio.

Body:
Try this may be solve your problem

android:largeHeap="true"

add this in manifest

<application
    android:name=".MyApp"
    android:allowBackup="true"
    android:icon="@drawable/app_icon_rounded"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:supportsRtl="true"
    android:theme="@style/AppTheme.NoActionBar">


问:
PrimeNG dropdown selected option with dynamic value
How to set PrimeNG p-dropdown selected option with dynamic value ?

I am using Formgroup, Formcontrol and my dropdown are set with data querying from database. Now in one of my edit component page I want selected option with dynamic value.

答:
After you receive the values from the database, set the options of the dropdown with the array of SelectItems.

Set the formControl value associated with the dropdown with the value of the SelectItem.