答:
You can create a model class that will store the IP information like :

```<code>public class DeviceIPAddress
{
    public string IPv4 { get; set; }

    public string MAC { get; set; }

    public string IPType { get; set; }
}
</code>```

Now, we can use this model to parse the provided list, in which will make it easier for us to handle :

```<code>var ips = new List<DeviceIPAddress>();

foreach (var ip in result)
{
    var info = ip.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    ips.Add(new DeviceIPAddress { IPv4 = info[0].Trim(), MAC = info[1].Trim(), IPType = info[2].Trim() });
}
</code>```

now using the ips list, we can manage the received data easily :

```<code>var getIP = ips.First(x => x.MAC.Equals("a8-3e-0e-61-3f-db", StringComparison.InvariantCultureIgnoreCase));
// call getIP.IPv4 will to get the IP 192.168.137.44
</code>```

Title: Use "arp -a" to retreive MAC address of corresponding IP Adress

Body:
You can create a model class that will store the IP information like :

public class DeviceIPAddress
{
    public string IPv4 { get; set; }

    public string MAC { get; set; }

    public string IPType { get; set; }
}

Now, we can use this model to parse the provided list, in which will make it easier for us to handle :

var ips = new List<DeviceIPAddress>();

foreach (var ip in result)
{
    var info = ip.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    ips.Add(new DeviceIPAddress { IPv4 = info[0].Trim(), MAC = info[1].Trim(), IPType = info[2].Trim() });
}

now using the ips list, we can manage the received data easily :

var getIP = ips.First(x => x.MAC.Equals("a8-3e-0e-61-3f-db", StringComparison.InvariantCultureIgnoreCase));
// call getIP.IPv4 will to get the IP 192.168.137.44


来源: stackexchange

问:
Missing "Ado.Net Entity Data Model" on Visual Studio 2013
I have created new web project but I can't find ADO.net Entity DAta Model to add it.

How to fix it or Install it ?

答: Be sure you are trying to do that in .Net Framework project. For example, when you are creating a project do not use a template called Windows Forms App (.Net Core), use Windows Forms <strong>(.Net Framework)</strong>. The (.Net Framework) extension is important. </p>

ContentLicense: CC BY-SA 3.0

Body: Be sure you are trying to do that in .Net Framework project. For example, when you are creating a project do not use a template called Windows Forms App (.Net Core), use Windows Forms (.Net Framework). The (.Net Framework) extension is important.

ContentLicense: CC BY-SA 4.0


问:
Spring DataSize class not found
I'm trying to run an appliaction using spring framework, but an exception is always raised :

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/util/unit/DataSize
    at org.springframework.boot.convert.StringToDataSizeConverter.getConvertibleTypes(StringToDataSizeConverter.java:40)
    at org.springframework.core.convert.support.GenericConversionService$Converters.add(GenericConversionService.java:507)
    at org.springframework.core.convert.support.GenericConversionService.addConverter(GenericConversionService.java:105)
    at org.springframework.boot.convert.ApplicationConversionService.addApplicationConverters(ApplicationConversionService.java:107)
    at org.springframework.boot.convert.ApplicationConversionService.configure(ApplicationConversionService.java:91)
    at org.springframework.boot.convert.ApplicationConversionService.<init>(ApplicationConversionService.java:52)
    at org.springframework.boot.convert.ApplicationConversionService.<init>(ApplicationConversionService.java:45)
    at org.springframework.boot.convert.ApplicationConversionService.getSharedInstance(ApplicationConversionService.java:71)
    at org.springframework.boot.SpringApplication.configureEnvironment(SpringApplication.java:472)
    at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:340)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:305)
    at fr.edf.as.meteo.MeteoedfApp.main(MeteoedfApp.java:67)
Caused by: java.lang.ClassNotFoundException: org.springframework.util.unit.DataSize
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 12 more
</code>```

There are 2 modules : commons and editic, both of them has a pom.xml file :

commons 'pom :

```<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">
    <parent>
        <artifactId>meteoedf</artifactId>
        <groupId>fr.edf.as.meteo</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>commons</artifactId>
    <packaging>war</packaging>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>fr.edf.as.meteo</groupId>
            <artifactId>editic</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>net.logstash.logback</groupId>
            <artifactId>logstash-logback-encoder</artifactId>
            <version>5.2</version>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        <dependency>
            <groupId>io.github.jhipster</groupId>
            <artifactId>jhipster-framework</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.7</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>5.0.11.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-envers</artifactId>
            <version>5.2.17.Final</version>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.11.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.6.2</version>
        </dependency>
        <dependency>
            <groupId>org.zalando</groupId>
            <artifactId>problem</artifactId>
            <version>0.21.0</version>
        </dependency>
        <dependency>
            <groupId>org.zalando</groupId>
            <artifactId>problem-violations</artifactId>
            <version>0.24.0-RC.0</version>
        </dependency>
        <dependency>
            <groupId>org.zalando</groupId>
            <artifactId>problem-spring-web</artifactId>
            <version>0.24.0-RC.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>3.5.3</version>
        </dependency>
        <dependency>
            <groupId>javax.cache</groupId>
            <artifactId>cache-api</artifactId>
            <version>1.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-spring-service-connector</artifactId>
            <version>2.0.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.liquibase</groupId>
            <artifactId>liquibase-core</artifactId>
            <version>3.5.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-hibernate5</artifactId>
            <version>2.9.8</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-afterburner</artifactId>
            <version>2.9.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>5.0.11.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>io.undertow</groupId>
            <artifactId>undertow-core</artifactId>
            <version>1.4.26.Final</version>
        </dependency>
        <dependency>
            <groupId>io.github.jhipster</groupId>
            <artifactId>jhipster-framework</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
    </dependencies>

</project>
</code>```

**editic's pom : **

```<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">
    <parent>
        <groupId>fr.edf.as.meteo</groupId>
        <artifactId>meteoedf</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <groupId>fr.edf.as.meteo</groupId>
    <artifactId>editic</artifactId>
    <packaging>jar</packaging>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.0.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.12.RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.2.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.0.13.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.0.12.RELEASE</version>
        </dependency>
    </dependencies>

</project>
</code>```

**And the main pom : **

```<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>fr.edf.as.meteo</groupId>
    <artifactId>meteoedf</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <modules>
        <module>editic</module>
        <module>commons</module>
    </modules>
    <packaging>pom</packaging>
    <name>Meteoedf</name>

    <repositories>
    <!-- more information at https://blogs.oracle.com/dev2dev/entry/how_to_get_oracle_jdbc -->
        <repository>
            <id>maven.oracle.com</id>
            <name>oracle-maven-repo</name>
            <url>https://maven.oracle.com</url>
            <layout>default</layout>
            <releases>
                <enabled>true</enabled>
                <updatePolicy>always</updatePolicy>
            </releases>
        </repository>
        <!-- jhipster-needle-mafr.edf.as.meteo.editic.repositorytory -->
    </repositories>

    <pluginRepositories>
        <!-- jhipster-needle-maven-plufr.edf.as.meteo.editic.repositorytory -->
    </pluginRepositories>

    <!-- jhipster-needle-distribution-management -->

    <properties>
        <!-- Build properties -->
        <maven.version>3.0.0</maven.version>
        <java.version>1.8</java.version>
        <scala.version>2.12.6</scala.version>
        <node.version>v10.15.0</node.version>
        <npm.version>6.4.1</npm.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <project.testresult.directory>${project.build.directory}/test-results</project.testresult.directory>
        <maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format>
        <argLine>-Djava.security.egd=file:/dev/./urandom -Xmx256m</argLine>
        <m2e.apt.activation>jdt_apt</m2e.apt.activation>
        <run.addResources>false</run.addResources>
        <!-- These remain empty unless the corresponding profile is active -->
        <profile.no-liquibase />
        <profile.swagger />
        <profile.tls />

        <!-- Dependency versions -->
        <jhipster-dependencies.version>2.1.1</jhipster-dependencies.version>
        <!-- The spring-boot version should match the one managed by
        https://mvnrepository.com/artifact/io.github.jhipster/jhipster-dependencies/${jhipster-dependencies.version} -->
        <spring-boot.version>2.1.8.RELEASE</spring-boot.version>
        <!-- The hibernate version should match the one managed by
        https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-dependencies/${spring-boot.version} -->
        <hibernate.version>5.2.17.Final</hibernate.version>
        <!-- The javassist version should match the one managed by
        https://mvnrepository.com/artifact/org.hibernate/hibernate-core/${hibernate.version} -->
        <javassist.version>3.22.0-GA</javassist.version>
        <!-- The liquibase version should match the one managed by
        https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-dependencies/${spring-boot.version} -->
        <liquibase.version>3.5.5</liquibase.version>
        <liquibase-hibernate5.version>3.6</liquibase-hibernate5.version>
        <validation-api.version>2.0.1.Final</validation-api.version>
        <mapstruct.version>1.2.0.Final</mapstruct.version>

        <!-- Sonar properties -->
        <sonar.host.url>http://localhost:9001</sonar.host.url>
        <sonar.exclusions>commons/src/main/webapp/content/**/*.*, commons/src/main/webapp/i18n/*.js, commons/target/www/**/*.*</sonar.exclusions>
        <sonar.issue.ignore.multicriteria>S3437,S4684,UndocumentedApi,BoldAndItalicTagsCheck</sonar.issue.ignore.multicriteria>
        <!-- Rule https://sonarcloud.io/coding_rules?open=Web%3ABoldAndItalicTagsCheck&rule_key=Web%3ABoldAndItalicTagsCheck is ignored. Even if we agree that using the "i" tag is an awful practice, this is what is recommended by http://fontawesome.io/examples/ -->
        <sonar.issue.ignore.multicriteria.BoldAndItalicTagsCheck.resourceKey>src/main/webapp/app/**/*.*</sonar.issue.ignore.multicriteria.BoldAndItalicTagsCheck.resourceKey>
        <sonar.issue.ignore.multicriteria.BoldAndItalicTagsCheck.ruleKey>Web:BoldAndItalicTagsCheck</sonar.issue.ignore.multicriteria.BoldAndItalicTagsCheck.ruleKey>
        <!-- Rule https://sonarcloud.io/coding_rules?open=squid%3AS3437&rule_key=squid%3AS3437 is ignored, as a JPA-managed field cannot be transient -->
        <sonar.issue.ignore.multicriteria.S3437.resourceKey>src/main/java/**/*</sonar.issue.ignore.multicriteria.S3437.resourceKey>
        <sonar.issue.ignore.multicriteria.S3437.ruleKey>squid:S3437</sonar.issue.ignore.multicriteria.S3437.ruleKey>
        <!-- Rule https://sonarcloud.io/coding_rules?open=squid%3AUndocumentedApi&rule_key=squid%3AUndocumentedApi is ignored, as we want to follow "clean code" guidelines and classes, methods and arguments names should be self-explanatory -->
        <sonar.issue.ignore.multicriteria.UndocumentedApi.resourceKey>src/main/java/**/*</sonar.issue.ignore.multicriteria.UndocumentedApi.resourceKey>
        <sonar.issue.ignore.multicriteria.UndocumentedApi.ruleKey>squid:UndocumentedApi</sonar.issue.ignore.multicriteria.UndocumentedApi.ruleKey>
        <!-- Rule https://sonarcloud.io/coding_rules?open=squid%3AS4684&rule_key=squid%3AS4684 -->
        <sonar.issue.ignore.multicriteria.S4684.resourceKey>src/main/java/**/*</sonar.issue.ignore.multicriteria.S4684.resourceKey>
        <sonar.issue.ignore.multicriteria.S4684.ruleKey>squid:S4684</sonar.issue.ignore.multicriteria.S4684.ruleKey>
        <sonar.jacoco.reportPaths>${project.testresult.directory}/coverage/jacoco/jacoco.exec</sonar.jacoco.reportPaths>
        <sonar.java.codeCoveragePlugin>jacoco</sonar.java.codeCoveragePlugin>
        <sonar.typescript.lcov.reportPaths>${project.testresult.directory}/lcov.info</sonar.typescript.lcov.reportPaths>
        <sonar.sources>${project.basedir}/src/main/</sonar.sources>
        <sonar.junit.reportsPath>${project.testresult.directory}</sonar.junit.reportsPath>
        <sonar.tests>${project.basedir}/src/test/</sonar.tests>

        <!-- jhipster-needle-maven-property -->
    </properties>

</project>
</code>```

I searched on the Internet but it seems like this error isn't common, and might be linked with dependencies' version ?

Thank you

答:
Problem is mismatching Spring Boot (2.1.8.RELEASE) and Spring Core (5.0.12) versions. Core is 5.0.12, because it is transitive dependency of spring-beans 5.0.12.

DataSize is part Spring Core since 5.1. Boot version 2.1.x expects Core 5.1, as one can see from release notes. Exact version one can found from pom.xml.

One can of course define versions manually, but that is lot of works - especially when Spring Boot version changes:

```<code><dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.1.9.RELEASE</version>
</dependency>
</code>```

Because it is rather tedious (though doable) to match versions manually, one should use spring-boot-dependencies in depencyManagement (link to documentation):

```<code><dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.1.8.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
</code>```

And remove version from dependencies such as spring-beans and spring-context etc.:

```<code><dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
</dependency>
</code>```

Version should be defined (instead of inheriting from spring-boot-dependencies) only if there is valid reason to use some other version.

Title: Spring DataSize class not found

Body:
I'm trying to run an appliaction using spring framework, but an exception is always raised :

Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/util/unit/DataSize
    at org.springframework.boot.convert.StringToDataSizeConverter.getConvertibleTypes(StringToDataSizeConverter.java:40)
    at org.springframework.core.convert.support.GenericConversionService$Converters.add(GenericConversionService.java:507)
    at org.springframework.core.convert.support.GenericConversionService.addConverter(GenericConversionService.java:105)
    at org.springframework.boot.convert.ApplicationConversionService.addApplicationConverters(ApplicationConversionService.java:107)
    at org.springframework.boot.convert.ApplicationConversionService.configure(ApplicationConversionService.java:91)
    at org.springframework.boot.convert.ApplicationConversionService.<init>(ApplicationConversionService.java:52)
    at org.springframework.boot.convert.ApplicationConversionService.<init>(ApplicationConversionService.java:45)
    at org.springframework.boot.convert.ApplicationConversionService.getSharedInstance(ApplicationConversionService.java:71)
    at org.springframework.boot.SpringApplication.configureEnvironment(SpringApplication.java:472)
    at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:340)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:305)
    at fr.edf.as.meteo.MeteoedfApp.main(MeteoedfApp.java:67)
Caused by: java.lang.ClassNotFoundException: org.springframework.util.unit.DataSize
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 12 more

There are 2 modules : commons and editic, both of them has a pom.xml file :

commons 'pom :

<?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">
    <parent>
        <artifactId>meteoedf</artifactId>
        <groupId>fr.edf.as.meteo</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>commons</artifactId>
    <packaging>war</packaging>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>fr.edf.as.meteo</groupId>
            <artifactId>editic</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>net.logstash.logback</groupId>
            <artifactId>logstash-logback-encoder</artifactId>
            <version>5.2</version>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        <dependency>
            <groupId>io.github.jhipster</groupId>
            <artifactId>jhipster-framework</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.7</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>5.0.11.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-envers</artifactId>
            <version>5.2.17.Final</version>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.11.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.6.2</version>
        </dependency>
        <dependency>
            <groupId>org.zalando</groupId>
            <artifactId>problem</artifactId>
            <version>0.21.0</version>
        </dependency>
        <dependency>
            <groupId>org.zalando</groupId>
            <artifactId>problem-violations</artifactId>
            <version>0.24.0-RC.0</version>
        </dependency>
        <dependency>
            <groupId>org.zalando</groupId>
            <artifactId>problem-spring-web</artifactId>
            <version>0.24.0-RC.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>3.5.3</version>
        </dependency>
        <dependency>
            <groupId>javax.cache</groupId>
            <artifactId>cache-api</artifactId>
            <version>1.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-spring-service-connector</artifactId>
            <version>2.0.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.liquibase</groupId>
            <artifactId>liquibase-core</artifactId>
            <version>3.5.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-hibernate5</artifactId>
            <version>2.9.8</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-afterburner</artifactId>
            <version>2.9.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>5.0.11.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>io.undertow</groupId>
            <artifactId>undertow-core</artifactId>
            <version>1.4.26.Final</version>
        </dependency>
        <dependency>
            <groupId>io.github.jhipster</groupId>
            <artifactId>jhipster-framework</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
    </dependencies>

</project>

**editic's pom : **

<?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">
    <parent>
        <groupId>fr.edf.as.meteo</groupId>
        <artifactId>meteoedf</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <groupId>fr.edf.as.meteo</groupId>
    <artifactId>editic</artifactId>
    <packaging>jar</packaging>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.0.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.12.RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.2.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.0.13.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.0.12.RELEASE</version>
        </dependency>
    </dependencies>

</project>

**And the main pom : **

<?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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>fr.edf.as.meteo</groupId>
    <artifactId>meteoedf</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <modules>
        <module>editic</module>
        <module>commons</module>
    </modules>
    <packaging>pom</packaging>
    <name>Meteoedf</name>

    <repositories>

        <repository>
            <id>maven.oracle.com</id>
            <name>oracle-maven-repo</name>
            <url>https://maven.oracle.com</url>
            <layout>default</layout>
            <releases>
                <enabled>true</enabled>
                <updatePolicy>always</updatePolicy>
            </releases>
        </repository>

    </repositories>

    <pluginRepositories>

    </pluginRepositories>

    <properties>

        <maven.version>3.0.0</maven.version>
        <java.version>1.8</java.version>
        <scala.version>2.12.6</scala.version>
        <node.version>v10.15.0</node.version>
        <npm.version>6.4.1</npm.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <project.testresult.directory>${project.build.directory}/test-results</project.testresult.directory>
        <maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format>
        <argLine>-Djava.security.egd=file:/dev/./urandom -Xmx256m</argLine>
        <m2e.apt.activation>jdt_apt</m2e.apt.activation>
        <run.addResources>false</run.addResources>

        <profile.no-liquibase />
        <profile.swagger />
        <profile.tls />

        <jhipster-dependencies.version>2.1.1</jhipster-dependencies.version>

        <spring-boot.version>2.1.8.RELEASE</spring-boot.version>

        <hibernate.version>5.2.17.Final</hibernate.version>

        <javassist.version>3.22.0-GA</javassist.version>

        <liquibase.version>3.5.5</liquibase.version>
        <liquibase-hibernate5.version>3.6</liquibase-hibernate5.version>
        <validation-api.version>2.0.1.Final</validation-api.version>
        <mapstruct.version>1.2.0.Final</mapstruct.version>

        <sonar.host.url>http://localhost:9001</sonar.host.url>
        <sonar.exclusions>commons/src/main/webapp/content/**/*.*, commons/src/main/webapp/i18n/*.js, commons/target/www/**/*.*</sonar.exclusions>
        <sonar.issue.ignore.multicriteria>S3437,S4684,UndocumentedApi,BoldAndItalicTagsCheck</sonar.issue.ignore.multicriteria>

        <sonar.issue.ignore.multicriteria.BoldAndItalicTagsCheck.resourceKey>src/main/webapp/app/**/*.*</sonar.issue.ignore.multicriteria.BoldAndItalicTagsCheck.resourceKey>
        <sonar.issue.ignore.multicriteria.BoldAndItalicTagsCheck.ruleKey>Web:BoldAndItalicTagsCheck</sonar.issue.ignore.multicriteria.BoldAndItalicTagsCheck.ruleKey>

        <sonar.issue.ignore.multicriteria.S3437.resourceKey>src/main/java/**/*</sonar.issue.ignore.multicriteria.S3437.resourceKey>
        <sonar.issue.ignore.multicriteria.S3437.ruleKey>squid:S3437</sonar.issue.ignore.multicriteria.S3437.ruleKey>

        <sonar.issue.ignore.multicriteria.UndocumentedApi.resourceKey>src/main/java/**/*</sonar.issue.ignore.multicriteria.UndocumentedApi.resourceKey>
        <sonar.issue.ignore.multicriteria.UndocumentedApi.ruleKey>squid:UndocumentedApi</sonar.issue.ignore.multicriteria.UndocumentedApi.ruleKey>

        <sonar.issue.ignore.multicriteria.S4684.resourceKey>src/main/java/**/*</sonar.issue.ignore.multicriteria.S4684.resourceKey>
        <sonar.issue.ignore.multicriteria.S4684.ruleKey>squid:S4684</sonar.issue.ignore.multicriteria.S4684.ruleKey>
        <sonar.jacoco.reportPaths>${project.testresult.directory}/coverage/jacoco/jacoco.exec</sonar.jacoco.reportPaths>
        <sonar.java.codeCoveragePlugin>jacoco</sonar.java.codeCoveragePlugin>
        <sonar.typescript.lcov.reportPaths>${project.testresult.directory}/lcov.info</sonar.typescript.lcov.reportPaths>
        <sonar.sources>${project.basedir}/src/main/</sonar.sources>
        <sonar.junit.reportsPath>${project.testresult.directory}</sonar.junit.reportsPath>
        <sonar.tests>${project.basedir}/src/test/</sonar.tests>

    </properties>

</project>

I searched on the Internet but it seems like this error isn't common, and might be linked with dependencies' version ?

Thank you

Body:
Problem is mismatching Spring Boot (2.1.8.RELEASE) and Spring Core (5.0.12) versions. Core is 5.0.12, because it is transitive dependency of spring-beans 5.0.12.

DataSize is part Spring Core since 5.1. Boot version 2.1.x expects Core 5.1, as one can see from release notes. Exact version one can found from pom.xml.

One can of course define versions manually, but that is lot of works - especially when Spring Boot version changes:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.1.9.RELEASE</version>
</dependency>

Because it is rather tedious (though doable) to match versions manually, one should use spring-boot-dependencies in depencyManagement (link to documentation):

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.1.8.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

And remove version from dependencies such as spring-beans and spring-context etc.:

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

Version should be defined (instead of inheriting from spring-boot-dependencies) only if there is valid reason to use some other version.


问:
jwilder/nginx giving 403 permission forbidden
I'm trying to serve multiple containers with a static index.html file with a nginx reverse proxy

I've tried to follow the documentation here to create a default location

```<code>location / {
  root   /app;
  index  index.html;
  try_files $uri $uri/ /index.html;
}
</code>```

If I check my default.conf in my container with

```<code>$ docker-compose exec nginx-proxy cat /etc/nginx/conf.d/default.conf
</code>```

I get this result:

```<code>server {
        server_name _; # This is just an invalid value which will never trigger on a real hostname.
        listen 80;
        access_log /var/log/nginx/access.log vhost;
        return 503;
}
# xx.example.services
upstream xx.example.services {
                                ## Can be connected with "nginx-proxy" network
                        # examplecontainer1
                        server 172.18.0.4:80;
}
server {
        server_name xx.example.services;
        listen 80 ;
        access_log /var/log/nginx/access.log vhost;
        location / {
                proxy_pass http://xx.example.services;
                include /etc/nginx/vhost.d/default_location;
        }
}
# yy.example.services
upstream yy.example.services {
                                ## Can be connected with "nginx-proxy" network
                        # examplecontainer2
                        server 172.18.0.2:80;
}
server {
        server_name yy.example.services;
        listen 80 ;
        access_log /var/log/nginx/access.log vhost;
        location / {
                proxy_pass http://yy.example.services;
                include /etc/nginx/vhost.d/default_location;
        }
}
</code>```

If i check the content of /etc/nginx/vhost.d/default_location it is exactly what I typed in the beginning, so that's fine

However when i go to xx.example.services  I get a 403 forbidden.

To my understanding this means that no index.html file was found, but if i exec into my container and cat app/index.html it does exist!

I've checked that all my containers are on the same network.

I'm running my container with this command

```<code>docker run -d --name examplecontainer1 --expose 80 --net nginx-proxy -e VIRTUAL_HOST=xx.example.services my-container-registry
</code>```

Update
I checked the logs of my nginx-proxy container and found this error message:

[error] 29#29: *1 directory index of "/app/" is forbidden..

Tried removing $uri/ as per this SO post but this just left me with redirect cycles. Right now I'm trying to see if I can set the correct permissions, but I'm struggling

What am I missing?

答: Hi its simple your containers is missing /app/index.html inside them</p>

Body:
I'm trying to serve multiple containers with a static index.html file with a nginx reverse proxy

I've tried to follow the documentation here to create a default location

location / {
  root   /app;
  index  index.html;
  try_files $uri $uri/ /index.html;
}

If I check my default.conf in my container with

$ docker-compose exec nginx-proxy cat /etc/nginx/conf.d/default.conf

I get this result:

server {
        server_name _; # This is just an invalid value which will never trigger on a real hostname.
        listen 80;
        access_log /var/log/nginx/access.log vhost;
        return 503;
}
# xx.example.services
upstream xx.example.services {
                                ## Can be connected with "nginx-proxy" network
                        # examplecontainer1
                        server 172.18.0.4:80;
}
server {
        server_name xx.example.services;
        listen 80 ;
        access_log /var/log/nginx/access.log vhost;
        location / {
                proxy_pass http://xx.example.services;
                include /etc/nginx/vhost.d/default_location;
        }
}
# yy.example.services
upstream yy.example.services {
                                ## Can be connected with "nginx-proxy" network
                        # examplecontainer2
                        server 172.18.0.2:80;
}
server {
        server_name yy.example.services;
        listen 80 ;
        access_log /var/log/nginx/access.log vhost;
        location / {
                proxy_pass http://yy.example.services;
                include /etc/nginx/vhost.d/default_location;
        }
}

If i check the content of /etc/nginx/vhost.d/default_location it is exactly what I typed in the beginning, so that's fine

However when i go to xx.example.services  I get a 403 forbidden.

To my understanding this means that no index.html file was found, but if i exec into my container and cat app/index.html it does exist!

I've checked that all my containers are on the same network.

I'm running my container with this command

docker run -d --name examplecontainer1 --expose 80 --net nginx-proxy -e VIRTUAL_HOST=xx.example.services my-container-registry

Update
I checked the logs of my nginx-proxy container and found this error message:

[error] 29#29: *1 directory index of "/app/" is forbidden..

Tried removing $uri/ as per this SO post but this just left me with redirect cycles. Right now I'm trying to see if I can set the correct permissions, but I'm struggling

What am I missing?


问:
React Child component not sent the updated state from parent
I am trying to follow the react tutorial on their official site: https://reactjs.org/tutorial/tutorial.html

Only difference is I am trying to implement it by only using functional components, here is my code on code pen:

  See the Pen
  React tutorial functional component by Snedden Gonsalves (@snedden-gonsalves)
  on CodePen.

To summarize; I have simple square component that draws individual squares, a parent board component that draws a 3x3 square board and an overarching game component that maintains state ,like history, current square, current turn etc as in the tutorial.
I currently send the squares from the parent game-component to board components like so :

```<code><Board
   onClick ={(i)=>{handleClick(i)}}
   squares = {state.history[state.history.length - 1]}
</code>```

/>

The handleClick creates new squares state and appends it to the history array which I assume should be dynamically passed as I also pass the last entry in the array , but it doesn't look it passes the last entry at all to the child components. Not sure what is happening..

Thanks for you time.

Components:

Square:

```<code> const Square = (props)=>{
        return(
            <button className="square" onClick={(e)=>props.onClick()}>
                {props.value}
            </button>
        )
    }
</code>```

Board:

```<code>const Board = (props) => {
    const renderSquare = (i)=>{
        return <Square
            value={props.squares[i]}
            onClick={() => {
                props.onClick(i)
                }
            }
        />
    }
    return(
        <div>
            <div className="board-row">
                {renderSquare(0)}
                {renderSquare(1)}
                {renderSquare(2)}
            </div>
            <div className="board-row">
                {renderSquare(3)}
                {renderSquare(4)}
                {renderSquare(5)}
            </div>
            <div className="board-row">
                {renderSquare(6)}
                {renderSquare(7)}
                {renderSquare(8)}
            </div>
        </div>
    )
}
</code>```

Game:

```<code>const Game = () =>{
    let [state, setState] = useState({
        history:[{
            squares:Array(9).fill(null)
        }],
        isXNext:true,
        status:'Next player X'
    });

    useEffect(() =>{
        const currentSquares = state.history[state.history.length - 1].squares;
        const winner = calculateWinner(currentSquares);
        if(winner){
            setState( state => ({...state, status:'Winner is ' + winner, ended:true}));
        }
    },[state.history]);

    const handleClick = (i) =>{
        const currentSquares = state.history[state.history.length - 1].squares;

        if(state.ended || currentSquares[i])
            return;

        const newSquares = currentSquares.slice();
        newSquares[i] = state.isXNext?'X':'O';

        const newIsXNext = !state.isXNext;
        const newHistory = state.history.concat([
            {squares:newSquares}]);

        setState(state => ({...state,
            history: newHistory,
            isXNext: newIsXNext,
            status:'Next player ' + (newIsXNext?'X':'O')
        }));

    }

    return(
        <div className="game">
            <div className="game-board">
                <Board
                    onClick ={(i)=>{handleClick(i)}}
                    squares = {state.history[state.history.length - 1]}
                />
            </div>
            <div className="game-info">
                <div>{state.status}</div>
                <ol>{/* TODO */}</ol>
            </div>
        </div>
    );
}
</code>```

答:
So turns out it was passing  the updated state I was not using the right key, this is how I fixed it:

```<code><Board
    onClick ={(i)=>{handleClick(i)}}
    squares = {state.history[state.history.length - 1].squares}/>
</code>```

Working code pen:

  See the Pen
  React tutorial functional component Working by Snedden Gonsalves (@snedden-gonsalves)
  on CodePen.

Body:
I am trying to follow the react tutorial on their official site: https://reactjs.org/tutorial/tutorial.html

Only difference is I am trying to implement it by only using functional components, here is my code on code pen:

  See the Pen
  React tutorial functional component by Snedden Gonsalves (@snedden-gonsalves)
  on CodePen.

To summarize; I have simple square component that draws individual squares, a parent board component that draws a 3x3 square board and an overarching game component that maintains state ,like history, current square, current turn etc as in the tutorial.
I currently send the squares from the parent game-component to board components like so :

<Board
   onClick ={(i)=>{handleClick(i)}}
   squares = {state.history[state.history.length - 1]}

/>

The handleClick creates new squares state and appends it to the history array which I assume should be dynamically passed as I also pass the last entry in the array , but it doesn't look it passes the last entry at all to the child components. Not sure what is happening..

Thanks for you time.

Components:

Square:

 const Square = (props)=>{
        return(
            <button className="square" onClick={(e)=>props.onClick()}>
                {props.value}
            </button>
        )
    }

Board:

const Board = (props) => {
    const renderSquare = (i)=>{
        return <Square
            value={props.squares[i]}
            onClick={() => {
                props.onClick(i)
                }
            }
        />
    }
    return(

                {renderSquare(0)}
                {renderSquare(1)}
                {renderSquare(2)}

                {renderSquare(3)}
                {renderSquare(4)}
                {renderSquare(5)}

                {renderSquare(6)}
                {renderSquare(7)}
                {renderSquare(8)}

    )
}

Game:

const Game = () =>{
    let [state, setState] = useState({
        history:[{
            squares:Array(9).fill(null)
        }],
        isXNext:true,
        status:'Next player X'
    });

    useEffect(() =>{
        const currentSquares = state.history[state.history.length - 1].squares;
        const winner = calculateWinner(currentSquares);
        if(winner){
            setState( state => ({...state, status:'Winner is ' + winner, ended:true}));
        }
    },[state.history]);

    const handleClick = (i) =>{
        const currentSquares = state.history[state.history.length - 1].squares;

        if(state.ended || currentSquares[i])
            return;

        const newSquares = currentSquares.slice();
        newSquares[i] = state.isXNext?'X':'O';

        const newIsXNext = !state.isXNext;
        const newHistory = state.history.concat([
            {squares:newSquares}]);

        setState(state => ({...state,
            history: newHistory,
            isXNext: newIsXNext,
            status:'Next player ' + (newIsXNext?'X':'O')
        }));

    }

    return(

                <Board
                    onClick ={(i)=>{handleClick(i)}}
                    squares = {state.history[state.history.length - 1]}
                />

{state.status}

{/* TODO */}

    );
}

Body:
So turns out it was passing  the updated state I was not using the right key, this is how I fixed it:

<Board
    onClick ={(i)=>{handleClick(i)}}
    squares = {state.history[state.history.length - 1].squares}/>

Working code pen:

  See the Pen
  React tutorial functional component Working by Snedden Gonsalves (@snedden-gonsalves)
  on CodePen.


问:
Recursive parse JSON with c#
I try to do a recursive parse but it doesn't work, it only parse the first title.

I already tried that: C# parse recursive json but it didn't work.

I also tried a parse with Regex but it didn't work either, it only captures the first title.

So I'm hoping you can help me solve the problem that's been blocking my progress :/

My Json

```<code>{
   "data":{
      "count":[

      ],
      "list":[
         {
            "title":"new doc 4",
            "rotate":0,
            "sort_key":"new doc 4",
            "tag_ids":"",
            "doc_id":"ee4DM4Ly7CFBM3JFWAW60TUX",
            "co_token":"",
            "p":"XQXLDEQyA2hf6BBfyXhSaUHL",
            "t":"1474932063",
            "c":"2",
            "updated":"1474932063"
         },
         {
            "title":"new doc 5",
            "rotate":0,
            "sort_key":"new doc 5",
            "tag_ids":"",
            "doc_id":"Xy67QdRhTR9XS159WLyCCTbK",
            "co_token":"",
            "p":"XadS23UUQbQRQt9gLPWDWTAQ",
            "t":"1474932060",
            "c":"1",
            "updated":"1474932061"
         },
         {
            "title":"new doc 6",
            "rotate":0,
            "sort_key":"new doc 6",
            "tag_ids":"",
            "doc_id":"Q4W55XLA1AeERUJHaVN7EF80",
            "co_token":"",
            "p":"T6BYAMKXNa086Tb4FaYd4rV1",
            "t":"1474932059",
            "c":"1",
            "updated":"1474932059"
         },
         {
            "title":"new doc 7",
            "rotate":0,
            "sort_key":"new doc 7",
            "tag_ids":"",
            "doc_id":"9heQFfeYFUFXb536VTyHLhKL",
            "co_token":"",
            "p":"BeFULN12QL6H9L5HXCAYfH1S",
            "t":"1474932056",
            "c":"2",
            "updated":"1474932056"
         },
         {
            "title":"new doc 8",
            "rotate":0,
            "sort_key":"new doc 8",
            "tag_ids":"",
            "doc_id":"H7eXd1yTfFAY2V8ha3a6FS9K",
            "co_token":"",
            "p":"LJVyNVCPMbXH2abMMbb6BRYN",
            "t":"1474932053",
            "c":"1",
            "updated":"1474932053"
         },
         {
            "title":"new doc 9",
            "rotate":0,
            "sort_key":"new doc 9",
            "tag_ids":"",
            "doc_id":"3VVL56tQDXf73V8UKXrNX0d0",
            "co_token":"",
            "p":"rV2H7WWCRy1Vrb0PaU1TQKTD",
            "t":"1474932047",
            "c":"3",
            "updated":"1474932049"
         },
         {
            "title":"new doc 10",
            "rotate":0,
            "sort_key":"new doc 10",
            "tag_ids":"",
            "doc_id":"4TBabHAKNRXdREJXNdWfQEWF",
            "co_token":"",
            "p":"TR7Dt89gV3hfSJBTDQ1JQP72",
            "t":"1474402937",
            "c":"1",
            "updated":"1474402937"
         },
         {
            "title":"new doc 11",
            "rotate":0,
            "sort_key":"new doc 11",
            "tag_ids":"",
            "doc_id":"TV4fBdehY4fFHN00g082QDKX",
            "co_token":"",
            "p":"SCUPQ9bW6BgTT9JAP4K2WCYU",
            "t":"1474402932",
            "c":"3",
            "updated":"1474402932"
         },
         {
            "title":"new doc 12",
            "rotate":0,
            "sort_key":"new doc 12",
            "tag_ids":"",
            "doc_id":"M8fHK8gQB3FWUEeLKQMdUaFB",
            "co_token":"",
            "p":"BPDTg3aTTDELyFUA1WK0M2rA",
            "t":"1474402911",
            "c":"7",
            "updated":"1474402913"
         },
         {
            "title":"new doc",
            "rotate":0,
            "sort_key":"new doc",
            "tag_ids":"",
            "doc_id":"ayCK8RrHSe796g4PSNRgMD5N",
            "co_token":"",
            "p":"Y46RWJFb0XJRHtKy6B077Me1",
            "t":"1389379718",
            "c":"1",
            "updated":"1389379718"
         }
      ],
   }
}
</code>```

答:
I used Newtonsoft.Json package to convert json from file data.json which contains the json data    </p>

```<code>class Program
{
    static void Main(string[] args)
    {
        LoadJson();
    }

    public static void LoadJson()
    {
        using (StreamReader r = new StreamReader(@"C:\\Users\\user\\source\\repos\\RecursiveParseJSON\\RecursiveParseJSON\\data.json"))
        {
            string json = r.ReadToEnd();
            JsonObject datas = JsonConvert.DeserializeObject<JsonObject>(json);
        }
    }
}

public class JsonObject
{
    public Data data { get; set; }
}
public class Data
{
    public List<string> count { get; set; }
    public List<Doc> list { get; set; }
}

public class Doc
{
    public string title { get; set; }
    public int rotate { get; set; }
    public string sort_key { get; set; }
    public string tag_ids { get; set; }
    public string doc_id { get; set; }
    public string co_token { get; set; }
    public string p { get; set; }
    public string t { get; set; }
    public string c { get; set; }
    public string updated { get; set; }
}
</code>```

Title: Recursive parse JSON with c#

Body:
I try to do a recursive parse but it doesn't work, it only parse the first title.

I already tried that: C# parse recursive json but it didn't work.

I also tried a parse with Regex but it didn't work either, it only captures the first title.

So I'm hoping you can help me solve the problem that's been blocking my progress :/

My Json

{
   "data":{
      "count":[

      ],
      "list":[
         {
            "title":"new doc 4",
            "rotate":0,
            "sort_key":"new doc 4",
            "tag_ids":"",
            "doc_id":"ee4DM4Ly7CFBM3JFWAW60TUX",
            "co_token":"",
            "p":"XQXLDEQyA2hf6BBfyXhSaUHL",
            "t":"1474932063",
            "c":"2",
            "updated":"1474932063"
         },
         {
            "title":"new doc 5",
            "rotate":0,
            "sort_key":"new doc 5",
            "tag_ids":"",
            "doc_id":"Xy67QdRhTR9XS159WLyCCTbK",
            "co_token":"",
            "p":"XadS23UUQbQRQt9gLPWDWTAQ",
            "t":"1474932060",
            "c":"1",
            "updated":"1474932061"
         },
         {
            "title":"new doc 6",
            "rotate":0,
            "sort_key":"new doc 6",
            "tag_ids":"",
            "doc_id":"Q4W55XLA1AeERUJHaVN7EF80",
            "co_token":"",
            "p":"T6BYAMKXNa086Tb4FaYd4rV1",
            "t":"1474932059",
            "c":"1",
            "updated":"1474932059"
         },
         {
            "title":"new doc 7",
            "rotate":0,
            "sort_key":"new doc 7",
            "tag_ids":"",
            "doc_id":"9heQFfeYFUFXb536VTyHLhKL",
            "co_token":"",
            "p":"BeFULN12QL6H9L5HXCAYfH1S",
            "t":"1474932056",
            "c":"2",
            "updated":"1474932056"
         },
         {
            "title":"new doc 8",
            "rotate":0,
            "sort_key":"new doc 8",
            "tag_ids":"",
            "doc_id":"H7eXd1yTfFAY2V8ha3a6FS9K",
            "co_token":"",
            "p":"LJVyNVCPMbXH2abMMbb6BRYN",
            "t":"1474932053",
            "c":"1",
            "updated":"1474932053"
         },
         {
            "title":"new doc 9",
            "rotate":0,
            "sort_key":"new doc 9",
            "tag_ids":"",
            "doc_id":"3VVL56tQDXf73V8UKXrNX0d0",
            "co_token":"",
            "p":"rV2H7WWCRy1Vrb0PaU1TQKTD",
            "t":"1474932047",
            "c":"3",
            "updated":"1474932049"
         },
         {
            "title":"new doc 10",
            "rotate":0,
            "sort_key":"new doc 10",
            "tag_ids":"",
            "doc_id":"4TBabHAKNRXdREJXNdWfQEWF",
            "co_token":"",
            "p":"TR7Dt89gV3hfSJBTDQ1JQP72",
            "t":"1474402937",
            "c":"1",
            "updated":"1474402937"
         },
         {
            "title":"new doc 11",
            "rotate":0,
            "sort_key":"new doc 11",
            "tag_ids":"",
            "doc_id":"TV4fBdehY4fFHN00g082QDKX",
            "co_token":"",
            "p":"SCUPQ9bW6BgTT9JAP4K2WCYU",
            "t":"1474402932",
            "c":"3",
            "updated":"1474402932"
         },
         {
            "title":"new doc 12",
            "rotate":0,
            "sort_key":"new doc 12",
            "tag_ids":"",
            "doc_id":"M8fHK8gQB3FWUEeLKQMdUaFB",
            "co_token":"",
            "p":"BPDTg3aTTDELyFUA1WK0M2rA",
            "t":"1474402911",
            "c":"7",
            "updated":"1474402913"
         },
         {
            "title":"new doc",
            "rotate":0,
            "sort_key":"new doc",
            "tag_ids":"",
            "doc_id":"ayCK8RrHSe796g4PSNRgMD5N",
            "co_token":"",
            "p":"Y46RWJFb0XJRHtKy6B077Me1",
            "t":"1389379718",
            "c":"1",
            "updated":"1389379718"
         }
      ],
   }
}

Body:
I used Newtonsoft.Json package to convert json from file data.json which contains the json data

class Program
{
    static void Main(string[] args)
    {
        LoadJson();
    }

    public static void LoadJson()
    {
        using (StreamReader r = new StreamReader(@"C:\\Users\\user\\source\\repos\\RecursiveParseJSON\\RecursiveParseJSON\\data.json"))
        {
            string json = r.ReadToEnd();
            JsonObject datas = JsonConvert.DeserializeObject<JsonObject>(json);
        }
    }
}

public class JsonObject
{
    public Data data { get; set; }
}
public class Data
{
    public List<string> count { get; set; }
    public List<Doc> list { get; set; }
}

public class Doc
{
    public string title { get; set; }
    public int rotate { get; set; }
    public string sort_key { get; set; }
    public string tag_ids { get; set; }
    public string doc_id { get; set; }
    public string co_token { get; set; }
    public string p { get; set; }
    public string t { get; set; }
    public string c { get; set; }
    public string updated { get; set; }
}


问:
How to draw one line with different colors in chartjs2?
I need to draw a chart that looks like the one on the picture. How do I do that with chartjs2? Unfortunately, I couldn't find any examples that show how to implement it.

答:
First convert your line chart into a scatter chart. Then draw the lines directly on the canvas using the Plugin Core API. The API offers a range of hooks that may be used for performing custom code.

In below code snippet, I use the beforeDraw hook to draw connection lines of different colors between data points.

const values = [11,9,7,8,7,11,13,12,7,12];
const colors = ['red','red','orange','orange','green','green','orange','red','green'];
const data = values.map((value, index) => ( { x: index + 1, y: value, color: index == 0 ? undefined: colors[index - 1]} ));

const colorsPer100 = ['green', 'orange', 'blue', 'red'];

new Chart(document.getElementById("myChart"), {
  type: "scatter",
  plugins: [{
    beforeDraw: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-1'];
      var yAxis = chart.scales['y-axis-1'];
      chart.config.data.datasets[0].data.forEach((value, index) => {
        if (index > 0) {
           var valueFrom = data[index - 1];
           var xFrom = xAxis.getPixelForValue(valueFrom.x);
           var yFrom = yAxis.getPixelForValue(valueFrom.y);
           var xTo = xAxis.getPixelForValue(value.x);
           var yTo = yAxis.getPixelForValue(value.y);
           ctx.save();
           ctx.strokeStyle = value.color;
           ctx.lineWidth = 2;
           ctx.beginPath();
           ctx.moveTo(xFrom, yFrom);
           ctx.lineTo(xTo, yTo);
           ctx.stroke();
           ctx.restore();
        }
      });
    }
  }],
  data: {
    datasets: [{
      label: "My Dataset",
      data: data,
      borderColor: "black"
    }]
  },
  options: {
    animation: {
      duration: 0
    },
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        ticks: {
          min: 0,
          max: 12,
          stepSize: 1
        }
      }],
      yAxes: [{
        ticks: {
          min: 0,
          max: 14,
          stepSize: 2
        }
      }]
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
  max-width: 400px;
}</code>```

<canvas id="myChart" width="10" height="6"></canvas>```

Body:
First convert your line chart into a scatter chart. Then draw the lines directly on the canvas using the Plugin Core API. The API offers a range of hooks that may be used for performing custom code.

In below code snippet, I use the beforeDraw hook to draw connection lines of different colors between data points.

const values = [11,9,7,8,7,11,13,12,7,12];
const colors = ['red','red','orange','orange','green','green','orange','red','green'];
const data = values.map((value, index) => ( { x: index + 1, y: value, color: index == 0 ? undefined: colors[index - 1]} ));

const colorsPer100 = ['green', 'orange', 'blue', 'red'];

new Chart(document.getElementById("myChart"), {
  type: "scatter",
  plugins: [{
    beforeDraw: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-1'];
      var yAxis = chart.scales['y-axis-1'];
      chart.config.data.datasets[0].data.forEach((value, index) => {
        if (index > 0) {
           var valueFrom = data[index - 1];
           var xFrom = xAxis.getPixelForValue(valueFrom.x);
           var yFrom = yAxis.getPixelForValue(valueFrom.y);
           var xTo = xAxis.getPixelForValue(value.x);
           var yTo = yAxis.getPixelForValue(value.y);
           ctx.save();
           ctx.strokeStyle = value.color;
           ctx.lineWidth = 2;
           ctx.beginPath();
           ctx.moveTo(xFrom, yFrom);
           ctx.lineTo(xTo, yTo);
           ctx.stroke();
           ctx.restore();
        }
      });
    }
  }],
  data: {
    datasets: [{
      label: "My Dataset",
      data: data,
      borderColor: "black"
    }]
  },
  options: {
    animation: {
      duration: 0
    },
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        ticks: {
          min: 0,
          max: 12,
          stepSize: 1
        }
      }],
      yAxes: [{
        ticks: {
          min: 0,
          max: 14,
          stepSize: 2
        }
      }]
    }
  }
});

canvas {
  max-width: 400px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" width="10" height="6"></canvas>


问:
Google Sheet notification when a cell in a particular column is edited
I have google sheet where i would like to have an email notification been sent to a specified user whenever a cell in particular column has been edited.

The sheets contains 15 columns and one of the column is for comments and another for email address.

My requirement is whenever any cells in the comment column is edited, I would like to have an email sent to email address mentioned in a different column of the same sheet.

I did went over few of thread and found this thread had similar problem and has been successfully answered with a code. However, when i used this script it gives a  a "Cannot read property 'range' of undefined (line 2, file "Code")" message.

I'm a noob to coding and not sure what does that means.

I also tried Magic Cell Notification addon but to no avail.

Any help will be greatly appreciated.

答:
Send Email

You need to create an installable trigger for onMyEdit.

You need to provide the sheet name, the emailColumn, the commentColumn, the startingRow for data, the and the subject.

And please realize that you can't call this function from the script editor as it requires the event block from the onedit trigger.

`

```<code>function onMyEdit(e) {
  var sh=e.range.getSheet();
  if(sh.getName()!='Your Sheet Name')return;
  var emailColumn=1;//you have to tell me what column the email is on
  var commentColumn=2;//you have to tell me what column the comment is on
  var startingRow=2;//you have to tell me what row the data starts on
  var subject='You tell me what the subject is';
  if(e.range.columnStart==emailColumn && e.range.rowStart>startingRow && e.value) {
    GmailApp.sendEmail(sh.getRange(e.range.rowStart,emailColumn).getValue(), subject, sh.getRange(e.range.rowStart,commentColumn));
  }
}
</code>```

Body:
Send Email

You need to create an installable trigger for onMyEdit.

You need to provide the sheet name, the emailColumn, the commentColumn, the startingRow for data, the and the subject.

And please realize that you can't call this function from the script editor as it requires the event block from the onedit trigger.

`

function onMyEdit(e) {
  var sh=e.range.getSheet();
  if(sh.getName()!='Your Sheet Name')return;
  var emailColumn=1;//you have to tell me what column the email is on
  var commentColumn=2;//you have to tell me what column the comment is on
  var startingRow=2;//you have to tell me what row the data starts on
  var subject='You tell me what the subject is';
  if(e.range.columnStart==emailColumn && e.range.rowStart>startingRow && e.value) {
    GmailApp.sendEmail(sh.getRange(e.range.rowStart,emailColumn).getValue(), subject, sh.getRange(e.range.rowStart,commentColumn));
  }
}


问:
Help Configuring Associations in Castle Active Record in case of association table
I have tables like

Users (UserId,Username,Password,CreatedOn,CreatedBy)

Roles (RoleId,RoleName,Description,CreatedOn,CreatedBy)

UserRoleMap(UserRoleMapId,UserId,RoleId,CreatedOn,CreatedBy)

These are my entities:

```<code>[ActiveRecord(Table="Users")]
public class User:ActiveRecordBase<User>
{
    [PrimaryKey(Generator = PrimaryKeyType.Identity, Column = "RoleId")]
    public virtual int UserId { get; set; }

    [Property(Column="Username")]
    public virtual string Username { get; set; }

    [Property(Column = "Password")]
    public virtual string  Password { get; set; }

    [Property(Column="CreatedBy")]
    public virtual string CreatedBy { get; set; }

    [Property(Column="CreatedOn")]
    public virtual DateTime CreatedOn { get; set; }

    [HasAndBelongsToMany(Table="UserRoleMap",ColumnKey="UserId")]
    public IList<Role> Roles { get; set; }

}
[ActiveRecord(Table = "Roles")]
public class Role : ActiveRecordBase<User>
{
    [PrimaryKey(Generator = PrimaryKeyType.Identity, Column = "RoleId")]
    public virtual int RoleId { get; set; }

    [Property(Column = "RoleName")]
    public virtual string RoleName { get; set; }

    [Property(Column = "Description")]
    public virtual string Description { get; set; }

    [Property(Column = "CreatedBy")]
    public virtual string CreatedBy { get; set; }

    [Property(Column = "CreatedOn")]
    public virtual DateTime CreatedOn { get; set; }

    [HasAndBelongsToMany(Table = "UserRoleMap", ColumnKey = "RoleId")]
    public IList<User> Users { get; set; }
}

[ActiveRecord(Table="UserRoleMap")]
public class UserRoleMap:ActiveRecordBase<UserRoleMap>
{
    [PrimaryKey(Generator = PrimaryKeyType.Identity, Column = "UserRoleMapId")]
    public virtual int UserRoleMapId { get; set; }

    [BelongsTo(Column="UserId",Table="Users")]
    public virtual User UserId { get; set; }

    [BelongsTo(Column = "RoleId", Table = "Roles")]
    public virtual Role RoleId { get; set; }

}
</code>```

I keep getting this error:
ActiveRecordSample.Tests.FrameworkInitializationTest.CanInitializaFramework : Castle.ActiveRecord.Framework.ActiveRecordException : Property UserId references table "Users", which does not have a corresponding [JoinedTable] on the class.

答:
Wherever the column name matches the property name, you don't need to set Column="..."

User.UserId is mapped to column "RoleId", it should be "UserId" (or as I said in the above point, just don't define it)

Make sure to understand the pros and cons of each PK generator.

When using HasAndBelongsToMany you don't want a separate relationship class (in your case UserRoleMap).

IIRC you also need to define the other FK in HasAndBelongsToMany with ColumnRef.

Body:
I have tables like

Users (UserId,Username,Password,CreatedOn,CreatedBy)

Roles (RoleId,RoleName,Description,CreatedOn,CreatedBy)

UserRoleMap(UserRoleMapId,UserId,RoleId,CreatedOn,CreatedBy)

These are my entities:

[ActiveRecord(Table="Users")]
public class User:ActiveRecordBase<User>
{
    [PrimaryKey(Generator = PrimaryKeyType.Identity, Column = "RoleId")]
    public virtual int UserId { get; set; }

    [Property(Column="Username")]
    public virtual string Username { get; set; }

    [Property(Column = "Password")]
    public virtual string  Password { get; set; }

    [Property(Column="CreatedBy")]
    public virtual string CreatedBy { get; set; }

    [Property(Column="CreatedOn")]
    public virtual DateTime CreatedOn { get; set; }

    [HasAndBelongsToMany(Table="UserRoleMap",ColumnKey="UserId")]
    public IList<Role> Roles { get; set; }

}
[ActiveRecord(Table = "Roles")]
public class Role : ActiveRecordBase<User>
{
    [PrimaryKey(Generator = PrimaryKeyType.Identity, Column = "RoleId")]
    public virtual int RoleId { get; set; }

    [Property(Column = "RoleName")]
    public virtual string RoleName { get; set; }

    [Property(Column = "Description")]
    public virtual string Description { get; set; }

    [Property(Column = "CreatedBy")]
    public virtual string CreatedBy { get; set; }

    [Property(Column = "CreatedOn")]
    public virtual DateTime CreatedOn { get; set; }

    [HasAndBelongsToMany(Table = "UserRoleMap", ColumnKey = "RoleId")]
    public IList<User> Users { get; set; }
}

[ActiveRecord(Table="UserRoleMap")]
public class UserRoleMap:ActiveRecordBase<UserRoleMap>
{
    [PrimaryKey(Generator = PrimaryKeyType.Identity, Column = "UserRoleMapId")]
    public virtual int UserRoleMapId { get; set; }

    [BelongsTo(Column="UserId",Table="Users")]
    public virtual User UserId { get; set; }

    [BelongsTo(Column = "RoleId", Table = "Roles")]
    public virtual Role RoleId { get; set; }

}

I keep getting this error:
ActiveRecordSample.Tests.FrameworkInitializationTest.CanInitializaFramework : Castle.ActiveRecord.Framework.ActiveRecordException : Property UserId references table "Users", which does not have a corresponding [JoinedTable] on the class.


问:
call async function from angular controller
I want to call an async function from angular form template controller. But if I do so, execution hangs.

Following the html template:

    <form>

        Identnummer (Adresse) *
        <input type="text" class="form-control" id="address" required placeholder="0x"
                    [(ngModel)]="model.address"
                    #address="ngForm"
                    [ngClass]="setAddressCssValidityClass(address)"
                    ngControl="address">

          <button type="submit" class="btn btn-primary">Submit</button>

        * Required

    </form>

```

<p>Here is a simplified version of my controller:</p>

<pre class="lang-dart prettyprint-override"><code>import 'package:angular/angular.dart';
import 'package:angular_forms/angular_forms.dart';

@Component(
  selector: 'sCert-validate-form',
  templateUrl: 'sCert_validate_form_component.html',
  directives: [coreDirectives, formDirectives],
)
class ScertValidateFormComponent {

  Map<String, bool> setAddressCssValidityClass(NgControl control) {
    var validityClass;
    //callCertificateByAddress(control.value);
    if(control.value == "test"){
      validityClass = 'is-valid';
      callCertificateByAddress(control.value);
    }
    else{
      validityClass = 'is-invalid';
    }
    Map<String, bool> map = {validityClass: true};
    return map;
  }

  Future<bool> callCertificateByAddress(String address) async {
    // some code -> also does not work if removed
    return true;
  }
}
</code>```

Future<bool> callCertificateByAddress(String address) async has to be async, because I do async lib calls in there. But how can I achieve this in combination with the template?

答:
there is a problem: you bind callback to the input here [ngClass]="setAddressCssValidityClass(address)" angular calls your function [which calls network] on each change detection cycle. and the response from http forces a new change detection which recursively calls http again and again. save the result to some variable and bind it to ngClass instead of a method

```<code>ngOnInit() {
  this.classes = this.setAddressCssValidityClass(address);
}
....
[ngClass]="classes"
</code>```

Body:
I want to call an async function from angular form template controller. But if I do so, execution hangs.

Following the html template:

    <form>

        Identnummer (Adresse) *
        <input type="text" class="form-control" id="address" required placeholder="0x"
                    [(ngModel)]="model.address"
                    #address="ngForm"
                    [ngClass]="setAddressCssValidityClass(address)"
                    ngControl="address">

          <button type="submit" class="btn btn-primary">Submit</button>

        * Required

    </form>

Here is a simplified version of my controller:

import 'package:angular/angular.dart';
import 'package:angular_forms/angular_forms.dart';

@Component(
  selector: 'sCert-validate-form',
  templateUrl: 'sCert_validate_form_component.html',
  directives: [coreDirectives, formDirectives],
)
class ScertValidateFormComponent {

  Map<String, bool> setAddressCssValidityClass(NgControl control) {
    var validityClass;
    //callCertificateByAddress(control.value);
    if(control.value == "test"){
      validityClass = 'is-valid';
      callCertificateByAddress(control.value);
    }
    else{
      validityClass = 'is-invalid';
    }
    Map<String, bool> map = {validityClass: true};
    return map;
  }

  Future<bool> callCertificateByAddress(String address) async {
    // some code -> also does not work if removed
    return true;
  }
}

Future<bool> callCertificateByAddress(String address) async has to be async, because I do async lib calls in there. But how can I achieve this in combination with the template?

Body:
there is a problem: you bind callback to the input here [ngClass]="setAddressCssValidityClass(address)" angular calls your function [which calls network] on each change detection cycle. and the response from http forces a new change detection which recursively calls http again and again. save the result to some variable and bind it to ngClass instead of a method

ngOnInit() {
  this.classes = this.setAddressCssValidityClass(address);
}
....
[ngClass]="classes"


问:
How do I plot pie chart graph with pandas data
I currently have plotted out my pie chart successfully and with this relatively small dataframe.

But however, when i try to plot out my pandas pie chart, it looks perfectly fine only until i realise that my index has been included (see the number 0 and 1 at the top right and bottom left corners).

Is there anyway to remove the index? Currently, i'm highly suspicious that the problem comes with the part where i reset and drop my old index.

Here's my code:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# import the csv file
dataname = 'Datasets\\tax-and-penalty-arising-from-audits-by-tax-type.csv'
data = pd.read_csv(dataname)
df = pd.DataFrame(data)

# drop the no_of_cases column since we will not be using it
df2 = df.drop(['tax_and_penalty_arising'],axis=1)

# merge the values: individual income tax and corporate income tax together under tax type together as they can be seen to be seperated in some years eg 2011
dictionary = {'Corporate Income Tax':'Individual and Corporate Income Tax','Individual Income Tax':'Individual and Corporate Income Tax'}
df3 = df2.groupby(['financial_year',df2['tax_type'].replace(dictionary)]).sum().reset_index()

# get only the data from the latest financial_year(2018)
df4 = df3[(df3.financial_year == (2018))]
df4 = df4.reset_index(drop=True)

# # drop the column financial_year as we will not be using it
df4 = df4.drop(['financial_year'],axis=1)

# #  print the dataframe
print(df4)

# plot out the pie chart
# df4 = df4.drop("index",axis=1)
ax = df4.plot.pie(y='no_of_cases',figsize=(10,10))
ax.legend(labels='tax_type')
plt.pie(df4['no_of_cases'],labels=df4['tax_type'],shadow=False,startangle=90, autopct="%1.1f%%")
plt.show()
```

答:
Starting with defining your df4:

```<code>df4 = pd.DataFrame({"tax_type":["GST", "Individual and Corporate Income Tax"],
                    "no_of_cases":[3145,7001]})

_, ax = plt.subplots(figsize = (10,10))
wedges,_,_ = ax.pie(df4['no_of_cases']
                    ,labels=df4["tax_type"]
                    ,shadow=False,startangle=90, autopct="%1.1f%%"
                    ,textprops={'fontsize': 16})
ax.legend(wedges,df4["tax_type"], loc="upper center", prop={'size': 16});
</code>```

Body:
Starting with defining your df4:

df4 = pd.DataFrame({"tax_type":["GST", "Individual and Corporate Income Tax"],
                    "no_of_cases":[3145,7001]})

_, ax = plt.subplots(figsize = (10,10))
wedges,_,_ = ax.pie(df4['no_of_cases']
                    ,labels=df4["tax_type"]
                    ,shadow=False,startangle=90, autopct="%1.1f%%"
                    ,textprops={'fontsize': 16})
ax.legend(wedges,df4["tax_type"], loc="upper center", prop={'size': 16});


问:
Map count really counts or just checks existence
In CPP primer or other websites I have found the language of count (from map STL) definition very vague and misleading:

Searches the container for elements with a key equivalent to k and returns the number of matches

Now what I have studied so far is that key is singular and so is the mapped value - the mapped value can be changed through assignment.

So doesn't it just returns whether the container contains the key or not? Rather than the count? Where am I wrong in understanding the concept?

答:
A std::map's count() will always return either 0 or 1.

But the C++ library has other associative containers that might very well have multiple values for the same key. Like std::multimap and std::multiset. And by a very lucky coincidence they also have a count() method that may actually return values greater than 1.

But what this allows you to do is metaprogramming by developing templates that can use any associative container, one that may or may not be unique. All your template needs to do is use count() to determine how many values exist in the container with the given key, and the end result can be used with either std::map or std::multimap. It won't care in the slightest. In both cases, your template will get the right answer: the number of values in the container with the given key.


问:
How to serve a lot of pages
I want to create a web server with many subpages. For example

www.mainpage.com - main page and I have many subpages

www.mainpage.com/1page; www.mainpage.com/2page; www.mainpage.com/3page; ..... www.mainpage.com/999page

I have no idea how to handle all of this pages. I think that this way isn't correct

```<code>func main() {
    http.HandleFunc("/1page", PageHandler)
    http.HandleFunc("/2page", PageHandler)
    ......
    http.HandleFunc("/999page", PageHandler)

    fmt.Println("Server is listening...")
    http.ListenAndServe(":8181", nil)
}
</code>```

答:
Have you tried serving static files?

Check this answer: How do you serve a static html file using a go web server?

package main

import (
        "net/http"
)

func main() {
        http.Handle("/", http.FileServer(http.Dir("./static")))
        http.ListenAndServe(":3000", nil)
}
```

<p>If you do not want to use static files and only <code>http.Handler</code>, you can use a loop to register your handler function. For example:</p>

<pre class="lang-golang prettyprint-override"><code>package main

import (
    "fmt"
    "net/http"
    "strconv"
)

func main() {
    for i := 1; i < 1000; i++ {
        http.HandleFunc(fmt.Sprintf("/%dpage", i), PageHandler(i))
    }
    fmt.Println("Server is listening...")
    http.ListenAndServe(":8181", nil)
}

func PageHandler(i int) func(http.ResponseWriter, *http.Request) {
    return func(resp http.ResponseWriter, req *http.Request) {
        resp.WriteHeader(200)
        resp.Write([]byte(strconv.Itoa(i)))
    }
}
</code>```

Title: How to serve a lot of pages

Body:
I want to create a web server with many subpages. For example

www.mainpage.com - main page and I have many subpages

www.mainpage.com/1page; www.mainpage.com/2page; www.mainpage.com/3page; ..... www.mainpage.com/999page

I have no idea how to handle all of this pages. I think that this way isn't correct

func main() {
    http.HandleFunc("/1page", PageHandler)
    http.HandleFunc("/2page", PageHandler)
    ......
    http.HandleFunc("/999page", PageHandler)

    fmt.Println("Server is listening...")
    http.ListenAndServe(":8181", nil)
}

Body:
Have you tried serving static files?

Check this answer: How do you serve a static html file using a go web server?

package main

import (
        "net/http"
)

func main() {
        http.Handle("/", http.FileServer(http.Dir("./static")))
        http.ListenAndServe(":3000", nil)
}

If you do not want to use static files and only http.Handler, you can use a loop to register your handler function. For example:

package main

import (
    "fmt"
    "net/http"
    "strconv"
)

func main() {
    for i := 1; i < 1000; i++ {
        http.HandleFunc(fmt.Sprintf("/%dpage", i), PageHandler(i))
    }
    fmt.Println("Server is listening...")
    http.ListenAndServe(":8181", nil)
}

func PageHandler(i int) func(http.ResponseWriter, *http.Request) {
    return func(resp http.ResponseWriter, req *http.Request) {
        resp.WriteHeader(200)
        resp.Write([]byte(strconv.Itoa(i)))
    }
}


问:
Valgrind + C: Handling uninitialized pointers without error
Maybe I got too involved with testing my assignment, but here's my dilemma:

This is my offending function (more or less):

```<code>struct thing{
    char* data;
}

int function(struct thing* arg){
    if(arg->data == NULL)
        return -1;
}
</code>```

This is my offending input:

```<code>struct thing *x = malloc(sizeof(struct thing));
function(x);
</code>```

And valgrind outputs this when I test it:

Conditional jump or move depends on uninitialised value(s)
```

I'm about 99% sure that this is because valgrind has an issue with evaluating x->data when it hasn't been initialized to NULL or malloced. Is there a workaround for this?

答:
The memory allocated by malloc is not initialized.

You need to set it to the know state:

```<code>struct thing *x = calloc(1,sizeof(*x));
</code>```

or

```<code>struct thing *x = malloc(sizeof(*x));
memset(x, 0, sizeof(*x);
</code>```

you can also of course just assign some values to the struct members,

```<code>struct thing *x = malloc(sizeof(*x));
x -> data = NULL;
</code>```

Body:
Maybe I got too involved with testing my assignment, but here's my dilemma:

This is my offending function (more or less):

struct thing{
    char* data;
}

int function(struct thing* arg){
    if(arg->data == NULL)
        return -1;
}

This is my offending input:

struct thing *x = malloc(sizeof(struct thing));
function(x);

And valgrind outputs this when I test it:

Conditional jump or move depends on uninitialised value(s)

I'm about 99% sure that this is because valgrind has an issue with evaluating x->data when it hasn't been initialized to NULL or malloced. Is there a workaround for this?

Body:
The memory allocated by malloc is not initialized.

You need to set it to the know state:

struct thing *x = calloc(1,sizeof(*x));

or

struct thing *x = malloc(sizeof(*x));
memset(x, 0, sizeof(*x);

you can also of course just assign some values to the struct members,

struct thing *x = malloc(sizeof(*x));
x -> data = NULL;


问:
Android Integration test: Mocking the logic/ method in within an activity using Dagger and Mockito and get the returned value back within the test
I am developing an Android application using Kotlin. I am also writing integrated tests for my application using Dagger and Expresso. I am now having a problem with mocking a logic. First, let me show you how I mock logic in the code using Dagger for the integrated tests.

I have the Dagger app component class for the test with the following definition

```<code>@Singleton
@Component(modules = [ TestAppModule::class ])
interface TestAppComponent : AppComponent //App component is the actual class used for the application
{
    fun inject(app: MainActivity)
}
</code>```

This is the definition of the TestAppModule class

```<code>@Module
open class TestAppModule (private val app: Application) {
    @Singleton
    @Provides
    open fun fileIOService(): IFileIOService {
        return FakeFileIOService()
    }
}
</code>```

I also have a class called AppModule for the actual Application code with the following definition.

```<code>@Module
open class TestAppModule (private val app: Application) {
    @Singleton
    @Provides
    open fun fileIOService(): IFileIOService {
        return FakeFileIOService()
    }
}
</code>```

The idea is that the integration tests will use the TestAppModule and so the FakeFileIOService class will be injected. For the actual application, it will use the AppModule and so the FileIOService class will be injected instead. Both the FakeFileIOService class and the FileIOService class will inherit from the IFileIOService interface. The IFileIOService interface will have the following definition.

```<code>interface IFileIOService
{
    fun saveFile(data: String)
}
</code>```

The FileIOService class and the FakeIOService class will have their own version of the implementation for the saveFile method. The FakeIOService will have the mock version.

I will have a property for IFileIOService in the MainActivity class for dependency injection.

```<code>class MainActivity: AppCompatActivity()
{
    @Inject
    lateinit var fileIOService: IFileIOService
}
</code>```

As I mentioned, the FakeFileIOService class will be injected for the integration tests. The code works fine. It uses the fake version for the integration tests and the concrete for the actual application.

But now, I am having a problem where I need to mock the logic of the method using Mockito and get the returned value within the tests.

But, now I am having an issue with mocking the logic using Mokito to test File and getting the mocked value back within the tests.

Following is the implementation of my

```<code>fun saveFile(data: String) {
    FileOutputStream mockFos = Mockito.mock(FileOutputStream.class);
    mockFos.write(data.getBytes());
    mockFos.close();
}
</code>```

Literally, I am trying to mock the file logic using Mockito. Then I am trying to write an integration test something like this.

```<code>@get:Rule
var mainActivityRule: ActivityTestRule<MainActivity> = ActivityTestRule<MainActivity>(CameraActivity::class.java, true, false)

@Test
fun fileIsSaveInWhenButtonIsClicked() {
    Intents.init()
    var targetContext: Context = InstrumentationRegistry.getInstrumentation().targetContext
    var intent: Intent = Intent(targetContext, MainActivity::class.java)
    this.mainActivityRule.launchActivity(null)
    onView(withId(R.id.button_save_file)).perform(click())

    //here I want to assert if the file is saved using Mockito something like this
    //verify(mockFos).write(data.getBytes()); the issue is that I cannot get the mockFos instance creatd in the saveFile method of the FakeFileIOService class
    Intents.release()
}
</code>```

See the comment in the test. The issue is that I want to verify if the file is saved using Mockito. But the issue is that I cannot get the mockFos instance created in the saveFile of the FakeIOService class. How can I test it? What would be the best way to test this scenario?

答:
You are not supposed to mock system logic. Writing to a file and closing the file is system logic. You are only supposed to mock your own logic.

And what you should be verifying is that the saveFile method was called. Not that the content of saveMyFile was invoked.

```<code>val mock = mock(IFileIOService::class.java)
mainActivity.fileIOService = mock

//do something that in return does fileIOService.saveFile

verify(mock).saveFile(any())
</code>```

Another option is to spy:

```<code> val spy = spy(mainActivity.fileIOService)
 //do something that in return does fileIOService.saveFile

 verify(spy).saveFile(any())
</code>```

Body:
I am developing an Android application using Kotlin. I am also writing integrated tests for my application using Dagger and Expresso. I am now having a problem with mocking a logic. First, let me show you how I mock logic in the code using Dagger for the integrated tests.

I have the Dagger app component class for the test with the following definition

@Singleton
@Component(modules = [ TestAppModule::class ])
interface TestAppComponent : AppComponent //App component is the actual class used for the application
{
    fun inject(app: MainActivity)
}

This is the definition of the TestAppModule class

@Module
open class TestAppModule (private val app: Application) {
    @Singleton
    @Provides
    open fun fileIOService(): IFileIOService {
        return FakeFileIOService()
    }
}

I also have a class called AppModule for the actual Application code with the following definition.

@Module
open class TestAppModule (private val app: Application) {
    @Singleton
    @Provides
    open fun fileIOService(): IFileIOService {
        return FakeFileIOService()
    }
}

The idea is that the integration tests will use the TestAppModule and so the FakeFileIOService class will be injected. For the actual application, it will use the AppModule and so the FileIOService class will be injected instead. Both the FakeFileIOService class and the FileIOService class will inherit from the IFileIOService interface. The IFileIOService interface will have the following definition.

interface IFileIOService
{
    fun saveFile(data: String)
}

The FileIOService class and the FakeIOService class will have their own version of the implementation for the saveFile method. The FakeIOService will have the mock version.

I will have a property for IFileIOService in the MainActivity class for dependency injection.

class MainActivity: AppCompatActivity()
{
    @Inject
    lateinit var fileIOService: IFileIOService
}

As I mentioned, the FakeFileIOService class will be injected for the integration tests. The code works fine. It uses the fake version for the integration tests and the concrete for the actual application.

But now, I am having a problem where I need to mock the logic of the method using Mockito and get the returned value within the tests.

But, now I am having an issue with mocking the logic using Mokito to test File and getting the mocked value back within the tests.

Following is the implementation of my

fun saveFile(data: String) {
    FileOutputStream mockFos = Mockito.mock(FileOutputStream.class);
    mockFos.write(data.getBytes());
    mockFos.close();
}

Literally, I am trying to mock the file logic using Mockito. Then I am trying to write an integration test something like this.

@get:Rule
var mainActivityRule: ActivityTestRule<MainActivity> = ActivityTestRule<MainActivity>(CameraActivity::class.java, true, false)

@Test
fun fileIsSaveInWhenButtonIsClicked() {
    Intents.init()
    var targetContext: Context = InstrumentationRegistry.getInstrumentation().targetContext
    var intent: Intent = Intent(targetContext, MainActivity::class.java)
    this.mainActivityRule.launchActivity(null)
    onView(withId(R.id.button_save_file)).perform(click())

    //here I want to assert if the file is saved using Mockito something like this
    //verify(mockFos).write(data.getBytes()); the issue is that I cannot get the mockFos instance creatd in the saveFile method of the FakeFileIOService class
    Intents.release()
}

See the comment in the test. The issue is that I want to verify if the file is saved using Mockito. But the issue is that I cannot get the mockFos instance created in the saveFile of the FakeIOService class. How can I test it? What would be the best way to test this scenario?

Body:
You are not supposed to mock system logic. Writing to a file and closing the file is system logic. You are only supposed to mock your own logic.

And what you should be verifying is that the saveFile method was called. Not that the content of saveMyFile was invoked.

val mock = mock(IFileIOService::class.java)
mainActivity.fileIOService = mock

//do something that in return does fileIOService.saveFile

verify(mock).saveFile(any())

Another option is to spy:

 val spy = spy(mainActivity.fileIOService)
 //do something that in return does fileIOService.saveFile

 verify(spy).saveFile(any())