问:
How to use log4j2 to logging entire application?
I am not sure whether I have integrated my application correctly with log4j2 but my objective is very clear. I want to capture each and every tiny logging information in my log file. The logging information includes the spring framework loading + apache tiles loading + my app loading and runtime logging.

Although I am able to capture org.springframework logging details but unable to do so for org.apache.tiles. However, I do capture all the logging information in my console.

It's not like that didn't capture anything at all from tiles logging, I do capture but it's ver few logging information. The amount of logging information I can see in the console is not even little close in the log file.

Here is my log4j2.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<Configuration monitorInterval="60">
    <Properties>
        <Property name="filename">D://log/</Property>
    </Properties>
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout
                pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
        </Console>
        <File name="LOGFILE" fileName="${filename}/SpringWebJsp.log">
            <PatternLayout
                pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
        </File>
    </Appenders>
    <Loggers>
        <Logger name="com.jio.tiny" level="info" additivity="true">
            <AppenderRef ref="LOGFILE" level="info" />
        </Logger>
        <Logger name="org.springframework" level="info" additivity="true">
            <appender-ref ref="LOGFILE" level="info" />
        </Logger>
        <Logger name="org.apache.tiles" level="debug" additivity="true">
            <appender-ref ref="LOGFILE" level="debug" />
        </Logger>
        <!--<Logger name="org.springframework.security" level="debug" additivity="true">
            <appender-ref ref="LOGFILE" level="debug" />
        </Logger> -->
        <!-- <Logger name="org.thymeleaf" level="info" additivity="true">
            <appender-ref ref="LOGFILE" level="info" />
        </Logger> -->
        <!-- <Logger name="org.hibernate" level="info" additivity="true">
            <appender-ref ref="LOGFILE" level="info" />
        </Logger> -->
        <Root level="debug">
            <AppenderRef ref="STDOUT" />
        </Root>
    </Loggers>
</Configuration>
</code>```

my pom.xml

```<code><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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.jio.tiny</groupId>
    <artifactId>SpringWebJsp</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringWebJsp Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <apachetiles.version>3.0.5</apachetiles.version>
        <apache.logger.version>2.8.2</apache.logger.version>
    </properties>

    <repositories>
        <repository>
            <id>io.spring.repo.maven.release</id>
            <url>http://repo.spring.io/release/</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-framework-bom</artifactId>
                <version>4.1.9.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>

        <!-- Apache Tiles -->

        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-core</artifactId>
            <version>${apachetiles.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>jcl-over-slf4j</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-api</artifactId>
            <version>${apachetiles.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-servlet</artifactId>
            <version>${apachetiles.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-jsp</artifactId>
            <version>${apachetiles.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- Apache Log4j2 -->

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${apache.logger.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${apache.logger.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-jcl</artifactId>
            <version>${apache.logger.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>${apache.logger.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
             <version>1.7.6</version>
        </dependency> -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-ext</artifactId>
            <version>1.7.24</version>
        </dependency>

        <!-- Servlet+JSP+JSTL -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <!-- <version>3.2</version> -->
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>2.4</version>
                    <configuration>
                        <warSourceDirectory>src/main/webapp</warSourceDirectory>
                        <warName>SpringWebJsp</warName>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <configuration>
                        <outputDirectory>
                            D://log/jars/
                        </outputDirectory>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
        <finalName>SpringWebJsp</finalName>
    </build>
</project>
</code>```

logging for tiles captured in console

```<code>[DEBUG] 2017-07-04 22:02:57.504 [tomcat-http--2] sax - setDocumentLocator(com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser$LocatorProxy@261c3a65)
[DEBUG] 2017-07-04 22:02:57.504 [tomcat-http--2] sax - startDocument()
[DEBUG] 2017-07-04 22:02:57.504 [tomcat-http--2] sax - resolveEntity('-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN', 'http://tiles.apache.org/dtds/tiles-config_3_0.dtd')
[DEBUG] 2017-07-04 22:02:57.504 [tomcat-http--2] Digester -  Resolving to alternate DTD 'jar:file:/D:/sts-bundle/pivotal-tc-server-developer-3.2.4.SR1/base-instance/wtpwebapps/SpringWebJsp/WEB-INF/lib/tiles-core-3.0.5.jar!/org/apache/tiles/resources/tiles-config_3_0.dtd'
[DEBUG] 2017-07-04 22:02:57.506 [tomcat-http--2] sax - startElement(,tiles-definitions,tiles-definitions)
[DEBUG] 2017-07-04 22:02:57.506 [tomcat-http--2] Digester -   Pushing body text ''
[DEBUG] 2017-07-04 22:02:57.506 [tomcat-http--2] Digester -   New match='tiles-definitions'
[DEBUG] 2017-07-04 22:02:57.506 [tomcat-http--2] Digester -   No rules found matching 'tiles-definitions'.
[DEBUG] 2017-07-04 22:02:57.507 [tomcat-http--2] sax - ignorableWhitespace(

    )
[DEBUG] 2017-07-04 22:02:57.507 [tomcat-http--2] sax - ignorableWhitespace(
    )
.
.
Similar piles of log continue
.
.
[DEBUG] 2017-07-04 22:02:57.540 [tomcat-http--2] BaseLocaleUrlDefinitionDAO - File Resource file:/D:/sts-bundle/pivotal-tc-server-developer-3.2.4.SR1/base-instance/wtpwebapps/SpringWebJsp/WEB-INF/views/tiles/tiles_en.xml at file:/D:/sts-bundle/pivotal-tc-server-developer-3.2.4.SR1/base-instance/wtpwebapps/SpringWebJsp/WEB-INF/views/tiles/tiles_en.xml not found, continue
[DEBUG] 2017-07-04 22:02:57.540 [tomcat-http--2] BaseLocaleUrlDefinitionDAO - File Resource file:/D:/sts-bundle/pivotal-tc-server-developer-3.2.4.SR1/base-instance/wtpwebapps/SpringWebJsp/WEB-INF/views/tiles/tiles_en_US.xml at file:/D:/sts-bundle/pivotal-tc-server-developer-3.2.4.SR1/base-instance/wtpwebapps/SpringWebJsp/WEB-INF/views/tiles/tiles_en_US.xml not found, continue
[DEBUG] 2017-07-04 22:02:57.654 [tomcat-http--2] ResolvingLocaleUrlDefinitionDAO - Resolve definition for child name='home' extends='base-definition.
[DEBUG] 2017-07-04 22:02:57.654 [tomcat-http--2] ResolvingLocaleUrlDefinitionDAO - Resolve definition for child name='products' extends='base-definition.
[DEBUG] 2017-07-04 22:02:57.654 [tomcat-http--2] ResolvingLocaleUrlDefinitionDAO - Resolve definition for child name='contactus' extends='base-definition.
[DEBUG] 2017-07-04 22:02:57.661 [tomcat-http--2] BasicTilesContainer - Render request received for definition 'home'
</code>```

The amount of logging that my log file able to capture is just the last six lines of the above log details.

I wonder if the behavior is ok!

答:
The amount of logging information in the console is not even little
  close in the log file. Is this behavior ok?

Yes.

According to your configuration file, you are writing logs of only 3 packages (com.jio.tiny, org.springframework and org.apache.tiles) in log file. But every log (with level debug or higher) are being written in console, including logs of mentioned 3 packages. So it is expected that console may have more logs than file.

Is it possible to set the console and log file to have same logs? How?

Remove extra Logger definitions from Loggers section and refer file appender along with console appender. So, to have same logs in console and log file, your Loggers section can be as follows:

```<code><Loggers>
    <Root level="debug">
        <AppenderRef ref="STDOUT" />
        <AppenderRef ref="LOGFILE" />
    </Root>
</Loggers>
</code>```

Body:
I am not sure whether I have integrated my application correctly with log4j2 but my objective is very clear. I want to capture each and every tiny logging information in my log file. The logging information includes the spring framework loading + apache tiles loading + my app loading and runtime logging.

Although I am able to capture org.springframework logging details but unable to do so for org.apache.tiles. However, I do capture all the logging information in my console.

It's not like that didn't capture anything at all from tiles logging, I do capture but it's ver few logging information. The amount of logging information I can see in the console is not even little close in the log file.

Here is my log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<Configuration monitorInterval="60">
    <Properties>
        <Property name="filename">D://log/</Property>
    </Properties>
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout
                pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
        </Console>
        <File name="LOGFILE" fileName="${filename}/SpringWebJsp.log">
            <PatternLayout
                pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
        </File>
    </Appenders>
    <Loggers>
        <Logger name="com.jio.tiny" level="info" additivity="true">
            <AppenderRef ref="LOGFILE" level="info" />
        </Logger>
        <Logger name="org.springframework" level="info" additivity="true">
            <appender-ref ref="LOGFILE" level="info" />
        </Logger>
        <Logger name="org.apache.tiles" level="debug" additivity="true">
            <appender-ref ref="LOGFILE" level="debug" />
        </Logger>

        <Root level="debug">
            <AppenderRef ref="STDOUT" />
        </Root>
    </Loggers>
</Configuration>

my pom.xml

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.jio.tiny</groupId>
    <artifactId>SpringWebJsp</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringWebJsp Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <apachetiles.version>3.0.5</apachetiles.version>
        <apache.logger.version>2.8.2</apache.logger.version>
    </properties>

    <repositories>
        <repository>
            <id>io.spring.repo.maven.release</id>
            <url>http://repo.spring.io/release/</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-framework-bom</artifactId>
                <version>4.1.9.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-core</artifactId>
            <version>${apachetiles.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>jcl-over-slf4j</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-api</artifactId>
            <version>${apachetiles.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-servlet</artifactId>
            <version>${apachetiles.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-jsp</artifactId>
            <version>${apachetiles.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${apache.logger.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${apache.logger.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-jcl</artifactId>
            <version>${apache.logger.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>${apache.logger.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-ext</artifactId>
            <version>1.7.24</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>

                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>2.4</version>
                    <configuration>
                        <warSourceDirectory>src/main/webapp</warSourceDirectory>
                        <warName>SpringWebJsp</warName>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <configuration>
                        <outputDirectory>
                            D://log/jars/
                        </outputDirectory>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
        <finalName>SpringWebJsp</finalName>
    </build>
</project>

logging for tiles captured in console

[DEBUG] 2017-07-04 22:02:57.504 [tomcat-http--2] sax - setDocumentLocator(com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser$LocatorProxy@261c3a65)
[DEBUG] 2017-07-04 22:02:57.504 [tomcat-http--2] sax - startDocument()
[DEBUG] 2017-07-04 22:02:57.504 [tomcat-http--2] sax - resolveEntity('-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN', 'http://tiles.apache.org/dtds/tiles-config_3_0.dtd')
[DEBUG] 2017-07-04 22:02:57.504 [tomcat-http--2] Digester -  Resolving to alternate DTD 'jar:file:/D:/sts-bundle/pivotal-tc-server-developer-3.2.4.SR1/base-instance/wtpwebapps/SpringWebJsp/WEB-INF/lib/tiles-core-3.0.5.jar!/org/apache/tiles/resources/tiles-config_3_0.dtd'
[DEBUG] 2017-07-04 22:02:57.506 [tomcat-http--2] sax - startElement(,tiles-definitions,tiles-definitions)
[DEBUG] 2017-07-04 22:02:57.506 [tomcat-http--2] Digester -   Pushing body text ''
[DEBUG] 2017-07-04 22:02:57.506 [tomcat-http--2] Digester -   New match='tiles-definitions'
[DEBUG] 2017-07-04 22:02:57.506 [tomcat-http--2] Digester -   No rules found matching 'tiles-definitions'.
[DEBUG] 2017-07-04 22:02:57.507 [tomcat-http--2] sax - ignorableWhitespace(

    )
[DEBUG] 2017-07-04 22:02:57.507 [tomcat-http--2] sax - ignorableWhitespace(
    )
.
.
Similar piles of log continue
.
.
[DEBUG] 2017-07-04 22:02:57.540 [tomcat-http--2] BaseLocaleUrlDefinitionDAO - File Resource file:/D:/sts-bundle/pivotal-tc-server-developer-3.2.4.SR1/base-instance/wtpwebapps/SpringWebJsp/WEB-INF/views/tiles/tiles_en.xml at file:/D:/sts-bundle/pivotal-tc-server-developer-3.2.4.SR1/base-instance/wtpwebapps/SpringWebJsp/WEB-INF/views/tiles/tiles_en.xml not found, continue
[DEBUG] 2017-07-04 22:02:57.540 [tomcat-http--2] BaseLocaleUrlDefinitionDAO - File Resource file:/D:/sts-bundle/pivotal-tc-server-developer-3.2.4.SR1/base-instance/wtpwebapps/SpringWebJsp/WEB-INF/views/tiles/tiles_en_US.xml at file:/D:/sts-bundle/pivotal-tc-server-developer-3.2.4.SR1/base-instance/wtpwebapps/SpringWebJsp/WEB-INF/views/tiles/tiles_en_US.xml not found, continue
[DEBUG] 2017-07-04 22:02:57.654 [tomcat-http--2] ResolvingLocaleUrlDefinitionDAO - Resolve definition for child name='home' extends='base-definition.
[DEBUG] 2017-07-04 22:02:57.654 [tomcat-http--2] ResolvingLocaleUrlDefinitionDAO - Resolve definition for child name='products' extends='base-definition.
[DEBUG] 2017-07-04 22:02:57.654 [tomcat-http--2] ResolvingLocaleUrlDefinitionDAO - Resolve definition for child name='contactus' extends='base-definition.
[DEBUG] 2017-07-04 22:02:57.661 [tomcat-http--2] BasicTilesContainer - Render request received for definition 'home'

The amount of logging that my log file able to capture is just the last six lines of the above log details.

I wonder if the behavior is ok!

Body:
The amount of logging information in the console is not even little
  close in the log file. Is this behavior ok?

Yes.

According to your configuration file, you are writing logs of only 3 packages (com.jio.tiny, org.springframework and org.apache.tiles) in log file. But every log (with level debug or higher) are being written in console, including logs of mentioned 3 packages. So it is expected that console may have more logs than file.

Is it possible to set the console and log file to have same logs? How?

Remove extra Logger definitions from Loggers section and refer file appender along with console appender. So, to have same logs in console and log file, your Loggers section can be as follows:

<Loggers>
    <Root level="debug">
        <AppenderRef ref="STDOUT" />
        <AppenderRef ref="LOGFILE" />
    </Root>
</Loggers>


来源: stackexchange

问:
Go failing - expected 'package', found 'EOF'
I've been having a hard time trying to execute a simple golang program in a virtual machine powered by vagrant.
These are the relevant fields of my go env:

```<code>GOARCH="amd64"
GOPATH="/usr/local/src/go"
GOROOT="/usr/local/go"
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
</code>```

This is the program I'm trying to execute ( located in /usr/local/src/go/program ):

```<code>package program

import (
    "fmt"
)

func main() {
    fmt.Print("Aloha")
}
</code>```

This, the output that I get:

```<code>main.go:4:5:
/usr/local/go/src/fmt/doc.go:1:1: expected 'package', found 'EOF'
package runtime:
/usr/local/go/src/runtime/alg.go:1:1: expected 'package', found 'EOF'
</code>```

Take into account that this is a completely fake program. The weird thing is that it totally works in a different environment.
What am I missing here?

Thanks a lot!

答:
As a new go user I came upon this answer looking for someone to tell me that I need to start my scripts with package main although my error was a little different,

... expected 'package', found 'import'

It's real obvious now, but hey, that's how it goes.

ContentLicense: CC BY-SA 3.0

Body:
I've been having a hard time trying to execute a simple golang program in a virtual machine powered by vagrant.
These are the relevant fields of my go env:

GOARCH="amd64"
GOPATH="/usr/local/src/go"
GOROOT="/usr/local/go"
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"

This is the program I'm trying to execute ( located in /usr/local/src/go/program ):

package program

import (
    "fmt"
)

func main() {
    fmt.Print("Aloha")
}

This, the output that I get:

main.go:4:5:
/usr/local/go/src/fmt/doc.go:1:1: expected 'package', found 'EOF'
package runtime:
/usr/local/go/src/runtime/alg.go:1:1: expected 'package', found 'EOF'

Take into account that this is a completely fake program. The weird thing is that it totally works in a different environment.
What am I missing here?

Thanks a lot!


问:
Service Registry for Apache Camel Applications
A registry is a list of items with pointers for where to find the items, like the index on a database table or the card catalog for a library.

Correct me if I am wrong, from this definition, what I'd expect from a camel application registry is where a client application can (depending on the client protocol) do a lookup and based on metadata, selects a particular service and uses it as defined.

I am wondering if Apache Camel has anything close to this. Most of the service registries articles/implementations I have seen seems to address only SOAP protocols.

Regards.

答:
You can use the REST API from camel-web to lookup routes and endpoint which is the "services" in Camel.
http://camel.apache.org/web-console.html

In terms of a SOA service registry then you may look at other products which specialize in that such as Apache ZooKepper
http://hadoop.apache.org/zookeeper/

You can use ManagementStrategy SPI to hook into events in Camel and track services as they are created/started/stopped etc. Then you can bridge that to your SOA service registry product of choice.

ContentLicense: CC BY-SA 2.5


问:
TimeZoneInfo.ClearCachedData not in Universal Windows
This is a follow up question to DateTime.Now vs system time

In normal .NET TimeZoneInfo.ClearCachedData() is available to sync the application the system timezone.

In Universal Windows version of TimeZoneInfo this method is not present.

Can I somehow sync the timezone info?

答:
Solution 1

```<code>using System.Reflection;

MethodInfo clearCachedData = typeof(TimeZoneInfo).GetMethod("ClearCachedData",
   BindingFlags.NonPublic | BindingFlags.Static);
if (clearCachedData != null)
{
    clearCachedData.Invoke(null, null);
}
</code>```

Tested on:

Device Model:     Raspberry Pi 3

OS Version:   10.0.14393.0

Solution 2

How to clear TimeZoneInfo cache in WinRT?

Body:
Solution 1

using System.Reflection;

MethodInfo clearCachedData = typeof(TimeZoneInfo).GetMethod("ClearCachedData",
   BindingFlags.NonPublic | BindingFlags.Static);
if (clearCachedData != null)
{
    clearCachedData.Invoke(null, null);
}

Tested on:

Device Model:     Raspberry Pi 3

OS Version:   10.0.14393.0

Solution 2

How to clear TimeZoneInfo cache in WinRT?

ContentLicense: CC BY-SA 4.0


问:
What's default field for query in solr
I am a newcomer for solr, and i have a problem.

Every fieldType definition in managed-schema, you can specify both index analyzer and query analyzer, like this:

```<code><fieldType name="text_en" class="solr.TextField" positionIncrementGap="100">
<analyzer type="index">
  <tokenizer class="solr.StandardTokenizerFactory"/>
  <filter class="solr.StopFilterFactory" words="lang/stopwords_en.txt" ignoreCase="true"/>
  <filter class="solr.LowerCaseFilterFactory"/>
  <filter class="solr.EnglishPossessiveFilterFactory"/>
  <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
  <filter class="solr.PorterStemFilterFactory"/>
</analyzer>
<analyzer type="query">
  <tokenizer class="solr.StandardTokenizerFactory"/>
  <filter class="solr.SynonymFilterFactory" expand="true" ignoreCase="true" synonyms="synonyms.txt"/>
  <filter class="solr.StopFilterFactory" words="lang/stopwords_en.txt" ignoreCase="true"/>
  <filter class="solr.LowerCaseFilterFactory"/>
  <filter class="solr.EnglishPossessiveFilterFactory"/>
  <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
  <filter class="solr.PorterStemFilterFactory"/>
</analyzer>
</code>```

So when i make a query like "q:something", how can i specify the field for "something", and what's the default field for it?

答:
You will find default search field in your request handler, You need to check that in conf/solrconfig.xml

Check for "df" parameter,

```<code><str name="df">_text_</str>
</code>```

OR if you want to query particular field without changing df value then you need specify your query in below format,

```<code>fieldname:something
</code>```

if your query has more than one token you can specify it as ,

```<code>fieldname:"something1 something2"
</code>```

Title: What's default field for query in solr

Body:
I am a newcomer for solr, and i have a problem.

Every fieldType definition in managed-schema, you can specify both index analyzer and query analyzer, like this:

<fieldType name="text_en" class="solr.TextField" positionIncrementGap="100">
<analyzer type="index">
  <tokenizer class="solr.StandardTokenizerFactory"/>
  <filter class="solr.StopFilterFactory" words="lang/stopwords_en.txt" ignoreCase="true"/>
  <filter class="solr.LowerCaseFilterFactory"/>
  <filter class="solr.EnglishPossessiveFilterFactory"/>
  <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
  <filter class="solr.PorterStemFilterFactory"/>
</analyzer>
<analyzer type="query">
  <tokenizer class="solr.StandardTokenizerFactory"/>
  <filter class="solr.SynonymFilterFactory" expand="true" ignoreCase="true" synonyms="synonyms.txt"/>
  <filter class="solr.StopFilterFactory" words="lang/stopwords_en.txt" ignoreCase="true"/>
  <filter class="solr.LowerCaseFilterFactory"/>
  <filter class="solr.EnglishPossessiveFilterFactory"/>
  <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
  <filter class="solr.PorterStemFilterFactory"/>
</analyzer>

So when i make a query like "q:something", how can i specify the field for "something", and what's the default field for it?

Body:
You will find default search field in your request handler, You need to check that in conf/solrconfig.xml

Check for "df" parameter,

<str name="df">_text_</str>

OR if you want to query particular field without changing df value then you need specify your query in below format,

fieldname:something

if your query has more than one token you can specify it as ,

fieldname:"something1 something2"


问:
AngularJS checkbox avoid counting when uncheck checkBox
Here is my running code in Plunker

I got a bug: When I uncheck the answer, I do not want to count how many times we select this answer? We will only count the number when we check the answer. For example, I check "Yes", I uncheck "Yes", I check "Yes" again, I will only show "Yes" was selected 2 times, instead of 3 times.

I read some posts about this issue, but cannot make it work by using checked property?

```<code><input type="checkbox" ng-change="answerSelected(ans)" ng-model="checkAnswer">{{ans.answer}}
</code>```

答:
One workaround is to pass the element itself to the answerSelected method, and check its checkAnswer property. We will only increment the count if this property is true.

```<code><input type="checkbox" ng-change="answerSelected(ans, this)" ng-model="checkAnswer">{{ans.answer}}

$scope.answerSelected = function(checkAnswer, elem) {
  if (elem.checkAnswer === true) {
    checkAnswer.count++;
  }

  $scope.answerBoxSelected = true;
};
</code>```

Body:
Here is my running code in Plunker

I got a bug: When I uncheck the answer, I do not want to count how many times we select this answer? We will only count the number when we check the answer. For example, I check "Yes", I uncheck "Yes", I check "Yes" again, I will only show "Yes" was selected 2 times, instead of 3 times.

I read some posts about this issue, but cannot make it work by using checked property?

<input type="checkbox" ng-change="answerSelected(ans)" ng-model="checkAnswer">{{ans.answer}}

Body:
One workaround is to pass the element itself to the answerSelected method, and check its checkAnswer property. We will only increment the count if this property is true.

<input type="checkbox" ng-change="answerSelected(ans, this)" ng-model="checkAnswer">{{ans.answer}}

$scope.answerSelected = function(checkAnswer, elem) {
  if (elem.checkAnswer === true) {
    checkAnswer.count++;
  }

  $scope.answerBoxSelected = true;
};


问:
Get external URL with Picker for a file in OneDrive Business
I want to get a permanent external link to a file in OneDrive Business using JavaScript Picker API. The link should not expire and should allow to download the file without logging in.

I have enabled external file sharing in my OneDrive Business account. In the UI, I can get a link like https://[my_host].sharepoint.com/personal/apps_tmp_onmicrosoft_com/_layouts/15/guestaccess.aspx?docid=...&authkey=.... This link is what I need.

But when I pick the same file in the picker, I get a link https://[my_host].sharepoint.com/personal/apps_tmp_onmicrosoft_com/_layouts/15/guestaccess.aspx?guestaccesstoken=...&docid=2_...&rev=1. This link requires to log in.

There is no such problem with a personal OneDrive. Is it possible to get a link to the file in OneDrive Business with authkey using the Picker?

答: Solved the issue by adding createLinkParameters: { type: 'view', scope: 'anonymous' }.


问:
Majority element in an array.It
```<code>#include <stdio.h>

void main()
{
    int maj, count, n = 6;
    int arr[] = {1, 2, 2, 2, 2, 3, 4};

    for (int i = 0; i < n; i++) {
        maj = arr[i];
        count = 0;
        for (int j = 9; j < n; j++) {
            if (arr[j] == maj) count++;
        }
        if (count > n / 2) {
            break; /* I think some problem is here ,if majority element not found then it takes last element as the majority element */
        }
    }
    printf("%d", maj);
}
</code>```

It is giving correct output if majority ellement is there but incorrect output if no majority element is there for example if array is {1,2,3,4} it is giving output as 4. please help!!

答:
For starters according to the C Standard function main without parameters shall be declared like

```<code>int main( void )
</code>```

Try not to use magic numbers. Usually as in your program they are a reason for program bugs. For example you declared the array arr as having 7 elements however the variable n that should keep the number of elements in the array is initialized with the value 6. Another magic number 9 is used in the loop

```<code>for (int j = 9; j < n; j++) {
            ^^^
</code>```

There is no need to write the outer loop that travers the whole array. Also the program does not report the case when the majority number does not exist in the array.

Using your approach with two loops the program can look the following way

```<code>#include <stdio.h>

int main( void )
{
    int a[] = { 1, 2, 2, 2, 2, 3, 4 };
    const size_t N = sizeof( a ) / sizeof( *a );

    size_t i = 0;
    for ( ; i < ( N + 1 ) / 2; i++ )
    {
        size_t count = 1;
        for ( size_t j = i + 1; count < N / 2 + 1 && j < N; j++ )
        {
            if ( a[i] == a[j] ) ++count;
        }

        if ( !( count < N / 2 + 1) ) break;
    }

    if ( i != ( N + 1 ) / 2 )
    {
        printf( "The majority is %d\n", a[i] );
    }
    else
    {
        puts( "There is no majority element" );
    }

    return 0;
}
</code>```

Its output is

```<code>The majority is 2
</code>```

Title: Majority element in an array.It

Body:
#include <stdio.h>

void main()
{
    int maj, count, n = 6;
    int arr[] = {1, 2, 2, 2, 2, 3, 4};

    for (int i = 0; i < n; i++) {
        maj = arr[i];
        count = 0;
        for (int j = 9; j < n; j++) {
            if (arr[j] == maj) count++;
        }
        if (count > n / 2) {
            break; /* I think some problem is here ,if majority element not found then it takes last element as the majority element */
        }
    }
    printf("%d", maj);
}

It is giving correct output if majority ellement is there but incorrect output if no majority element is there for example if array is {1,2,3,4} it is giving output as 4. please help!!

Body:
For starters according to the C Standard function main without parameters shall be declared like

int main( void )

Try not to use magic numbers. Usually as in your program they are a reason for program bugs. For example you declared the array arr as having 7 elements however the variable n that should keep the number of elements in the array is initialized with the value 6. Another magic number 9 is used in the loop

for (int j = 9; j < n; j++) {
            ^^^

There is no need to write the outer loop that travers the whole array. Also the program does not report the case when the majority number does not exist in the array.

Using your approach with two loops the program can look the following way

#include <stdio.h>

int main( void )
{
    int a[] = { 1, 2, 2, 2, 2, 3, 4 };
    const size_t N = sizeof( a ) / sizeof( *a );

    size_t i = 0;
    for ( ; i < ( N + 1 ) / 2; i++ )
    {
        size_t count = 1;
        for ( size_t j = i + 1; count < N / 2 + 1 && j < N; j++ )
        {
            if ( a[i] == a[j] ) ++count;
        }

        if ( !( count < N / 2 + 1) ) break;
    }

    if ( i != ( N + 1 ) / 2 )
    {
        printf( "The majority is %d\n", a[i] );
    }
    else
    {
        puts( "There is no majority element" );
    }

    return 0;
}

Its output is

The majority is 2


问:
supplying @Query with a runtime generated jpql query
I am working with a method that generates a query string according to a set of filters that the user wants to apply when retrieving data from the database. So for each new filter, the method appends something like AND variable_x = '4' for example.

I want to use the JpaRepository interface of spring data and I want to make a method that is annotated with @Query to be able to execute this generated query. However, the @Query requires a constant as a value. So is there a way to have the @Query execute this generated query? Could something like this work for example? Can I give the entire JPQL query as a parameter to @Query?

```<code>@Query("?1")
public abstract void executeRuntimeGeneratedQuery(String query);
</code>```

Or are there more elegant solutions that solve my problem?

答:
Can I give the entire JPQL query as a parameter to @Query?

No this is not possible. @Query annotations are a static thing and you can use parameters (including SpEL expressions) only as supported by JPA which basically means expressions, not column or table names and certainly not complete statements.

Or are there more elegant solutions that solve my problem?

Yes, there are alternatives. From what you describe Specifications seem to fit the bill best.

Of course, you can combine that with custom methods which will also save the day if you want to do more than Specifications can offer.

Body:
I am working with a method that generates a query string according to a set of filters that the user wants to apply when retrieving data from the database. So for each new filter, the method appends something like AND variable_x = '4' for example.

I want to use the JpaRepository interface of spring data and I want to make a method that is annotated with @Query to be able to execute this generated query. However, the @Query requires a constant as a value. So is there a way to have the @Query execute this generated query? Could something like this work for example? Can I give the entire JPQL query as a parameter to @Query?

@Query("?1")
public abstract void executeRuntimeGeneratedQuery(String query);

Or are there more elegant solutions that solve my problem?


问:
Linq with dot notation - which is better form or what's the difference between these two?
I've been reading Jon Skeet's C# In Depth: Second Edition and I noticed something slightly different in one of his examples from something I do myself.

He has something similar to the following:

```<code>var item = someObject.Where(user => user.Id == Id).Single();
</code>```

Whereas I've been doing the following:

```<code>var item = someObject.Single(user => user.Id == Id);
</code>```

Is there any real difference between the two? I know Jon Skeet is pretty much the c# god so I tend to think his knowledge in this area is better than mine so I might be misunderstanding something here. Hope someone can help.

答:
The only thing I can notice is that the IL produced using the Where method is one row bigger than the second example (tested through LinqPAD).

```<code>IL_0042:  call        System.Linq.Enumerable.Where
IL_0047:  call        System.Linq.Enumerable.Single
</code>```

instead of a single call to System.Linq.Enumerable.Single

```<code>IL_006B:  call        System.Linq.Enumerable.Single
</code>```

Body:
I've been reading Jon Skeet's C# In Depth: Second Edition and I noticed something slightly different in one of his examples from something I do myself.

He has something similar to the following:

var item = someObject.Where(user => user.Id == Id).Single();

Whereas I've been doing the following:

var item = someObject.Single(user => user.Id == Id);

Is there any real difference between the two? I know Jon Skeet is pretty much the c# god so I tend to think his knowledge in this area is better than mine so I might be misunderstanding something here. Hope someone can help.

Body:
The only thing I can notice is that the IL produced using the Where method is one row bigger than the second example (tested through LinqPAD).

IL_0042:  call        System.Linq.Enumerable.Where
IL_0047:  call        System.Linq.Enumerable.Single

instead of a single call to System.Linq.Enumerable.Single

IL_006B:  call        System.Linq.Enumerable.Single


问:
How can I make a combination array which contains maximum length?
I have these three arrays:

```<code>$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
</code>```

And this is expected result:

```<code>/* Array
   (
       [0] => one
       [1] => two
       [3] => three
       [4] => four
       [5] => five
       [6] => six
       [7] => seven
   )
</code>```

Here is my solution which doesn't work as expected:

```<code>print_r( array_unique( $arr1 + $arr2 + $arr3) );
/* Array
   (
       [0] => one
       [1] => two
       [2] => three
       [3] => seven
   )
</code>```

How can I do that?

答:
I think this will work just fine </p>

```<code>$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
$n_array = array_values(array_unique(array_merge($arr1 , $arr2 , $arr3)));
echo "```";print_r($n_array);echo "```";die;
</code>```

<p>Output is </p>

```<code>Array
(
    [0] => one
    [1] => two
    [2] => three
    [3] => four
    [4] => five
    [5] => six
    [6] => seven
)
</code>```

Body:
I have these three arrays:

$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];

And this is expected result:

/* Array
   (
       [0] => one
       [1] => two
       [3] => three
       [4] => four
       [5] => five
       [6] => six
       [7] => seven
   )

Here is my solution which doesn't work as expected:

print_r( array_unique( $arr1 + $arr2 + $arr3) );
/* Array
   (
       [0] => one
       [1] => two
       [2] => three
       [3] => seven
   )

How can I do that?

Body:
I think this will work just fine

$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
$n_array = array_values(array_unique(array_merge($arr1 , $arr2 , $arr3)));
echo "<pre>";print_r($n_array);echo "</pre>";die;

Output is

Array
(
    [0] => one
    [1] => two
    [2] => three
    [3] => four
    [4] => five
    [5] => six
    [6] => seven
)


问:
Pg-promise vs sequelize, To handle millions of sql queries
Module pg-promise provides method sequence to execute infinite sequences, suitable for massive transactions, like bulk inserts, with way over 1,000 records. And it supports query streams for high-performance, read-only queries.

Does Sequelize offer anything similar to those things?

Sorry for asking such basic things, but I am new and don't have any idea about these two.

Thanks for your response and suggestions.

答:
This answer will probably anger some of the Sequelize fans, but in the name of truth...

What you're referring to within pg-promise is fully documented in Data Imports.

And no, Sequelize doesn't have anything like that.

And in addition, Sequelize is known to be plagued by performance issues, like this one: Transactions extremely slow when inserting 1000s of records, ones that are very bad and very old at the same time.


问:
list.append in python 3: nonetype is not iterable?
I am trying to add every word in romeo.txt to an empty list.

I thought this code was okay but python3 returns a traceback saying

File "test.py", line 13, in <module>
      if i in lst:
  TypeError: argument of type 'NoneType' is not iterable

here's my code:

```<code>fh = open("romeo.txt")
lst = list()
words = fh.read()
list1 = words.split()
for i in list1:
    if i in lst:
        continue
    else:
        lst = lst.append(i)
lst = lst.sort()
print(lst)
</code>```

答:
If you want to avoid the loop, you can use sets:

```<code>fh = open("romeo.txt")
words = fh.read()
lst = list(set(words.split()))
lst.sort()
print(lst)
</code>```

Simply put, a set cannot have duplicates.

Body:
I am trying to add every word in romeo.txt to an empty list.

I thought this code was okay but python3 returns a traceback saying

File "test.py", line 13, in <module>
      if i in lst:
  TypeError: argument of type 'NoneType' is not iterable

here's my code:

fh = open("romeo.txt")
lst = list()
words = fh.read()
list1 = words.split()
for i in list1:
    if i in lst:
        continue
    else:
        lst = lst.append(i)
lst = lst.sort()
print(lst)

Body:
If you want to avoid the loop, you can use sets:

fh = open("romeo.txt")
words = fh.read()
lst = list(set(words.split()))
lst.sort()
print(lst)

Simply put, a set cannot have duplicates.


问:
Extract one or more qualifying substrings from each string in an array
I am trying to extract qualifying substrings from an array of strings. Some strings in the array have just one qualifying substring, but others may have more.  I need to build a flat array of all of these wanted values.

The following is my current Codeigniter method, but it doesn't handle cases when more than one qualifying substring exists.

```<code>public function generatenewname()
{
    $this->load->helper('directory');
    $map = directory_map('./assets/file_upload/md/temp/', FALSE, TRUE);
    for ($x = 0; $x < count($map); $x++) {
        $newest[$x] = explode(" ", $map[$x]);
        for ($y = 0; $y < count($newest[$x]); $y++) {
            if (strlen($newest[$x][$y]) >= 7) {
                $file[] = $newest[$x][$y];
            }
        }
    }
    for ($x = 0; $x < count($file); $x++) {
        echo $x . ' ' . $file[$x] . '<br>';
    }
}
</code>```

Assume that my $map array contains this:

```<code>$map = [
    'BACK PACK BBP160800103  G086-1 8#.JPG',
    'BACKPACK BBP160500010 G114-3#1.JPG',
    'WSL160800024-WSL160800025 L83-5.JPG',
    'IA041017 L83-5.JPG'
];
</code>```

Desired result:

```<code>[
    'BBP160800103',
    'BBP160500010',
    'WSL160800024',
    'WSL160800025',
    'IA041017'
]
</code>```

答:
Pass your final array to this function to achieve your result.</p>

```<code>arraymakking($file);//your array

function arraymakking($arr){
    foreach($arr as $key=>$val){
        if(strpos($val,'-') !== false){
            $res=explode('-',$val);
            unset($arr[$key]);
        }
    }
    $result=array_merge($arr,$res);
    return $result;
}
</code>```

Body:
I am trying to extract qualifying substrings from an array of strings. Some strings in the array have just one qualifying substring, but others may have more.  I need to build a flat array of all of these wanted values.

The following is my current Codeigniter method, but it doesn't handle cases when more than one qualifying substring exists.

public function generatenewname()
{
    $this->load->helper('directory');
    $map = directory_map('./assets/file_upload/md/temp/', FALSE, TRUE);
    for ($x = 0; $x < count($map); $x++) {
        $newest[$x] = explode(" ", $map[$x]);
        for ($y = 0; $y < count($newest[$x]); $y++) {
            if (strlen($newest[$x][$y]) >= 7) {
                $file[] = $newest[$x][$y];
            }
        }
    }
    for ($x = 0; $x < count($file); $x++) {
        echo $x . ' ' . $file[$x] . '
';
    }
}

Assume that my $map array contains this:

$map = [
    'BACK PACK BBP160800103  G086-1 8#.JPG',
    'BACKPACK BBP160500010 G114-3#1.JPG',
    'WSL160800024-WSL160800025 L83-5.JPG',
    'IA041017 L83-5.JPG'
];

Desired result:

[
    'BBP160800103',
    'BBP160500010',
    'WSL160800024',
    'WSL160800025',
    'IA041017'
]

Body:
Pass your final array to this function to achieve your result.

arraymakking($file);//your array

function arraymakking($arr){
    foreach($arr as $key=>$val){
        if(strpos($val,'-') !== false){
            $res=explode('-',$val);
            unset($arr[$key]);
        }
    }
    $result=array_merge($arr,$res);
    return $result;
}


问:
How to push a project to github after renamed a folder locally
I am learning Git. I renamed a folder locally and now could not push a project to GitHub. It shown this message when I push it.

```<code>push -u origin master
fatal: 'origin' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

Thank you for your help.

答:
its git push -u origin master.

Therotically, git has nothing to do with the folder names. It traks the whole content.

Body:
I am learning Git. I renamed a folder locally and now could not push a project to GitHub. It shown this message when I push it.

push -u origin master
fatal: 'origin' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Thank you for your help.


问:
wholesale replacement of options html string within select?
I would like to 'toggle' the list of options in a select box.

I have the two sets of options as strings (American states and Canadian Provinces). However, I notice that in the DOM, the select object has no 'innerhtml' property (at least not according to w3schools).

Do I have to go and remove and replace the options one by one? How do I do this?

答:
Why not replace the entire <SELECT>? There are a number of ways to do this. Easiest is to wrap the <SELECT> in a SPAN/DIV and replace its innerHTML.

If you're pulling your lists from an array, you can set the list length to zero, then insert the new elements in a loop.


答:
use array_merge then, array_unique

```<code>$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];

print_r(array_unique (array_merge($arr1,$arr2,$arr3)));
</code>```

Result

```<code>Array ( [0] => one [1] => two [2] => three [4] => four [6] => five [7] => six [8] => seven )
</code>```

Title: How can I make a combination array which contains maximum length?

Body:
use array_merge then, array_unique

$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];

print_r(array_unique (array_merge($arr1,$arr2,$arr3)));

Result

Array ( [0] => one [1] => two [2] => three [4] => four [6] => five [7] => six [8] => seven )


答:
Just Do That.. use array_uniqe

Demo: https://eval.in/827705

```<code><?php

    $arr1 = ['one', 'two', 'three'];
    $arr2 = ['three', 'four'];
    $arr3 = ['two', 'five', 'six', 'seven'];

    print_r ($difference = array_unique(array_merge($arr1, $arr2,$arr3)));
    ?>
</code>```

Body:
Just Do That.. use array_uniqe

Demo: https://eval.in/827705

<?php

    $arr1 = ['one', 'two', 'three'];
    $arr2 = ['three', 'four'];
    $arr3 = ['two', 'five', 'six', 'seven'];

    print_r ($difference = array_unique(array_merge($arr1, $arr2,$arr3)));
    ?>


问:
Can anyone please explain the output of ls -1 in Linux?
I was asked this question in one of the interviews.
Can anyone please explain</p>

答:
ls -1 will list files each on separate line...

whereas ls itself will list them like so


问:
how to set where condition under if result
I have four different where condition.

And I get 2 values(A,B) from outside.

If both A and B are null

I want to select rows under first where condition.

If A is null and B is not, the second where condition.

If A is not null and B is null, the third.

If Both A and B are not null, the fourth.

Let me show it to you briefly.

```<code>select * from mytable
if(A ==null and B == null)
   first where condition
if(A == null and B != null)
   second where condition

  ......
</code>```

How can I do this with SQL

答:
Four different sets of conditions you want to meet:

If both A and B are null , and...

If A is null and B is not , and ...

If A is not null and B is null , and ...

If Both A and B are not null , and ...

These could be expressed like this:

```<code>WHERE (A IS NULL     AND B IS NULL     AND NAME = 'Fred')
   OR (A IS NULL     AND B IS NOT NULL AND NAME = 'Barney')
   OR (A IS NOT NULL AND B IS NULL     AND NAME = 'Wilma')
   OR (A IS NOT NULL AND B IS NOT NULL AND NAME = 'Betty')
</code>```

Body:
I have four different where condition.

And I get 2 values(A,B) from outside.

If both A and B are null

I want to select rows under first where condition.

If A is null and B is not, the second where condition.

If A is not null and B is null, the third.

If Both A and B are not null, the fourth.

Let me show it to you briefly.

select * from mytable
if(A ==null and B == null)
   first where condition
if(A == null and B != null)
   second where condition

  ......

How can I do this with SQL

Body:
Four different sets of conditions you want to meet:

If both A and B are null , and...

If A is null and B is not , and ...

If A is not null and B is null , and ...

If Both A and B are not null , and ...

These could be expressed like this:

WHERE (A IS NULL     AND B IS NULL     AND NAME = 'Fred')
   OR (A IS NULL     AND B IS NOT NULL AND NAME = 'Barney')
   OR (A IS NOT NULL AND B IS NULL     AND NAME = 'Wilma')
   OR (A IS NOT NULL AND B IS NOT NULL AND NAME = 'Betty')


问:
Can a protocol require conforming types to be a subtype of another type?
For example: I'd like to say in a protocol definition that, a class conforming it, needs to also subclass UIView or another custom class type MyClass. Is that possible?

答:
Yes you can, just define your protocol as:</p>

```<code>protocol SomeProtocol where Self: MyClass {
    // protocol code here
}
</code>```

Body:
Yes you can, just define your protocol as:

protocol SomeProtocol where Self: MyClass {
    // protocol code here
}


问:
preventing double clicks on button with ajax call
I noticed my users sometimes click the buttons twice, maybe no one told them one click is enough.

What's the best way to prevent the double-click?
I basically hide the button and show a "loading" gif, but that apparently is not enough...

答:
Usually disabling/hiding/replacing the button should work. If they are real fast, try setting a variable to false when your script starts, return if it's true, set it to true after the first click.

```<code>var alReadyClicked = false;
function click(){
 if (alreadyClicked)
  return false;
 alreadyClicked = true;
}
</code>```

Don't forget to set it to false when the user can click again.

Body:
Usually disabling/hiding/replacing the button should work. If they are real fast, try setting a variable to false when your script starts, return if it's true, set it to true after the first click.

var alReadyClicked = false;
function click(){
 if (alreadyClicked)
  return false;
 alreadyClicked = true;
}

Don't forget to set it to false when the user can click again.


问:
Regex in Vim- inserting blank line before numbered lines
I have following text:

```<code>Title line
1. First list
First line
Second line
2. Second list
Oranges
Mangoes
3. Stationary
Pen
Pencils
Etc
</code>```

I want to add a blank line before every numbered line, so that above text looks like following:

```<code>Title line

1. First list
First line
Second line

2. Second list
Oranges
Mangoes

3. Stationary
Pen
Pencils
Etc
</code>```

I tried following code but it is not working:

```<code>%s/^(\d)/\r\1/g
</code>```

and

```<code>%s/(^\d)/\r\1/g
</code>```

and

%s/^([0-9])/\r\1/gc

Where is the problem and how can this be solved. Thanks for your help.

答:
To use capture group () without having to escape them, use \v very magic (See :h /magic)

```<code>:%s/\v^(\d)/\r\1/
</code>```

Note that g flag is redundant as there can be only one match at beginning of line

As entire matched string is needed in replacement section, one can simply use & or \0 without needing explicit capture group

```<code>:%s/^\d/\r&/
</code>```

Mentioned in comments

```<code>:g/^\d/norm O
</code>```

The g command allows filtering lines and executing command on those lines, like norm O to open new line above. Default range is entire file, so % is not needed

With substitute command, this would be :g/^\d/s/^/\r/

See :h :g and :h ex-cmd-index for complete list of commands to use with :g

Body:
I have following text:

Title line
1. First list
First line
Second line
2. Second list
Oranges
Mangoes
3. Stationary
Pen
Pencils
Etc

I want to add a blank line before every numbered line, so that above text looks like following:

Title line

1. First list
First line
Second line

2. Second list
Oranges
Mangoes

3. Stationary
Pen
Pencils
Etc

I tried following code but it is not working:

%s/^(\d)/\r\1/g

and

%s/(^\d)/\r\1/g

and

%s/^([0-9])/\r\1/gc

Where is the problem and how can this be solved. Thanks for your help.

Body:
To use capture group () without having to escape them, use \v very magic (See :h /magic)

:%s/\v^(\d)/\r\1/

Note that g flag is redundant as there can be only one match at beginning of line

As entire matched string is needed in replacement section, one can simply use & or \0 without needing explicit capture group

:%s/^\d/\r&/

Mentioned in comments

:g/^\d/norm O

The g command allows filtering lines and executing command on those lines, like norm O to open new line above. Default range is entire file, so % is not needed

With substitute command, this would be :g/^\d/s/^/\r/

See :h :g and :h ex-cmd-index for complete list of commands to use with :g


问:
How to use Isabelle's code_pred and values commands?
There is an example of code_pred usage in "Concrete Semantics" by Tobias Nipkow and Gerwin Klein, Section 7.2.2. I've implemented a simple language based on the examples and I try to calculate values of expressions:

```<code>theory BooLang
  imports Main
begin

type_synonym id = string
type_synonym 'a Env = "id ⇒ 'a"

datatype BooBoolExp =
  BooLiteralExp bool |
  BooLetExp id BooBoolExp BooBoolExp |
  BooVarExp id |
  BooAndExp BooBoolExp BooBoolExp

datatype BooVal = Bv bool

type_synonym BooEnv = "BooVal Env"

inductive tbooval :: "BooBoolExp × BooEnv ⇒ BooVal ⇒ bool" (infix "⇒" 55) where
  Literal: "(BooLiteralExp b, env) ⇒ Bv b" |
  And: "⟦(a, env) ⇒ Bv av; (b, env) ⇒ Bv bv⟧ ⟹ (BooAndExp a b, env) ⇒ Bv (av ∧ bv)" |
  Var: "(BooVarExp v, env) ⇒ env v" |
  Let: "⟦(val, env) ⇒ b; (body, env(v := b)) ⇒ x⟧ ⟹ (BooLetExp v val body, env) ⇒ x"

code_pred tbooval .

values "{t. True}"

values "{t. (BooLiteralExp true, λ_. Bv false) ⇒ t}"

end
</code>```

But for the 1st values' invocation I get the error:

Evaluation with values is not possible because compilation with
  code_pred was not invoked.

And for the 2nd one I get the error:

No mode possible for comprehension {t. (BooLiteralExp true, λ_. Bv
  false) ⇒ t}.

What's wrong with my theory?

答:
The first command values {t. True} cannot work as this command asks Isabelle to enumerate all values of the type of t, which is inferred to be a type variable 'a; and this cannot be done.

For the second command, you just misspelled True and False. As is, true and false are inferred to be boolean variables instead of boolean constants. Unlike value, the command values does not support symbolic execution in Isabelle2016-1. That is, all input arguments to the inductive  predicate must be ground values without variables. In your example, code_pred infers two execution modes: One in which everything is given as input and one in which only the first argument is given as input. You can see the inferred modes by passing the [show_modes] option as in

```<code> code_pred [show_modes] tboolval .
</code>```

You can find some further documentation on code_pred and values in the code generator tutorial.

Body:
There is an example of code_pred usage in "Concrete Semantics" by Tobias Nipkow and Gerwin Klein, Section 7.2.2. I've implemented a simple language based on the examples and I try to calculate values of expressions:

theory BooLang
  imports Main
begin

type_synonym id = string
type_synonym 'a Env = "id ⇒ 'a"

datatype BooBoolExp =
  BooLiteralExp bool |
  BooLetExp id BooBoolExp BooBoolExp |
  BooVarExp id |
  BooAndExp BooBoolExp BooBoolExp

datatype BooVal = Bv bool

type_synonym BooEnv = "BooVal Env"

inductive tbooval :: "BooBoolExp × BooEnv ⇒ BooVal ⇒ bool" (infix "⇒" 55) where
  Literal: "(BooLiteralExp b, env) ⇒ Bv b" |
  And: "⟦(a, env) ⇒ Bv av; (b, env) ⇒ Bv bv⟧ ⟹ (BooAndExp a b, env) ⇒ Bv (av ∧ bv)" |
  Var: "(BooVarExp v, env) ⇒ env v" |
  Let: "⟦(val, env) ⇒ b; (body, env(v := b)) ⇒ x⟧ ⟹ (BooLetExp v val body, env) ⇒ x"

code_pred tbooval .

values "{t. True}"

values "{t. (BooLiteralExp true, λ_. Bv false) ⇒ t}"

end

But for the 1st values' invocation I get the error:

Evaluation with values is not possible because compilation with
  code_pred was not invoked.

And for the 2nd one I get the error:

No mode possible for comprehension {t. (BooLiteralExp true, λ_. Bv
  false) ⇒ t}.

What's wrong with my theory?

Body:
The first command values {t. True} cannot work as this command asks Isabelle to enumerate all values of the type of t, which is inferred to be a type variable 'a; and this cannot be done.

For the second command, you just misspelled True and False. As is, true and false are inferred to be boolean variables instead of boolean constants. Unlike value, the command values does not support symbolic execution in Isabelle2016-1. That is, all input arguments to the inductive  predicate must be ground values without variables. In your example, code_pred infers two execution modes: One in which everything is given as input and one in which only the first argument is given as input. You can see the inferred modes by passing the [show_modes] option as in

 code_pred [show_modes] tboolval .

You can find some further documentation on code_pred and values in the code generator tutorial.


问:
Is there a way to set local storage in WKWebView
I want to set local storage before making request to WKWebView is that possible in any iOS version?

Can't find a way to do it, the only class seem to relevant is WKWebsiteDataStore https://developer.apple.com/documentation/webkit/wkwebsitedatastore which only have method to read and delete.

答:
From @paulvs comment here is what I do.

Set navigation delegate to listen to finished callback.

webView.navigationDelegate = self

Then in the callback, check for value in localStorage and set if needed.

```<code>func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

    webView.evaluateJavaScript("localStorage.getItem(\"key\")") { (result, error) in

        // check if result is what I want
        // if it is what I want, do nothing
        // if not set it
        webView.evaluateJavaScript("localStorage.setItem(\"key\", \"value\")") { (result, error) in

            webView.reload()

        }
    }
}
</code>```

Body:
From @paulvs comment here is what I do.

Set navigation delegate to listen to finished callback.

webView.navigationDelegate = self

Then in the callback, check for value in localStorage and set if needed.

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

    webView.evaluateJavaScript("localStorage.getItem(\"key\")") { (result, error) in

        // check if result is what I want
        // if it is what I want, do nothing
        // if not set it
        webView.evaluateJavaScript("localStorage.setItem(\"key\", \"value\")") { (result, error) in

            webView.reload()

        }
    }
}


问:
Label is displayed below the input textbox
This is my input code sample. So whenever an error is generated, this error label would be visible. But it is coming up below the input element. I want it to be on the right side of the input.

I am able to modify the css for this bit using the label.error code bit I have. Label being the type and error is the class of that label being generated.

```<code>label.error
{
display:inline;
float:right;
}

> <td><input
> name="answer_engineeringjobs_1^11"
> id="answer_engineeringjobs_1"
> class="reqfield required zipUS error"
> type="text"><label class="error"
> generated="true"
> for="answer_engineeringjobs_1">This
> field is required.</label></td>
</code>```

答:
It is actually the parent(s) element(s) size that causes the line break. There's nothing wrong with you code as you can see here:

http://jsfiddle.net/Pc2QB/

Body:
This is my input code sample. So whenever an error is generated, this error label would be visible. But it is coming up below the input element. I want it to be on the right side of the input.

I am able to modify the css for this bit using the label.error code bit I have. Label being the type and error is the class of that label being generated.

label.error
{
display:inline;
float:right;
}

> <input
> name="answer_engineeringjobs_1^11"
> id="answer_engineeringjobs_1"
> class="reqfield required zipUS error"
> type="text"> generated="true"
> for="answer_engineeringjobs_1">This
> field is required.


问:
AndroidStudio can't find Volley
I cloned volley from git clone https://android.googlesource.com/platform/frameworks/volley and imported it as a new module in AndroidStudio, but I get the following error when syncing:

Failed to resolve: com.android.volley:volley.1.0.0

My build.gradle, in my app folder:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.example.cs169_au.volleytest1"
        minSdkVersion 22
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.0'
    compile 'com.android.support:design:23.2.0'
    compile 'com.google.android.gms:play-services:8.1.0'
    compile 'com.android.support:support-v4:23.1.1'
    compile 'com.google.maps:google-maps-services:0.1.7'
    compile 'com.android.volley:volley.1.0.0'
}

repositories {
    mavenCentral()
}
</code>```

答:
Google's official Volley is hosted in JCenter, so you have to add jcenter() to repositories in the project's build.gradle:

```<code>allprojects {
    repositories {
        mavenCentral()
        jcenter() // Add this line
    }
}
</code>```

Title: AndroidStudio can't find Volley

Body:
I cloned volley from git clone https://android.googlesource.com/platform/frameworks/volley and imported it as a new module in AndroidStudio, but I get the following error when syncing:

Failed to resolve: com.android.volley:volley.1.0.0

My build.gradle, in my app folder:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.example.cs169_au.volleytest1"
        minSdkVersion 22
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.0'
    compile 'com.android.support:design:23.2.0'
    compile 'com.google.android.gms:play-services:8.1.0'
    compile 'com.android.support:support-v4:23.1.1'
    compile 'com.google.maps:google-maps-services:0.1.7'
    compile 'com.android.volley:volley.1.0.0'
}

repositories {
    mavenCentral()
}

Body:
Google's official Volley is hosted in JCenter, so you have to add jcenter() to repositories in the project's build.gradle:

allprojects {
    repositories {
        mavenCentral()
        jcenter() // Add this line
    }
}


问:
set tableview height dynamically and restrict to some extend swift 3?
i have one table view as popUpTableView, in that i need to set table view height as dynamically as per no of rows.
i am adding in cellForRowAtIndexpath

```<code>  popupTableView.height = popupTableView.contentSize.height
</code>```

it is working fine but the problem is when no of cells are increasing then the tableview height is increasing than its origingal height

```<code>extension DiagnosisViewController :UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if tableView == diagnosisTableView {
            return self.diagnosisModel.count
        } else if tableView == popupTableView {
            return self.popupDiagnosisModel.count
        }
        return 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell:DiagnosisTableViewCell?

        if tableView == self.diagnosisTableView {

            cell = self.diagnosisTableView.dequeueReusableCell(withIdentifier: "DiagnosisCell") as? DiagnosisTableViewCell

            if diagnosisModel.count > 0 {

                let model = diagnosisModel[indexPath.row]
                cell?.indexLabel.text =  String(indexPath.row + 1)
                cell?.diagnosisNameLabel.text = "  \(model.diagnosisDescription!)"
                cell?.deleteButton.tag = indexPath.row
                cell?.deleteButton.addTarget(self, action:#selector(deleteDiagnosis(button:)), for: .touchUpInside)
                diagnosisNotFoundLabel.isHidden = true

            }

        } else if tableView == self.popupTableView {

            cell = self.diagnosisTableView.dequeueReusableCell(withIdentifier: "DiagnosisCell") as? DiagnosisTableViewCell

            cell?.deleteButton.isHidden = true

            if (indexPath.row % 2 == 0) {
                cell?.baseView.backgroundColor = UIColor.white
            }
            else {
                cell?.baseView.backgroundColor = UIColor.init(colorLiteralRed: 241/255, green: 241/255, blue: 241/255, alpha: 1.0)
            }

            cell?.indexLabel.text =  String(indexPath.row + 1)
            cell?.indexView.layer.cornerRadius = (cell?.indexView.frame.size.width)!/2
            cell?.indexView.layer.borderWidth = 0.5
            cell?.indexView.layer.borderColor = UIColor.lightGray.cgColor

            cell?.baseView.layer.borderWidth = 0.5
            cell?.baseView.layer.cornerRadius = 5.0
            cell?.baseView.layer.borderColor = UIColor.lightGray.cgColor;

            if diagnosisModel.count > 0 {

                let model = popupDiagnosisModel[indexPath.row]
                cell?.diagnosisNameLabel.text = "  \(model.diagnosisDescription!)"
            }
            self.popupTableView.height = self.popupTableView.contentSize.height

        }
        return cell!
    }

}

let maxHeight = popupTableView.frame.size.height
let changeHeight = popupTableView.contentSize.height

if changeHeight < maxHeight {
popupTableView.height = changeHeight
}
</code>```

how to get tableview height for only visible cells and where to place that code ??

Thanks in Advance.

答:
take one variable which will caluculate bottomconstraint value of tableview

```<code> var bottomConstraintValue : CGFloat = 0.0
    override func viewDidLoad() {
        super.viewDidLoad()
   bottomConstraintValue = self.popupContainerView.height - self.popupTableView.frame.origin.y - self.popupTableView.frame.size.height
     }
</code>```

call delegate method willDisplay: of tableview

```<code>func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

if tableView == popupTableView {
        if indexPath.row == (popupTableView.indexPathsForVisibleRows?.last)?.row {
            adjustTableViewHieght(popupTableView: self.popupTableView,popupContainerView: self.popupContainerView , bottomConstraintValue: self.bottomConstraintValue)
        }
    }
}

    func adjustTableViewHieght(popupTableView: UITableView,popupContainerView: UIView , bottomConstraintValue:CGFloat){
        let contentSizeHeight = popupTableView.contentSize.height;
        let tableViewHieghtWithBottomSpace = popupContainerView.height - popupTableView.frame.origin.y
        let actualTableViewHieght = (tableViewHieghtWithBottomSpace - bottomConstraintValue)
        if (contentSizeHeight > actualTableViewHieght) {
            popupTableView.height = actualTableViewHieght
        } else {
            popupTableView.height = contentSizeHeight
        }
    }
</code>```

Body:
i have one table view as popUpTableView, in that i need to set table view height as dynamically as per no of rows.
i am adding in cellForRowAtIndexpath

  popupTableView.height = popupTableView.contentSize.height

it is working fine but the problem is when no of cells are increasing then the tableview height is increasing than its origingal height

extension DiagnosisViewController :UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if tableView == diagnosisTableView {
            return self.diagnosisModel.count
        } else if tableView == popupTableView {
            return self.popupDiagnosisModel.count
        }
        return 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell:DiagnosisTableViewCell?

        if tableView == self.diagnosisTableView {

            cell = self.diagnosisTableView.dequeueReusableCell(withIdentifier: "DiagnosisCell") as? DiagnosisTableViewCell

            if diagnosisModel.count > 0 {

                let model = diagnosisModel[indexPath.row]
                cell?.indexLabel.text =  String(indexPath.row + 1)
                cell?.diagnosisNameLabel.text = "  \(model.diagnosisDescription!)"
                cell?.deleteButton.tag = indexPath.row
                cell?.deleteButton.addTarget(self, action:#selector(deleteDiagnosis(button:)), for: .touchUpInside)
                diagnosisNotFoundLabel.isHidden = true

            }

        } else if tableView == self.popupTableView {

            cell = self.diagnosisTableView.dequeueReusableCell(withIdentifier: "DiagnosisCell") as? DiagnosisTableViewCell

            cell?.deleteButton.isHidden = true

            if (indexPath.row % 2 == 0) {
                cell?.baseView.backgroundColor = UIColor.white
            }
            else {
                cell?.baseView.backgroundColor = UIColor.init(colorLiteralRed: 241/255, green: 241/255, blue: 241/255, alpha: 1.0)
            }

            cell?.indexLabel.text =  String(indexPath.row + 1)
            cell?.indexView.layer.cornerRadius = (cell?.indexView.frame.size.width)!/2
            cell?.indexView.layer.borderWidth = 0.5
            cell?.indexView.layer.borderColor = UIColor.lightGray.cgColor

            cell?.baseView.layer.borderWidth = 0.5
            cell?.baseView.layer.cornerRadius = 5.0
            cell?.baseView.layer.borderColor = UIColor.lightGray.cgColor;

            if diagnosisModel.count > 0 {

                let model = popupDiagnosisModel[indexPath.row]
                cell?.diagnosisNameLabel.text = "  \(model.diagnosisDescription!)"
            }
            self.popupTableView.height = self.popupTableView.contentSize.height

        }
        return cell!
    }

}

let maxHeight = popupTableView.frame.size.height
let changeHeight = popupTableView.contentSize.height

if changeHeight < maxHeight {
popupTableView.height = changeHeight
}

how to get tableview height for only visible cells and where to place that code ??

Thanks in Advance.

Body:
take one variable which will caluculate bottomconstraint value of tableview

 var bottomConstraintValue : CGFloat = 0.0
    override func viewDidLoad() {
        super.viewDidLoad()
   bottomConstraintValue = self.popupContainerView.height - self.popupTableView.frame.origin.y - self.popupTableView.frame.size.height
     }

call delegate method willDisplay: of tableview

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

if tableView == popupTableView {
        if indexPath.row == (popupTableView.indexPathsForVisibleRows?.last)?.row {
            adjustTableViewHieght(popupTableView: self.popupTableView,popupContainerView: self.popupContainerView , bottomConstraintValue: self.bottomConstraintValue)
        }
    }
}

    func adjustTableViewHieght(popupTableView: UITableView,popupContainerView: UIView , bottomConstraintValue:CGFloat){
        let contentSizeHeight = popupTableView.contentSize.height;
        let tableViewHieghtWithBottomSpace = popupContainerView.height - popupTableView.frame.origin.y
        let actualTableViewHieght = (tableViewHieghtWithBottomSpace - bottomConstraintValue)
        if (contentSizeHeight > actualTableViewHieght) {
            popupTableView.height = actualTableViewHieght
        } else {
            popupTableView.height = contentSizeHeight
        }
    }


问:
Git submodule - How to keep the submodule updated when pulling from the main repo
We have the main git repository and one single git submodule. For this question, the main repository does only have a master branch, and the submodule does have two branches - X and Y.

Let's say Coder A just switched to submodule branch X and applied some small changes.

Coder B it's on submodule branch Y.

Now A pushes to the remote and B pulls - then it does not seem like B's active submodule commit (on their local machine) gets automatically changed to the commit that A pushed on branch X, even though A actively committed the changed submodule commit.

Instead for B, their version on branch Y stays active.

If B does now manually pull from the repository and set the branch to X, everything works again.

How can we achieve that submodule changes / active commits get automatically synced when pulling from the main repository?

We're using Source Tree as Git GUI if that makes any explanations easier.

答:
then it does not seam like B's active submodule commit (on their local machine) gets automatically changed to the commit that A pushed on branch X, even though A actively committed the changed submodule commit

You need to be sure A committed and push from the submodule, and then add/commit and push from the parent repo (in order to record the new submodule SHA1)

Since Git 1.7.5, git pull should update the submodules as well.

Double-check with a git submodule update --init --recursive

But don't forget that "updating a submodule" would only check out its SHA1, not a branch. Unless a submodule is set to track a branch, and you do a git submodule update --recursive --remote.

Even then, it would pull one branch (X or Y), not both.

A friend just told us that the repo on my friends machine might be broken. So we re-cloned it from Origin and now everything just works.

I'm now looking into tracking branches with submodules, to avoid the "checked out HEAD" issue. Can you recommend that?

As explained in the "True Nature of Submodules", a submodule is always in a detached HEAD mode at first.

You can still force it to follow a branch and update itself: see "git submodule tracking latest".

That means the following command would update the submodule content after pulling a branch said submodule must follow:

```<code>git submodule update --remote
</code>```

Body:
then it does not seam like B's active submodule commit (on their local machine) gets automatically changed to the commit that A pushed on branch X, even though A actively committed the changed submodule commit

You need to be sure A committed and push from the submodule, and then add/commit and push from the parent repo (in order to record the new submodule SHA1)

Since Git 1.7.5, git pull should update the submodules as well.

Double-check with a git submodule update --init --recursive

But don't forget that "updating a submodule" would only check out its SHA1, not a branch. Unless a submodule is set to track a branch, and you do a git submodule update --recursive --remote.

Even then, it would pull one branch (X or Y), not both.

A friend just told us that the repo on my friends machine might be broken. So we re-cloned it from Origin and now everything just works.

I'm now looking into tracking branches with submodules, to avoid the "checked out HEAD" issue. Can you recommend that?

As explained in the "True Nature of Submodules", a submodule is always in a detached HEAD mode at first.

You can still force it to follow a branch and update itself: see "git submodule tracking latest".

That means the following command would update the submodule content after pulling a branch said submodule must follow:

git submodule update --remote


答:
ls -l shows all files or directories, with their respectives names, sizes, last date and hour of modification, and also all permitions for them.

while ls -1 will list files each on separate line

Title: Can anyone please explain the output of ls -1 in Linux?

Body:
I was asked this question in one of the interviews.
Can anyone please explain