问:
Using maven release plugin on multi-module project
I have a multi-module project with two modules: war and ear module. I'm trying to use Maven release plugin to manage releases.

My config so far...

parent pom:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>Test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>

    <modules>
        <module>Test-WAR</module>
        <module>Test-EAR</module>
    </modules>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <!-- some other properties -->
    </properties>

    <dependencyManagement>
        <dependencies>
            <!-- some dependencies -->
        </dependencies>
    </dependencyManagement>

    <repositories>
        <repository>
            <id>nexus-snapshots</id>
            <name>nexus</name>
            <url>http://nexus.example.com:8081/repository/maven-snapshots</url>
        </repository>
        <repository>
            <id>nexus-releases</id>
            <name>nexus</name>
            <url>http://nexus.example.com:8081/repository/maven-releases</url>
        </repository>
    </repositories>

    <distributionManagement>
        <snapshotRepository>
            <id>nexus-snapshots</id>
            <name>nexus</name>
            <url>http://nexus.example.com:8081/repository/maven-snapshots</url>
        </snapshotRepository>
        <repository>
            <id>nexus-releases</id>
            <name>nexus</name>
            <url>http://nexus.example.com:8081/repository/maven-releases</url>
        </repository>
    </distributionManagement>

    <scm>
        <connection>scm:git:http://gitlab.example.com/test/Test.git</connection>
        <developerConnection>scm:git:http://gitlab.example.com/test/Test.git</developerConnection>
        <url>http://gitlab.example.com/test/Test</url>
    </scm>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-release-plugin</artifactId>
                <version>2.5.3</version>
                <configuration>
                    <tagNameFormat>v@{project.version}</tagNameFormat>
                    <autoVersionSubmodules>true</autoVersionSubmodules>
                    <releaseProfiles>release</releaseProfiles>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.zeroturnaround</groupId>
                <artifactId>jrebel-maven-plugin</artifactId>
                <version>1.1.8</version>
                <executions>
                    <execution>
                        <id>generate-rebel-xml</id>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.8.2</version>
                <executions>
                    <execution>
                        <id>deploy-parent</id>
                        <phase>deploy</phase>
                        <goals>
                            <goal>deploy</goal>
                        </goals>
                        <configuration>
                            <skip>true</skip>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

war module pom:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.example</groupId>
        <artifactId>Test</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>Test-WAR</artifactId>
    <packaging>war</packaging>

    <properties>
        <maven.compiler.source>1.6</maven.compiler.source>
        <maven.compiler.target>1.6</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- some dependencies -->
    </dependencies>

    <profiles>
        <!-- dev -->
        <profile>
            <id>dev</id>
            <properties>
                <CREATE_EJB_STUBS_SCRIPT_FILE>createEJBStubs.bat</CREATE_EJB_STUBS_SCRIPT_FILE>
                <APP_CLASSES_DIR>${basedir}/target/classes</APP_CLASSES_DIR>
                <EJB_LOCATION>src/test/resources/build/${project.parent.artifactId}.jar</EJB_LOCATION>
                <EJB_CLIENT_LOCATION>src/test/resources/build/${project.parent.artifactId}-${project.parent.version}.jar</EJB_CLIENT_LOCATION>
            </properties>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-deploy-plugin</artifactId>
                        <version>2.8.2</version>
                        <executions>
                            <execution>
                                <id>deploy-ejb-client</id>
                                <phase>deploy</phase>
                                <goals>
                                    <goal>deploy-file</goal>
                                </goals>
                                <configuration>
                                    <repositoryId>nexus-snapshots</repositoryId>
                                    <file>${EJB_CLIENT_LOCATION}</file>
                                    <url>http://nexus.example.com:8081/repository/maven-snapshots</url>
                                    <groupId>${project.parent.groupId}</groupId>
                                    <artifactId>${project.parent.artifactId}-EJB-CLIENT</artifactId>
                                    <version>${project.parent.version}</version>
                                    <packaging>jar</packaging>
                                    <generatePom>true</generatePom>
                                </configuration>
                            </execution>
                            <execution>
                                <id>deploy-ejb</id>
                                <phase>deploy</phase>
                                <goals>
                                    <goal>deploy-file</goal>
                                </goals>
                                <configuration>
                                    <repositoryId>nexus-snapshots</repositoryId>
                                    <file>${EJB_LOCATION}</file>
                                    <url>http://nexus.example.com:8081/repository/maven-snapshots</url>
                                    <groupId>${project.parent.groupId}</groupId>
                                    <artifactId>${project.parent.artifactId}-EJB</artifactId>
                                    <version>${project.parent.version}</version>
                                    <packaging>jar</packaging>
                                    <generatePom>true</generatePom>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>

        <!-- release -->
        <profile>
            <id>release</id>
            <properties>
                <CREATE_EJB_STUBS_SCRIPT_FILE>createEJBStubs.bat</CREATE_EJB_STUBS_SCRIPT_FILE>
                <APP_CLASSES_DIR>../../../Test-WAR/target/classes</APP_CLASSES_DIR>
                <EJB_LOCATION>../../../Test-WAR/src/test/resources/build/${project.parent.artifactId}.jar</EJB_LOCATION>
                <EJB_CLIENT_LOCATION>../../../Test-WAR/src/test/resources/build/${project.parent.artifactId}-${project.parent.version}.jar</EJB_CLIENT_LOCATION>
            </properties>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-antrun-plugin</artifactId>
                        <version>1.8</version>
                        <executions>
                            <execution>
                                <id>ant-build</id>
                                <phase>prepare-package</phase>
                                <goals>
                                    <goal>run</goal>
                                </goals>
                                <configuration>
                                    <target>
                                        <property name="server.dir" value="${SERVER_DIR}" />
                                        <property name="createEjbStubsScriptFile" value="${CREATE_EJB_STUBS_SCRIPT_FILE}" />
                                        <property name="appClassesDir" value="${APP_CLASSES_DIR}" />
                                        <property name="author" value="${project.organization.name}" />
                                        <property name="maven.root" value="${project.parent.artifactId}" />
                                        <property name="maven.war.artifactId" value="${project.artifactId}" />
                                        <property name="maven.war.version" value="${project.parent.version}" />
                                        <ant antfile="${basedir}/src/test/resources/ant/build.xml">
                                            <target name="run" />
                                        </ant>
                                    </target>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <artifactId>maven-deploy-plugin</artifactId>
                        <version>2.8.2</version>
                        <executions>
                            <execution>
                                <id>deploy-ejb-client</id>
                                <phase>deploy</phase>
                                <goals>
                                    <goal>deploy-file</goal>
                                </goals>
                                <configuration>
                                    <repositoryId>nexus-releases</repositoryId>
                                    <file>${EJB_CLIENT_LOCATION}</file>
                                    <url>http://nexus.example.com:8081/repository/maven-releases</url>
                                    <groupId>${project.parent.groupId}</groupId>
                                    <artifactId>${project.parent.artifactId}-EJB-CLIENT</artifactId>
                                    <version>${project.parent.version}</version>
                                    <packaging>jar</packaging>
                                    <generatePom>true</generatePom>
                                </configuration>
                            </execution>
                            <execution>
                                <id>deploy-ejb</id>
                                <phase>deploy</phase>
                                <goals>
                                    <goal>deploy-file</goal>
                                </goals>
                                <configuration>
                                    <repositoryId>nexus-releases</repositoryId>
                                    <file>${EJB_LOCATION}</file>
                                    <url>http://nexus.example.com:8081/repository/maven-releases</url>
                                    <groupId>${project.parent.groupId}</groupId>
                                    <artifactId>${project.parent.artifactId}-EJB</artifactId>
                                    <version>${project.parent.version}</version>
                                    <packaging>jar</packaging>
                                    <generatePom>true</generatePom>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.2</version>
                <configuration>
                    <packagingExcludes>WEB-INF/classes/rebel.xml</packagingExcludes>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.1.0</version>
                <executions>
                    <execution>
                        <id>copy-resources</id>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <phase>package</phase>
                        <configuration>
                            <overwrite>true</overwrite>
                            <outputDirectory>${basedir}/target/classes</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>${basedir}/src/test/resources</directory>
                                    <includes>
                                        <include>log4j2.xml</include>
                                    </includes>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <version>1.8</version>
                <executions>
                    <execution>
                        <id>ant-build</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <target>
                                <property name="server.dir" value="${SERVER_DIR}" />
                                <property name="createEjbStubsScriptFile" value="${CREATE_EJB_STUBS_SCRIPT_FILE}" />
                                <property name="appClassesDir" value="${APP_CLASSES_DIR}" />
                                <property name="author" value="${project.organization.name}" />
                                <property name="maven.root" value="${project.parent.artifactId}" />
                                <property name="maven.war.artifactId" value="${project.artifactId}" />
                                <property name="maven.war.version" value="${project.parent.version}" />
                                <ant antfile="${basedir}/src/test/resources/ant/build.xml">
                                    <target name="run" />
                                </ant>
                            </target>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                    <verbose>true</verbose>
                    <fork>true</fork>
                    <executable>${IBM_JDK_1_8}/bin/javac</executable>
                    <compilerVersion>1.6</compilerVersion>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>3.0.1</version>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <phase>install</phase>
                        <goals>
                            <goal>javadoc</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                   <!-- some config -->
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

ear module pom:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.example</groupId>
        <artifactId>Test</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>Test-EAR</artifactId>
    <packaging>ear</packaging>

    <dependencies>
        <!-- WAR -->
        <dependency>
            <groupId>com.example</groupId>
            <artifactId>Test-WAR</artifactId>
            <version>${project.parent.version}</version>
            <type>war</type>
        </dependency>
        <!-- some other dependencies -->
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-ear-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <modules>
                        <!-- some jar modules -->
                        <webModule>
                            <groupId>com.example</groupId>
                            <artifactId>Test-WAR</artifactId>
                            <contextRoot>/Test</contextRoot>
                        </webModule>
                    </modules>
                    <version>6</version>
                    <finalName>${project.parent.artifactId}-${project.parent.version}</finalName>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.8.2</version>
                <executions>
                    <execution>
                        <id>deploy-ear</id>
                        <phase>deploy</phase>
                        <goals>
                            <goal>deploy-file</goal>
                        </goals>
                        <configuration>
                            <repositoryId>nexus-snapshots</repositoryId>
                            <file>target/${project.parent.artifactId}-${project.parent.version}.ear</file>
                            <url>http://nexus.example.com:8081/repository/maven-snapshots</url>
                            <groupId>${project.groupId}</groupId>
                            <artifactId>${project.artifactId}</artifactId>
                            <version>${project.version}</version>
                            <packaging>ear</packaging>
                            <generatePom>true</generatePom>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

I have two profiles - dev (which is active by default) and release (which is activated by release plugin). First, I had some problems with ant run (file paths) when releasing version, so I've used two profiles with some properties defined, that are used in ant run. Ant script is now executed properly, but I have another problem: plugin attempts to upload some release files twice which causes error:

executing mvn release:prepare "-Darguments=-Dmaven.test.skip=true": log

executing mvn release:perform "-Darguments=-Dmaven.test.skip=true": log

As you can see form logs, Test-WAR-0.0.1-sources.jar is uploading twice. Why is that? How can I edit my configuration to upload it only once?

答:
It is quite possible that you suffer from the same bug as I did some years ago:

Maven deploy-file goal: Why does the first execution interfere with the second one?

Try to update the Maven deploy plugin to version 3.0.0-M1.

Body:
I have a multi-module project with two modules: war and ear module. I'm trying to use Maven release plugin to manage releases.

My config so far...

parent pom:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>Test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>

    <modules>
        <module>Test-WAR</module>
        <module>Test-EAR</module>
    </modules>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

    </properties>

    <dependencyManagement>
        <dependencies>

        </dependencies>
    </dependencyManagement>

    <repositories>
        <repository>
            <id>nexus-snapshots</id>
            <name>nexus</name>
            <url>http://nexus.example.com:8081/repository/maven-snapshots</url>
        </repository>
        <repository>
            <id>nexus-releases</id>
            <name>nexus</name>
            <url>http://nexus.example.com:8081/repository/maven-releases</url>
        </repository>
    </repositories>

    <distributionManagement>
        <snapshotRepository>
            <id>nexus-snapshots</id>
            <name>nexus</name>
            <url>http://nexus.example.com:8081/repository/maven-snapshots</url>
        </snapshotRepository>
        <repository>
            <id>nexus-releases</id>
            <name>nexus</name>
            <url>http://nexus.example.com:8081/repository/maven-releases</url>
        </repository>
    </distributionManagement>

    <scm>
        <connection>scm:git:http://gitlab.example.com/test/Test.git</connection>
        <developerConnection>scm:git:http://gitlab.example.com/test/Test.git</developerConnection>
        <url>http://gitlab.example.com/test/Test</url>
    </scm>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-release-plugin</artifactId>
                <version>2.5.3</version>
                <configuration>
                    <tagNameFormat>v@{project.version}</tagNameFormat>
                    <autoVersionSubmodules>true</autoVersionSubmodules>
                    <releaseProfiles>release</releaseProfiles>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.zeroturnaround</groupId>
                <artifactId>jrebel-maven-plugin</artifactId>
                <version>1.1.8</version>
                <executions>
                    <execution>
                        <id>generate-rebel-xml</id>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.8.2</version>
                <executions>
                    <execution>
                        <id>deploy-parent</id>
                        <phase>deploy</phase>
                        <goals>
                            <goal>deploy</goal>
                        </goals>
                        <configuration>
                            <skip>true</skip>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

war module pom:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.example</groupId>
        <artifactId>Test</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>Test-WAR</artifactId>
    <packaging>war</packaging>

    <properties>
        <maven.compiler.source>1.6</maven.compiler.source>
        <maven.compiler.target>1.6</maven.compiler.target>
    </properties>

    <dependencies>

    </dependencies>

    <profiles>

        <profile>
            <id>dev</id>
            <properties>
                <CREATE_EJB_STUBS_SCRIPT_FILE>createEJBStubs.bat</CREATE_EJB_STUBS_SCRIPT_FILE>
                <APP_CLASSES_DIR>${basedir}/target/classes</APP_CLASSES_DIR>
                <EJB_LOCATION>src/test/resources/build/${project.parent.artifactId}.jar</EJB_LOCATION>
                <EJB_CLIENT_LOCATION>src/test/resources/build/${project.parent.artifactId}-${project.parent.version}.jar</EJB_CLIENT_LOCATION>
            </properties>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-deploy-plugin</artifactId>
                        <version>2.8.2</version>
                        <executions>
                            <execution>
                                <id>deploy-ejb-client</id>
                                <phase>deploy</phase>
                                <goals>
                                    <goal>deploy-file</goal>
                                </goals>
                                <configuration>
                                    <repositoryId>nexus-snapshots</repositoryId>
                                    <file>${EJB_CLIENT_LOCATION}</file>
                                    <url>http://nexus.example.com:8081/repository/maven-snapshots</url>
                                    <groupId>${project.parent.groupId}</groupId>
                                    <artifactId>${project.parent.artifactId}-EJB-CLIENT</artifactId>
                                    <version>${project.parent.version}</version>
                                    <packaging>jar</packaging>
                                    <generatePom>true</generatePom>
                                </configuration>
                            </execution>
                            <execution>
                                <id>deploy-ejb</id>
                                <phase>deploy</phase>
                                <goals>
                                    <goal>deploy-file</goal>
                                </goals>
                                <configuration>
                                    <repositoryId>nexus-snapshots</repositoryId>
                                    <file>${EJB_LOCATION}</file>
                                    <url>http://nexus.example.com:8081/repository/maven-snapshots</url>
                                    <groupId>${project.parent.groupId}</groupId>
                                    <artifactId>${project.parent.artifactId}-EJB</artifactId>
                                    <version>${project.parent.version}</version>
                                    <packaging>jar</packaging>
                                    <generatePom>true</generatePom>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>

        <profile>
            <id>release</id>
            <properties>
                <CREATE_EJB_STUBS_SCRIPT_FILE>createEJBStubs.bat</CREATE_EJB_STUBS_SCRIPT_FILE>
                <APP_CLASSES_DIR>../../../Test-WAR/target/classes</APP_CLASSES_DIR>
                <EJB_LOCATION>../../../Test-WAR/src/test/resources/build/${project.parent.artifactId}.jar</EJB_LOCATION>
                <EJB_CLIENT_LOCATION>../../../Test-WAR/src/test/resources/build/${project.parent.artifactId}-${project.parent.version}.jar</EJB_CLIENT_LOCATION>
            </properties>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-antrun-plugin</artifactId>
                        <version>1.8</version>
                        <executions>
                            <execution>
                                <id>ant-build</id>
                                <phase>prepare-package</phase>
                                <goals>
                                    <goal>run</goal>
                                </goals>
                                <configuration>
                                    <target>
                                        <property name="server.dir" value="${SERVER_DIR}" />
                                        <property name="createEjbStubsScriptFile" value="${CREATE_EJB_STUBS_SCRIPT_FILE}" />
                                        <property name="appClassesDir" value="${APP_CLASSES_DIR}" />
                                        <property name="author" value="${project.organization.name}" />
                                        <property name="maven.root" value="${project.parent.artifactId}" />
                                        <property name="maven.war.artifactId" value="${project.artifactId}" />
                                        <property name="maven.war.version" value="${project.parent.version}" />
                                        <ant antfile="${basedir}/src/test/resources/ant/build.xml">
                                            <target name="run" />
                                        </ant>
                                    </target>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <artifactId>maven-deploy-plugin</artifactId>
                        <version>2.8.2</version>
                        <executions>
                            <execution>
                                <id>deploy-ejb-client</id>
                                <phase>deploy</phase>
                                <goals>
                                    <goal>deploy-file</goal>
                                </goals>
                                <configuration>
                                    <repositoryId>nexus-releases</repositoryId>
                                    <file>${EJB_CLIENT_LOCATION}</file>
                                    <url>http://nexus.example.com:8081/repository/maven-releases</url>
                                    <groupId>${project.parent.groupId}</groupId>
                                    <artifactId>${project.parent.artifactId}-EJB-CLIENT</artifactId>
                                    <version>${project.parent.version}</version>
                                    <packaging>jar</packaging>
                                    <generatePom>true</generatePom>
                                </configuration>
                            </execution>
                            <execution>
                                <id>deploy-ejb</id>
                                <phase>deploy</phase>
                                <goals>
                                    <goal>deploy-file</goal>
                                </goals>
                                <configuration>
                                    <repositoryId>nexus-releases</repositoryId>
                                    <file>${EJB_LOCATION}</file>
                                    <url>http://nexus.example.com:8081/repository/maven-releases</url>
                                    <groupId>${project.parent.groupId}</groupId>
                                    <artifactId>${project.parent.artifactId}-EJB</artifactId>
                                    <version>${project.parent.version}</version>
                                    <packaging>jar</packaging>
                                    <generatePom>true</generatePom>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.2</version>
                <configuration>
                    <packagingExcludes>WEB-INF/classes/rebel.xml</packagingExcludes>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.1.0</version>
                <executions>
                    <execution>
                        <id>copy-resources</id>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <phase>package</phase>
                        <configuration>
                            <overwrite>true</overwrite>
                            <outputDirectory>${basedir}/target/classes</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>${basedir}/src/test/resources</directory>
                                    <includes>
                                        <include>log4j2.xml</include>
                                    </includes>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <version>1.8</version>
                <executions>
                    <execution>
                        <id>ant-build</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <target>
                                <property name="server.dir" value="${SERVER_DIR}" />
                                <property name="createEjbStubsScriptFile" value="${CREATE_EJB_STUBS_SCRIPT_FILE}" />
                                <property name="appClassesDir" value="${APP_CLASSES_DIR}" />
                                <property name="author" value="${project.organization.name}" />
                                <property name="maven.root" value="${project.parent.artifactId}" />
                                <property name="maven.war.artifactId" value="${project.artifactId}" />
                                <property name="maven.war.version" value="${project.parent.version}" />
                                <ant antfile="${basedir}/src/test/resources/ant/build.xml">
                                    <target name="run" />
                                </ant>
                            </target>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                    <verbose>true</verbose>
                    <fork>true</fork>
                    <executable>${IBM_JDK_1_8}/bin/javac</executable>
                    <compilerVersion>1.6</compilerVersion>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>3.0.1</version>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <phase>install</phase>
                        <goals>
                            <goal>javadoc</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>

                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

ear module pom:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.example</groupId>
        <artifactId>Test</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>Test-EAR</artifactId>
    <packaging>ear</packaging>

    <dependencies>

        <dependency>
            <groupId>com.example</groupId>
            <artifactId>Test-WAR</artifactId>
            <version>${project.parent.version}</version>
            <type>war</type>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-ear-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <modules>

                        <webModule>
                            <groupId>com.example</groupId>
                            <artifactId>Test-WAR</artifactId>
                            <contextRoot>/Test</contextRoot>
                        </webModule>
                    </modules>
                    <version>6</version>
                    <finalName>${project.parent.artifactId}-${project.parent.version}</finalName>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.8.2</version>
                <executions>
                    <execution>
                        <id>deploy-ear</id>
                        <phase>deploy</phase>
                        <goals>
                            <goal>deploy-file</goal>
                        </goals>
                        <configuration>
                            <repositoryId>nexus-snapshots</repositoryId>
                            <file>target/${project.parent.artifactId}-${project.parent.version}.ear</file>
                            <url>http://nexus.example.com:8081/repository/maven-snapshots</url>
                            <groupId>${project.groupId}</groupId>
                            <artifactId>${project.artifactId}</artifactId>
                            <version>${project.version}</version>
                            <packaging>ear</packaging>
                            <generatePom>true</generatePom>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

I have two profiles - dev (which is active by default) and release (which is activated by release plugin). First, I had some problems with ant run (file paths) when releasing version, so I've used two profiles with some properties defined, that are used in ant run. Ant script is now executed properly, but I have another problem: plugin attempts to upload some release files twice which causes error:

executing mvn release:prepare "-Darguments=-Dmaven.test.skip=true": log

executing mvn release:perform "-Darguments=-Dmaven.test.skip=true": log

As you can see form logs, Test-WAR-0.0.1-sources.jar is uploading twice. Why is that? How can I edit my configuration to upload it only once?


来源: stackexchange

问:
Windows service access folder under project
I am trying to work on a service where I need to export a report into a folder under the service project and email it to the user.  The delete the report when complete.  The issue I am having is I need to know how to access a folder under the project.   I know you can use System.AppDomain.CurrentDomain.BaseDirectory to get into the bin where the excuting file is but I want to get to a folder is this possible? If not is there a way of creating the folder under the bin directory and accessing it. I can manually create a folder under the bin but didnt really want to do that. Any help is greatly appreciated.</p>

答: Instead of using Application path, better option for temp files is Temp directory or AppData directory. You may not get write access to the installed directory.</p>

ContentLicense: CC BY-SA 3.0


问:
Get last N entries and order by ascending
I'm building a simple message box. Each message belongs to a conversation. What I'm trying to do is get the last 5 messages in the conversation and order them by ascending.

InboxController.php

```<code>public function messages($hashedId)
{
    $conversation = Conversation::where('hashed_id', $hashedId)->first();

    $messages = Message::where('conversation_id', $conversation->id)
        ->latest()
        ->take(5)
        ->get();

    $messages->orderBy('created_at','asc');

    return MessageResource::collection($messages);
}
</code>```

Error

BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::orderBy does not exist.

答:
try this</p>

```<code>public function messages($hashedId)
{
    $conversation = Conversation::where('hashed_id', $hashedId)->first();

    $messages = Message::where('conversation_id', $conversation->id)
        ->take(5)
        ->orderBy('created_at','desc')
        ->get();

    return MessageResource::collection($messages);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm building a simple message box. Each message belongs to a conversation. What I'm trying to do is get the last 5 messages in the conversation and order them by ascending.

InboxController.php

public function messages($hashedId)
{
    $conversation = Conversation::where('hashed_id', $hashedId)->first();

    $messages = Message::where('conversation_id', $conversation->id)
        ->latest()
        ->take(5)
        ->get();

    $messages->orderBy('created_at','asc');

    return MessageResource::collection($messages);
}

Error

BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::orderBy does not exist.

Body:
try this

public function messages($hashedId)
{
    $conversation = Conversation::where('hashed_id', $hashedId)->first();

    $messages = Message::where('conversation_id', $conversation->id)
        ->take(5)
        ->orderBy('created_at','desc')
        ->get();

    return MessageResource::collection($messages);
}


问:
Make child element wider than parent
I have a wrapper width of 720px, in it are some paragraphs and images. I need the paragraphs to be at 720px width, but the images should be wider (900px) and should extend the wrapper width. How can I do this?</p>

```<code>    <div class="wrapper">
        <p>...</p>
        <img>
        <p>...</p>
        <img>
    </div>
</code>```

答:
.wrapper{
  width:fit-content;
}
img{
  width:900px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
        <p>...</p>
        <img src="https://eoimages.gsfc.nasa.gov/images/imagerecords/146000/146220/lakebaikalring_oli_201692_th.jpg">
        <p>...</p>
        <img src="https://eoimages.gsfc.nasa.gov/images/imagerecords/146000/146220/lakebaikalring_oli_201692_th.jpg">
    </div></code>```

Title: Make child element wider than parent

Body:
I have a wrapper width of 720px, in it are some paragraphs and images. I need the paragraphs to be at 720px width, but the images should be wider (900px) and should extend the wrapper width. How can I do this?

...

...

Body:
.wrapper{
  width:fit-content;
}
img{
  width:900px;
}

<div class="wrapper">
        <p>...</p>
        <img src="https://eoimages.gsfc.nasa.gov/images/imagerecords/146000/146220/lakebaikalring_oli_201692_th.jpg">
        <p>...</p>
        <img src="https://eoimages.gsfc.nasa.gov/images/imagerecords/146000/146220/lakebaikalring_oli_201692_th.jpg">
    </div>


问:
Split values and loop through them
I have two tables:
Table1:

```<code>id | value
1  | val1
2  | val2
3  | val3
</code>```

Table2:

```<code>id | value
1  | val1,val2,val22
2  | val2
3  | val3,val15,
</code>```

The thing that I want to do is to split the values from Table2 by comma (to get separated values), next loop through it and find them in Table1. As a result I need the Table1.id and Table2.id that contains value from Table1 to insert them in the new table.

Is it possible to do it in mysql as there is no SPLIT function?

Edit: MySql version 5.7.27

Edit2: Desired result:

```<code>table1.id  table1.valie  table1.id  table1.valie
        1          val1          1  val1,val2,val22
        2          val2          1  val1,val2,val22
        2          val2          2  val2
        3          val3          3  val3,val15,
</code>```

答:
May be this would help you.

PATINDEX() replacement in MYSQL

After getting index split rows by index values.Your data will become like below

```<code>Table2:
id | value
1  | val1
1  | val2
1  | valu22
2  | val2
3  | val3
3  | val15
</code>```

then you can do something like :

```<code>select * from table2 where value in (select value from table1)
</code>```

Title: Split values and loop through them

Body:
I have two tables:
Table1:

id | value
1  | val1
2  | val2
3  | val3

Table2:

id | value
1  | val1,val2,val22
2  | val2
3  | val3,val15,

The thing that I want to do is to split the values from Table2 by comma (to get separated values), next loop through it and find them in Table1. As a result I need the Table1.id and Table2.id that contains value from Table1 to insert them in the new table.

Is it possible to do it in mysql as there is no SPLIT function?

Edit: MySql version 5.7.27

Edit2: Desired result:

table1.id  table1.valie  table1.id  table1.valie
        1          val1          1  val1,val2,val22
        2          val2          1  val1,val2,val22
        2          val2          2  val2
        3          val3          3  val3,val15,

Body:
May be this would help you.

PATINDEX() replacement in MYSQL

After getting index split rows by index values.Your data will become like below

Table2:
id | value
1  | val1
1  | val2
1  | valu22
2  | val2
3  | val3
3  | val15

then you can do something like :

select * from table2 where value in (select value from table1)


问:
Firestore simple collectionGroup makes the function timeout
I have a cloud function that is scheduled to run every 2 mins.
I am currently testing the function using an Http one, and trying to run a simple collectionGroup query as follows

Update 1
I updated my code to handle offset and limit but now it's working fine for the first record by then hangs while fetching the second record.

please check the snippet

```<code>/* eslint-disable promise/no-nesting */

/**
 * @description
 * This module will send out emails to different users who have alerts not sent out yet
 * @algorithm
 * 1 - Get all alerts where sent = false
 * 2 - Send out those alerts via the email module.
 */
const functions = require("firebase-functions");
const { db } = require("../helpers/firestore");
// console.log('admin: ', admin);
let _allUserAlerts = [];
let counter = 0;

exports.sendEmailsToUsers = functions.pubsub
  .schedule("every 2 minutes")
  .onRun(context => {
    return sendEmailsToUsers(context);
  });

exports.testSendEmailsToUsers = functions.https.onRequest((req, res) => {
  return sendEmailsToUsers("hello");
});

async function sendEmailsToUsers(context) {
  try {
    console.log("function execution")
    let alerts = await db
      .collectionGroup("alerts")
      .where("sent", "==", false)
      .limit(1)
      .offset(counter)
      .get();

    alerts.forEach(_alert => {
      if (_alert.exists) {
        console.log("alert exists")
        _allUserAlerts.push(_alert.data());
        counter++;
        return sendEmailsToUsers()
      } else {
        console.log("alert ends")
        sendAlertsToEmail(_allUserAlerts)
      }
    })
  } catch (err) {
    console.log(err)
  }
}

async function sendAlertsToEmail(alerts) {
  console.log('alerts: ', alerts);
}

</code>```

Old code

```<code>/* eslint-disable promise/no-nesting */

/**
 * @description
 * This module will send out emails to different users who have alerts not sent out yet
 * @algorithm
 * 1 - Get all alerts where sent = false
 * 2 - Send out those alerts via the email module.
 */
const functions = require("firebase-functions");
const { db } = require("../helpers/firestore");
const { Email } = require("../EmailModule");

const { groupBy } = require("../helpers/groupBy");

exports.sendEmailsToUsers = functions.pubsub
  .schedule("every 2 minutes")
  .onRun(context => {
    return sendEmailsToUsers(context);
  });

async function sendEmailsToUsers(context) {
  try {
    console.log("function execution")
    let alerts = await db
      .collectionGroup("alerts")
      .where("sent", "==", false)
      .get();
    console.log('alerts: ', alerts);
  } catch (err) {
    console.log(err)
  }
}

</code>```

This is literally the entire code in the function, but the function times out and I don't get to the log() of alerts.
I am not getting what could be the problem here ? Any thing I might be missing or not getting here ? Any help would be appreciated.

Thanks

答:
The solution to this problem was to upgrade the current node version.
By default Cloud functions work on Node 8 which has stopped support from the official node.js team. So when I upgrade to Node 10 it started working again perfectly !

Body:
I have a cloud function that is scheduled to run every 2 mins.
I am currently testing the function using an Http one, and trying to run a simple collectionGroup query as follows

Update 1
I updated my code to handle offset and limit but now it's working fine for the first record by then hangs while fetching the second record.

please check the snippet

/* eslint-disable promise/no-nesting */

/**
 * @description
 * This module will send out emails to different users who have alerts not sent out yet
 * @algorithm
 * 1 - Get all alerts where sent = false
 * 2 - Send out those alerts via the email module.
 */
const functions = require("firebase-functions");
const { db } = require("../helpers/firestore");
// console.log('admin: ', admin);
let _allUserAlerts = [];
let counter = 0;

exports.sendEmailsToUsers = functions.pubsub
  .schedule("every 2 minutes")
  .onRun(context => {
    return sendEmailsToUsers(context);
  });

exports.testSendEmailsToUsers = functions.https.onRequest((req, res) => {
  return sendEmailsToUsers("hello");
});

async function sendEmailsToUsers(context) {
  try {
    console.log("function execution")
    let alerts = await db
      .collectionGroup("alerts")
      .where("sent", "==", false)
      .limit(1)
      .offset(counter)
      .get();

    alerts.forEach(_alert => {
      if (_alert.exists) {
        console.log("alert exists")
        _allUserAlerts.push(_alert.data());
        counter++;
        return sendEmailsToUsers()
      } else {
        console.log("alert ends")
        sendAlertsToEmail(_allUserAlerts)
      }
    })
  } catch (err) {
    console.log(err)
  }
}

async function sendAlertsToEmail(alerts) {
  console.log('alerts: ', alerts);
}

Old code

/* eslint-disable promise/no-nesting */

/**
 * @description
 * This module will send out emails to different users who have alerts not sent out yet
 * @algorithm
 * 1 - Get all alerts where sent = false
 * 2 - Send out those alerts via the email module.
 */
const functions = require("firebase-functions");
const { db } = require("../helpers/firestore");
const { Email } = require("../EmailModule");

const { groupBy } = require("../helpers/groupBy");

exports.sendEmailsToUsers = functions.pubsub
  .schedule("every 2 minutes")
  .onRun(context => {
    return sendEmailsToUsers(context);
  });

async function sendEmailsToUsers(context) {
  try {
    console.log("function execution")
    let alerts = await db
      .collectionGroup("alerts")
      .where("sent", "==", false)
      .get();
    console.log('alerts: ', alerts);
  } catch (err) {
    console.log(err)
  }
}

This is literally the entire code in the function, but the function times out and I don't get to the log() of alerts.
I am not getting what could be the problem here ? Any thing I might be missing or not getting here ? Any help would be appreciated.

Thanks


答:
basically you don't have to do anything special. See the orange border which is set on the .wrapper element, That's 720px wide. The image just goes over it. As long as you haven't done anything else (which you didn't list in the question)...

.wrapper {
    width: 720px;
    border: solid 5px orange;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="wrapper">
        <p>...</p>
        <img src="https://picsum.photos/900/700">
        <p>...</p>
        <img>
    </div></code>```

Title: Make child element wider than parent

Body:
basically you don't have to do anything special. See the orange border which is set on the .wrapper element, That's 720px wide. The image just goes over it. As long as you haven't done anything else (which you didn't list in the question)...

.wrapper {
    width: 720px;
    border: solid 5px orange;
}

 <div class="wrapper">
        <p>...</p>
        <img src="https://picsum.photos/900/700">
        <p>...</p>
        <img>
    </div>


问:
java throw new NoSuchElementException build failed with arraylist
I'm coding a stack implementation using Arraylist. I'm trying to use NoSuchElementException when it tries to pop when the array is empty but I get a build error message and I have no idea what is going on. Here is the output I'm getting:

```<code>please enter your number:

1 f
*********************Stack ArrayList Implementation*********************
false
1
1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.ArrayList.elementData(ArrayList.java:422)
    at java.util.ArrayList.get(ArrayList.java:435)
    at StackUsingArrayList.peek(StackUsingArrayList.java:42)
    at StackUsingArrayList.main(StackUsingArrayList.java:74)
C:\Users\alsrb\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 4 seconds)
</code>```

this part seems to be the problem and the funny thing is if I don't use exception throws, it works just fine.

```<code>int pop() {
if (!isEmpty()) { // checks for an empty Stack
      int popValue = stackList.get(stackList.size() - 1);
      stackList.remove(stackList.size() - 1); // removes the poped element
      return popValue;
} else {
    throw new NoSuchElementException();
    //System.out.print("The stack is already empty  ");
    //return -1;
}
}
</code>```

Somebody please help me.
here's my whole code

```<code>import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class StackUsingArrayList{
Scanner scanner = new Scanner(System.in);

ArrayList<Integer> stackList;

StackUsingArrayList() {
    stackList = new ArrayList<>();
}

void push(int v) {
    stackList.add(v);
}

int pop() {
    if (!isEmpty()) { // checks for an empty Stack
          int popValue = stackList.get(stackList.size() - 1);
          stackList.remove(stackList.size() - 1); // removes the poped element
          return popValue;
    } else {
        throw new NoSuchElementException();
        //System.out.print("The stack is already empty  ");
        //return -1;
    }
}

boolean isEmpty() {
    if (stackList.get(0) == null){
        return true;
    } else {
        return false;
    }
}

int peek() {
    return stackList.get(stackList.size() - 1);
}

int size(){
    int i = 0;
    while(stackList != null){
        stackList.get(i);
        i++;
    }
return i;
}

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    StackUsingArrayList myStack = new StackUsingArrayList();

    System.out.println("Please enter your number: ");

    while(scanner.hasNextInt()){
        int x = scanner.nextInt();
        if(x >= 0){
        myStack.push(x);
        }
    }

    System.out.println("*********************Stack ArrayList Implementation*********************");
    System.out.println(myStack.isEmpty());
    System.out.println(myStack.peek());
    System.out.println(myStack.pop());
    System.out.println(myStack.peek());
    System.out.println(myStack.pop());
    System.out.println(myStack.peek());
    System.out.println(myStack.pop());
}
}
</code>```

答:
Are you sure it works without the exeception? From what I see you have used the input "1", which fills you ArrayList with one element.
In your main method you peek (returns "1") and then pop (returns "1"). And then you continue to peek and pop, resulting in the next peek call to execute

```<code>int peek() {
    return stackList.get(stackList.size() - 1);
}
</code>```

Since you already popped the only element in the list, the list size is 0. That means you try to return stackList.get(0-1), which correctly throws the ArrayIndexOutOfBoundsException.

You could add a check in the peek function to see if there are elements left in the list. If not, it might be a good idea to return null.

Besides that, it might be a good idea to have a look at the ArrayList methods provided by java. Specifically ArrayList.size() and ArrayList.isEmpty() are good alternatives to use.

Body:
I'm coding a stack implementation using Arraylist. I'm trying to use NoSuchElementException when it tries to pop when the array is empty but I get a build error message and I have no idea what is going on. Here is the output I'm getting:

please enter your number:

1 f
*********************Stack ArrayList Implementation*********************
false
1
1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.ArrayList.elementData(ArrayList.java:422)
    at java.util.ArrayList.get(ArrayList.java:435)
    at StackUsingArrayList.peek(StackUsingArrayList.java:42)
    at StackUsingArrayList.main(StackUsingArrayList.java:74)
C:\Users\alsrb\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 4 seconds)

this part seems to be the problem and the funny thing is if I don't use exception throws, it works just fine.

int pop() {
if (!isEmpty()) { // checks for an empty Stack
      int popValue = stackList.get(stackList.size() - 1);
      stackList.remove(stackList.size() - 1); // removes the poped element
      return popValue;
} else {
    throw new NoSuchElementException();
    //System.out.print("The stack is already empty  ");
    //return -1;
}
}

Somebody please help me.
here's my whole code

import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class StackUsingArrayList{
Scanner scanner = new Scanner(System.in);

ArrayList<Integer> stackList;

StackUsingArrayList() {
    stackList = new ArrayList<>();
}

void push(int v) {
    stackList.add(v);
}

int pop() {
    if (!isEmpty()) { // checks for an empty Stack
          int popValue = stackList.get(stackList.size() - 1);
          stackList.remove(stackList.size() - 1); // removes the poped element
          return popValue;
    } else {
        throw new NoSuchElementException();
        //System.out.print("The stack is already empty  ");
        //return -1;
    }
}

boolean isEmpty() {
    if (stackList.get(0) == null){
        return true;
    } else {
        return false;
    }
}

int peek() {
    return stackList.get(stackList.size() - 1);
}

int size(){
    int i = 0;
    while(stackList != null){
        stackList.get(i);
        i++;
    }
return i;
}

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    StackUsingArrayList myStack = new StackUsingArrayList();

    System.out.println("Please enter your number: ");

    while(scanner.hasNextInt()){
        int x = scanner.nextInt();
        if(x >= 0){
        myStack.push(x);
        }
    }

    System.out.println("*********************Stack ArrayList Implementation*********************");
    System.out.println(myStack.isEmpty());
    System.out.println(myStack.peek());
    System.out.println(myStack.pop());
    System.out.println(myStack.peek());
    System.out.println(myStack.pop());
    System.out.println(myStack.peek());
    System.out.println(myStack.pop());
}
}

Body:
Are you sure it works without the exeception? From what I see you have used the input "1", which fills you ArrayList with one element.
In your main method you peek (returns "1") and then pop (returns "1"). And then you continue to peek and pop, resulting in the next peek call to execute

int peek() {
    return stackList.get(stackList.size() - 1);
}

Since you already popped the only element in the list, the list size is 0. That means you try to return stackList.get(0-1), which correctly throws the ArrayIndexOutOfBoundsException.

You could add a check in the peek function to see if there are elements left in the list. If not, it might be a good idea to return null.

Besides that, it might be a good idea to have a look at the ArrayList methods provided by java. Specifically ArrayList.size() and ArrayList.isEmpty() are good alternatives to use.


问:
how to get correct ClientID
update:
asp.net

```<code><asp:RadioButtonList runat="server" ID="rbl" RepeatDirection="Horizontal">
    <asp:ListItem Text="None" Value="0" Selected="True" Enabled="true" />
    <asp:ListItem Text="Float" Value="1" Selected="False" Enabled="true" />
    <asp:ListItem Text="Float1" Value="2" Selected="False" Enabled="true" />
    <asp:ListItem Text="Center" Value="3" Selected="False" Enabled="false" />
</asp:RadioButtonList>
</code>```

when i view the source this is what it is rendering:

```<code>$('#ctl00_ctl00_ContentMain_rbl').hover(
    function (){
        $('#div1').dialog({title: "some title"});
        $('#div1').dialog('open');
    }
);
</code>```

the correct clientid is: ctl00_ctl00_ContentMain_rbl_0, ctl00_ctl00_ContentMain_rbl_1, ctl00_ctl00_ContentMain_rbl_2

the code does not work and it did not give me the correct ClientID name when i try to read it... what is the other way round for this problem, define class name ???

```<code>   $('#<%= rbl.ClientID %>').hover(
            function (){
                $('#div1').dialog({title: "Float Images Left"});
                $('#div1').dialog('open');
            }            );
</code>```

答:
If you want to do something on hover for the radio buttons, you have to target the inputs</p>

```<code>$('#<%= rbl.ClientID %> input').hover(
    function (){
        $('#div1').dialog({title: "Float Images Left"});
        $('#div1').dialog('open');
    }
);
</code>```

Title: how to get correct ClientID

Body:
update:
asp.net

<asp:RadioButtonList runat="server" ID="rbl" RepeatDirection="Horizontal">
    <asp:ListItem Text="None" Value="0" Selected="True" Enabled="true" />
    <asp:ListItem Text="Float" Value="1" Selected="False" Enabled="true" />
    <asp:ListItem Text="Float1" Value="2" Selected="False" Enabled="true" />
    <asp:ListItem Text="Center" Value="3" Selected="False" Enabled="false" />
</asp:RadioButtonList>

when i view the source this is what it is rendering:

$('#ctl00_ctl00_ContentMain_rbl').hover(
    function (){
        $('#div1').dialog({title: "some title"});
        $('#div1').dialog('open');
    }
);

the correct clientid is: ctl00_ctl00_ContentMain_rbl_0, ctl00_ctl00_ContentMain_rbl_1, ctl00_ctl00_ContentMain_rbl_2

the code does not work and it did not give me the correct ClientID name when i try to read it... what is the other way round for this problem, define class name ???

   $('#<%= rbl.ClientID %>').hover(
            function (){
                $('#div1').dialog({title: "Float Images Left"});
                $('#div1').dialog('open');
            }            );

Body:
If you want to do something on hover for the radio buttons, you have to target the inputs

$('#<%= rbl.ClientID %> input').hover(
    function (){
        $('#div1').dialog({title: "Float Images Left"});
        $('#div1').dialog('open');
    }
);


问:
Cgo pass a string to C file
I am using cgo and saw this post about running c++ from go:

I want to use [this function] in Go. I'll use the C interface

```<code>  // foo.h
  #ifdef __cplusplus
  extern "C" {
  #endif
   typedef void* Foo;
   Foo FooInit(void);
   void FooFree(Foo);
   void FooBar(Foo);
  #ifdef __cplusplus
  }
  #endif
</code>```

I did this, but how can I pass a string as an argument to the C++ function? I tried to pass a rune[] but it did not work.

答:
This is the Go code:

// GetFileSizeC wrapper method for retrieve byte lenght of a file
func GetFileSizeC(filename string) int64 {
    // Cast a string to a 'C string'
    fname := C.CString(filename)
    defer C.free(unsafe.Pointer(fname))
    // get the file size of the file
    size := C.get_file_size(fname)
    return int64(size)
}
```

<p>From C</p>

```long get_file_size(char *filename) {
  long fsize = 0;
  FILE *fp;
  fp = fopen(filename, "r");
  if (fp) {
    fseek(fp, 0, SEEK_END);
    fsize = ftell(fp);
    fclose(fp);
  }
  return fsize;
}
```

<p>Remember that you need to add the headers library that you need before the import in the Go file:</p>

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

// #cgo CFLAGS: -g -Wall
// #include <stdio.h>   |
// #include <stdlib.h>  | -> these are the necessary system header
// #include <string.h>  |
// #include "cutils.h" <-- this is a custom header file
import "C"
import (
    "bufio"
    "encoding/json"
    "fmt"
    "io/ioutil"
     ....
)
</code>```

This is an old project that you can use for future working example:

https://github.com/alessiosavi/GoUtils

Title: Cgo pass a string to C file

Body:
I am using cgo and saw this post about running c++ from go:

I want to use [this function] in Go. I'll use the C interface

  // foo.h
  #ifdef __cplusplus
  extern "C" {
  #endif
   typedef void* Foo;
   Foo FooInit(void);
   void FooFree(Foo);
   void FooBar(Foo);
  #ifdef __cplusplus
  }
  #endif

I did this, but how can I pass a string as an argument to the C++ function? I tried to pass a rune[] but it did not work.

Body:
This is the Go code:

// GetFileSizeC wrapper method for retrieve byte lenght of a file
func GetFileSizeC(filename string) int64 {
    // Cast a string to a 'C string'
    fname := C.CString(filename)
    defer C.free(unsafe.Pointer(fname))
    // get the file size of the file
    size := C.get_file_size(fname)
    return int64(size)
}

From C

long get_file_size(char *filename) {
  long fsize = 0;
  FILE *fp;
  fp = fopen(filename, "r");
  if (fp) {
    fseek(fp, 0, SEEK_END);
    fsize = ftell(fp);
    fclose(fp);
  }
  return fsize;
}

Remember that you need to add the headers library that you need before the import in the Go file:

package utils

// #cgo CFLAGS: -g -Wall
// #include <stdio.h>   |
// #include <stdlib.h>  | -> these are the necessary system header
// #include <string.h>  |
// #include "cutils.h" <-- this is a custom header file
import "C"
import (
    "bufio"
    "encoding/json"
    "fmt"
    "io/ioutil"
     ....
)

This is an old project that you can use for future working example:

https://github.com/alessiosavi/GoUtils


Title: How to create array this data

Body:
Please help me.

I want to create an array like this.

{
    "polyline": [
        [-5.40044378489256, 105.256219301373],
        [-5.40040246210992, 105.255722338334],
        [-5.40040673688054, 105.255641704425],
        [-5.40068350732327, 105.254918346182],
        [-5.40083421394229, 105.254701003432]
    ]
}

how implement in php array()?

Body:
This is a valid JSON actually. You can convert it to PHP array by using json_decode(), like:

<?php
$data = '{
    "polyline": [
        [-5.40044378489256, 105.256219301373],
        [-5.40040246210992, 105.255722338334],
        [-5.40040673688054, 105.255641704425],
        [-5.40068350732327, 105.254918346182],
        [-5.40083421394229, 105.254701003432]
    ]
}';

$arr = json_decode($data, true);
print_r($arr);

Output:

Array
(
    [polyline] => Array
        (
            [0] => Array
                (
                    [0] => -5.4004437848926
                    [1] => 105.25621930137
                )

            [1] => Array
                (
                    [0] => -5.4004024621099
                    [1] => 105.25572233833
                )

            [2] => Array
                (
                    [0] => -5.4004067368805
                    [1] => 105.25564170443
                )

            [3] => Array
                (
                    [0] => -5.4006835073233
                    [1] => 105.25491834618
                )

            [4] => Array
                (
                    [0] => -5.4008342139423
                    [1] => 105.25470100343
                )

        )

)


问:
jQuery how to select options by values?
How to select options which are not in 'restrictedIds', for example, selector should select the options with values 24 and 31.
Also I know how it could be done with using '.inArray' and '.each()' but it would be good to look at yours solutions. Thank you.</p>

```<code>...
var restrictedIds='0,38,23';
...
<select class="text4" size="1" name="drivers">
        <option value="0"></option>
        <option value="24">test1</option>
        <option value="31">test2</option>
        <option value="38">test3</option>
        <option value="23">test4</option>
</select>
</code>```

答:
You should take a look at these articles:

http://api.jquery.com/attribute-equals-selector/

http://api.jquery.com/attribute-not-equal-selector/

http://api.jquery.com/multiple-attribute-selector/

What you can do is select only options from whitelist, i.e.

```<code>$('option[value=24],option[value=31]')
</code>```

But I'm not sure if this is faster than .each()..

Title: jQuery how to select options by values?

Body:
How to select options which are not in 'restrictedIds', for example, selector should select the options with values 24 and 31.
Also I know how it could be done with using '.inArray' and '.each()' but it would be good to look at yours solutions. Thank you.

...
var restrictedIds='0,38,23';
...
<select class="text4" size="1" name="drivers">
        <option value="0"></option>
        <option value="24">test1</option>
        <option value="31">test2</option>
        <option value="38">test3</option>
        <option value="23">test4</option>
</select>

Body:
You should take a look at these articles:

http://api.jquery.com/attribute-equals-selector/

http://api.jquery.com/attribute-not-equal-selector/

http://api.jquery.com/multiple-attribute-selector/

What you can do is select only options from whitelist, i.e.

$('option[value=24],option[value=31]')

But I'm not sure if this is faster than .each()..


问:
How to find all subdomain for a particular given domain
So I have a  domain name let's say example.com, so is it possible to find all the sub-domains like a.example.com, b.example.com, etc.?

答:
You can use command like:

```<code>dig example.com ALL
</code>```

or

```<code>host -l example.com
</code>```

But be aware you will get result only if machine where you run this have permission to do  zone transfers for this domain. Otherwise you will see nothing.

Body:
You can use command like:

dig example.com ALL

or

host -l example.com

But be aware you will get result only if machine where you run this have permission to do  zone transfers for this domain. Otherwise you will see nothing.


问:
Modifying database in Access with query by insert?
Currently I am modifying my database tables with query SQL and I just have to insert a new row into the table but I can't seem to make my query run and at the moment my code reads:

INSERT INTO Facility( facname)
Values ('Swimming Pool')

Is there a step within the SQL I am missing or something for I genuinely can not figure it out. Thank you.

答:
You need to execute it:

```<code>CurrentDb.Execute "Insert Into Facility (facname) Values ('Swimming Pool')"
</code>```

Body:
You need to execute it:

CurrentDb.Execute "Insert Into Facility (facname) Values ('Swimming Pool')"


问:
How to set a scrolling distance limit for the scrollable UI (Unity)?
I work on a simple scrollable UI in Unity.

I have a canvas in the scene, it has Empty as a child.

The Empty is a parent for a long UI panel with different buttons.

I use the following script (assigned to the Empty) to make it scrollable:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class PageSwiper : MonoBehaviour, IDragHandler, IEndDragHandler
{
    private Vector3 scrollableUILocation;

    // Start is called before the first frame update
    void Start()
    {
        scrollableUILocation = transform.position;
    }
    public void OnDrag(PointerEventData data)
    {
        float difference = data.pressPosition.x - data.position.x;
        transform.position = scrollableUILocation - new Vector3(difference, 0, 0);
    }
    public void OnEndDrag(PointerEventData data)
    {
        scrollableUILocation = transform.position;

    }
}
</code>```

The problem is that I can scroll the UI panel outside of the screen. So I need to make it impossible, or make it so that if I scroll it too far, it smoothly returns back (to the end or to the start of the UI panel, depending on which is closer)

How can I do it?

I tried to implement the following solution but it doesn't work:

I added two Empty object on the left and on the right from the UI panel. I tried to make my UI panel to smoothly move at the position of one of those empty objects in case if I would move it close enough to them. But it doesn't work.

```<code> public void OnEndDrag(PointerEventData data)
{
    if (Vector3.Distance(transform.position, StartPoint.transform.position) < 1.0f)
    {
        StartCoroutine(SmoothMove(transform.position, StartPoint.transform.position, easing));
    }

    else if (Vector3.Distance(transform.position, EndPoint.transform.position) < 1.0f)
    {
        StartCoroutine(SmoothMove(transform.position, EndPoint.transform.position, easing));
    }

}

IEnumerator SmoothMove(Vector3 startpos, Vector3 endpos, float seconds)
{
    float t = 0f;
    while (t <= 1.0)
    {
        t += Time.deltaTime / seconds;
        transform.position = Vector3.Lerp(startpos, endpos, Mathf.SmoothStep(0f, 1f, t));
        yield return null;
    }
}
</code>```

答:
So you'd be better off with a ScrollRect as it already contains all the needed actions for this kind of feature.

MovementType will define how the system reacts when reaching the end of the container (from the documentation):

Unrestricted The content can move forever.

Elastic The content is allowed to temporarily move beyond the container, but is pulled back elastically.

Clamped The content can not be moved beyond its container.

Considering you have a long button system, maybe it needs to be dynamic, so you'd look into ContentSizeFitter.

You add a scroll view object. This will include by default:

Scrollview

Viewport

Content

Now add a Text component to the Content object, NOT a text child, a component to it. Also add a ContentSizeFitter and set the vertical fit to prefered size. This is because I will deal with vertical expansion.

Make sure the Viewport occupies the space that should serve as mask. For first practice, place the ScrollView object in the middle and set the anchors of Viewport to 0,1 so it takes the whole parent.

There is plenty more you can do and I would suggest to look into the free Unity UI extension library as it has some fancy accordeon or endless scrolling effects.

Body:
I work on a simple scrollable UI in Unity.

I have a canvas in the scene, it has Empty as a child.

The Empty is a parent for a long UI panel with different buttons.

I use the following script (assigned to the Empty) to make it scrollable:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class PageSwiper : MonoBehaviour, IDragHandler, IEndDragHandler
{
    private Vector3 scrollableUILocation;

    // Start is called before the first frame update
    void Start()
    {
        scrollableUILocation = transform.position;
    }
    public void OnDrag(PointerEventData data)
    {
        float difference = data.pressPosition.x - data.position.x;
        transform.position = scrollableUILocation - new Vector3(difference, 0, 0);
    }
    public void OnEndDrag(PointerEventData data)
    {
        scrollableUILocation = transform.position;

    }
}

The problem is that I can scroll the UI panel outside of the screen. So I need to make it impossible, or make it so that if I scroll it too far, it smoothly returns back (to the end or to the start of the UI panel, depending on which is closer)

How can I do it?

I tried to implement the following solution but it doesn't work:

I added two Empty object on the left and on the right from the UI panel. I tried to make my UI panel to smoothly move at the position of one of those empty objects in case if I would move it close enough to them. But it doesn't work.

 public void OnEndDrag(PointerEventData data)
{
    if (Vector3.Distance(transform.position, StartPoint.transform.position) < 1.0f)
    {
        StartCoroutine(SmoothMove(transform.position, StartPoint.transform.position, easing));
    }

    else if (Vector3.Distance(transform.position, EndPoint.transform.position) < 1.0f)
    {
        StartCoroutine(SmoothMove(transform.position, EndPoint.transform.position, easing));
    }

}

IEnumerator SmoothMove(Vector3 startpos, Vector3 endpos, float seconds)
{
    float t = 0f;
    while (t <= 1.0)
    {
        t += Time.deltaTime / seconds;
        transform.position = Vector3.Lerp(startpos, endpos, Mathf.SmoothStep(0f, 1f, t));
        yield return null;
    }
}


问:
How to upload multiple image to s3 in react-native?
I got bucket name, accesskey, region from my colleauge.

I want to upload image to s3 bucket.

How can I do this?

Thanks!

答: You should also check the Amplify framework from AWS (e.g. Storage.Put).</p>


问:
Send a product's custom feature in order confirmation email
I want to send the "units per box" custom feature in my confirmation mails in prestashop.

Here's an example if what I want to do

```<code>$myprod = new Product($product['id_product']);
$features = $myprod->getFrontFeatures(1));

foreach(from=$features item=feature)
{
  if ($feature.name == "Units per box")
  {
     $UnitsPerBox = $feature.value|escape:'htmlall':'UTF-8';
  }
}
</code>```

However I need to do this within a php file (PaymentModule.php) rather than a tpl file, so that code won't work.
If anybody could point me in the right direction of how to achieve this with php it'd be greatly appreciated.

EDIT:

I used the example code provided which seems to get inside the array but doesn't return any values

When I run some test code like this

```<code>$myprod = new Product($product['id_product']);
$features = $myprod->getFrontFeatures(1);
$UnitsPerBox .= '100';
foreach ($features as $feature)
{
  $UnitsPerBox .= '200';
  if ($feature->name == 'Units Per Box')
  {
    $UnitsPerBox .= htmlentities($feature->value, 'ENT_QUOTES', 'UTF-8');
    $UnitsPerBox .= $feature->name;
  }
  else
  {
    $UnitsPerBox .= $feature->name;
    $UnitsPerBox .= htmlentities($feature->name, 'ENT_QUOTES', 'UTF-8');
    $UnitsPerBox .= htmlentities($feature->value, 'ENT_QUOTES', 'UTF-8');
  }
}
</code>```

I get this output: "100200200200200200"

Any help would be great, thanks.

Thanks,
Andrew

EDIT: Solution

Got it working in the end, thanks for the help

```<code>$myprod = new Product($product['id_product']);
$features = $myprod->getFrontFeatures(1);
foreach ($features as $feature)
{
foreach ($feature as $key => $value)
{
    if($value == "Units per box")
    {
        $UnitsPerBox = $feature['value'];
    }
}
</code>```

}

答:
```<code>$myprod = new Product($product['id_product']);
$features = $myprod->getFrontFeatures(1);

foreach ($features as $feature) {
   if ($feature->name == 'Units per box') {
      $UnitsPerBox = htmlentities($feature->value, 'ENT_QUOTES', 'UTF-8');
   }
}
</code>```

Body:
I want to send the "units per box" custom feature in my confirmation mails in prestashop.

Here's an example if what I want to do

$myprod = new Product($product['id_product']);
$features = $myprod->getFrontFeatures(1));

foreach(from=$features item=feature)
{
  if ($feature.name == "Units per box")
  {
     $UnitsPerBox = $feature.value|escape:'htmlall':'UTF-8';
  }
}

However I need to do this within a php file (PaymentModule.php) rather than a tpl file, so that code won't work.
If anybody could point me in the right direction of how to achieve this with php it'd be greatly appreciated.

EDIT:

I used the example code provided which seems to get inside the array but doesn't return any values

When I run some test code like this

$myprod = new Product($product['id_product']);
$features = $myprod->getFrontFeatures(1);
$UnitsPerBox .= '100';
foreach ($features as $feature)
{
  $UnitsPerBox .= '200';
  if ($feature->name == 'Units Per Box')
  {
    $UnitsPerBox .= htmlentities($feature->value, 'ENT_QUOTES', 'UTF-8');
    $UnitsPerBox .= $feature->name;
  }
  else
  {
    $UnitsPerBox .= $feature->name;
    $UnitsPerBox .= htmlentities($feature->name, 'ENT_QUOTES', 'UTF-8');
    $UnitsPerBox .= htmlentities($feature->value, 'ENT_QUOTES', 'UTF-8');
  }
}

I get this output: "100200200200200200"

Any help would be great, thanks.

Thanks,
Andrew

EDIT: Solution

Got it working in the end, thanks for the help

$myprod = new Product($product['id_product']);
$features = $myprod->getFrontFeatures(1);
foreach ($features as $feature)
{
foreach ($feature as $key => $value)
{
    if($value == "Units per box")
    {
        $UnitsPerBox = $feature['value'];
    }
}

}


问:
How to call tryton from jsonrpc
I'm trying to connect via json-rpc to the trytond isntance using this class

```<code>class HttpClient:
    """HTTP Client to make JSON RPC requests to Tryton server.
    User is logged in when an object is created.
    """

    def __init__(self, url, database_name, user, passwd):
        self._url = '{}/{}/'.format(url, database_name)
        self._user = user
        self._passwd = passwd
        self._login()
        self._id = 0

    def get_id(self):
        self._id += 1
        return self._id

    def _login(self):
        """
        Returns list, where
        0 - user id
        1 - session token
        """
        payload = json.dumps({
            'params': [self._user, {'password': self._passwd}],
            'jsonrpc': "2.0",
            'method': 'common.db.login',
            'id': 1,
        })
        headers = {'content-type': 'application/json'}
        result = requests.post(self._url, data=payload, headers=headers)
        if result.status_code in [500, 401]:
            raise Exception(result.text)

        if 'json' in result:
            self._session = result.json()['result']
        else:
            self._session = json.loads(result.text)

        return self._session

    def call(self, prefix, method, params=[[], {}]):
        """RPC Call
        """
        method = '{}.{}'.format(prefix, method)
        payload = json.dumps({
            'params': params,
            'method': method,
            'id': self.get_id(),

        })

        authorization = base64.b64encode(self._session[1].encode('utf-8'))
        headers = {
        'Content-Type': 'application/json',
        'Authorization': b'Session ' + authorization
        }

        response = requests.post(self._url, data=payload, headers=headers)
        if response.status_code in [500, 401]:
            raise Exception(response.text)
        return response.json()

    def model(self, model, method, args=[], kwargs={}):
        return self.call('model.%s' % model, method, [args, kwargs])

    def system(self, method):
        return self.call('system', method, params=[])
</code>```

and I call it in this way

```<code>def notifieToMainServer(self):
    url = "http://%s:%s" % (HOST, PORT)
    headers = {'content-type': 'application/json'}
    client = HttpClient(url, "tryton", CREDENTIALS[0], CREDENTIALS[1])
    client.model('main.register',
                 'ActivateService',
                 {'code': self.code,
                  'name': self.nome,
                  'surname': self.cognome,
                  'service_type': 'registry',
                  'service_url': '' # qui andra messa l'url di chimata
                  }
                 )
</code>```

the creatin of the HttpClient works well and I'm able to login, but when I try to call the method ActivateService I recive a 401 responce.

I also add the ActivateService into the rpc class

```<code>@classmethod
def __setup__(cls):
    super(MainRegister, cls).__setup__()
    cls.__rpc__.update({
            'ActivateService': RPC(instantiate=0)})
</code>```

and the function is like

```<code>def ActivateService(self,
                    code,
                    name,
                    surname,
                    service_type,
                    service_url):
    """
        activate the service for the given code and the given service
    """
</code>```

what I did wrong ?

best regards,
Matteo

答:
At the and I finally solve the problem with this modifies class

```<code>class HttpClient:
    """HTTP Client to make JSON RPC requests to Tryton server.
    User is logged in when an object is created.
    """

    def __init__(self, url, database_name, user, passwd):
        self._url = '{}/{}/'.format(url, database_name)
        self._user = user
        self._passwd = passwd
        self._login()
        self._id = 0

    def get_id(self):
        self._id += 1
        return self._id

    def _login(self):
        """
        Returns list, where
        0 - user id
        1 - session token
        """
        payload = json.dumps({
            'params': [self._user, {'password': self._passwd}],
            'jsonrpc': "2.0",
            'method': 'common.db.login',
            'id': 1,
        })
        headers = {'content-type': 'application/json'}
        result = requests.post(self._url,
                               data=payload,
                               headers=headers)
        if result.status_code in [500, 401]:
            raise Exception(result.text)

        if 'json' in result:
            self._session = result.json()['result']
        else:
            self._session = json.loads(result.text)

        return self._session

    def call(self, prefix, method, params=[[], {}, {}]):
        """RPC Call
        """
        method = '{}.{}'.format(prefix, method)
        payload = json.dumps({
            'params': params,
            'method': method,
            'id': self.get_id(),
         })
        auth = "%s:%s:%s" % (self._user, self._session[0], self._session[1])
        authorization = base64.b64encode(auth.encode('utf-8'))
        headers = {
        'Content-Type': 'application/json',
        'Authorization': b'Session ' + authorization
        }

        response = requests.post(self._url,
                                 data=payload,
                                 headers=headers)
        if response.status_code in [500, 401]:
            raise Exception(response.text)
        return response.json()

    def model(self, model, method, args=[], kwargs={}):
        return self.call('model.%s' % model, method, (args, kwargs, {}))

    def system(self, method):
        return self.call('system', method, params=[])
</code>```

the key point is the call that must be done with the context in order to be executed in the right way !!

```<code>    def model(self, model, method, args=[], kwargs={}):
        return self.call('model.%s' % model, method, (args, kwargs, {}))
</code>```

hope it helps
regards

Title: How to call tryton from jsonrpc

Body:
I'm trying to connect via json-rpc to the trytond isntance using this class

class HttpClient:
    """HTTP Client to make JSON RPC requests to Tryton server.
    User is logged in when an object is created.
    """

    def __init__(self, url, database_name, user, passwd):
        self._url = '{}/{}/'.format(url, database_name)
        self._user = user
        self._passwd = passwd
        self._login()
        self._id = 0

    def get_id(self):
        self._id += 1
        return self._id

    def _login(self):
        """
        Returns list, where
        0 - user id
        1 - session token
        """
        payload = json.dumps({
            'params': [self._user, {'password': self._passwd}],
            'jsonrpc': "2.0",
            'method': 'common.db.login',
            'id': 1,
        })
        headers = {'content-type': 'application/json'}
        result = requests.post(self._url, data=payload, headers=headers)
        if result.status_code in [500, 401]:
            raise Exception(result.text)

        if 'json' in result:
            self._session = result.json()['result']
        else:
            self._session = json.loads(result.text)

        return self._session

    def call(self, prefix, method, params=[[], {}]):
        """RPC Call
        """
        method = '{}.{}'.format(prefix, method)
        payload = json.dumps({
            'params': params,
            'method': method,
            'id': self.get_id(),

        })

        authorization = base64.b64encode(self._session[1].encode('utf-8'))
        headers = {
        'Content-Type': 'application/json',
        'Authorization': b'Session ' + authorization
        }

        response = requests.post(self._url, data=payload, headers=headers)
        if response.status_code in [500, 401]:
            raise Exception(response.text)
        return response.json()

    def model(self, model, method, args=[], kwargs={}):
        return self.call('model.%s' % model, method, [args, kwargs])

    def system(self, method):
        return self.call('system', method, params=[])

and I call it in this way

def notifieToMainServer(self):
    url = "http://%s:%s" % (HOST, PORT)
    headers = {'content-type': 'application/json'}
    client = HttpClient(url, "tryton", CREDENTIALS[0], CREDENTIALS[1])
    client.model('main.register',
                 'ActivateService',
                 {'code': self.code,
                  'name': self.nome,
                  'surname': self.cognome,
                  'service_type': 'registry',
                  'service_url': '' # qui andra messa l'url di chimata
                  }
                 )

the creatin of the HttpClient works well and I'm able to login, but when I try to call the method ActivateService I recive a 401 responce.

I also add the ActivateService into the rpc class

@classmethod
def __setup__(cls):
    super(MainRegister, cls).__setup__()
    cls.__rpc__.update({
            'ActivateService': RPC(instantiate=0)})

and the function is like

def ActivateService(self,
                    code,
                    name,
                    surname,
                    service_type,
                    service_url):
    """
        activate the service for the given code and the given service
    """

what I did wrong ?

best regards,
Matteo

Body:
At the and I finally solve the problem with this modifies class

class HttpClient:
    """HTTP Client to make JSON RPC requests to Tryton server.
    User is logged in when an object is created.
    """

    def __init__(self, url, database_name, user, passwd):
        self._url = '{}/{}/'.format(url, database_name)
        self._user = user
        self._passwd = passwd
        self._login()
        self._id = 0

    def get_id(self):
        self._id += 1
        return self._id

    def _login(self):
        """
        Returns list, where
        0 - user id
        1 - session token
        """
        payload = json.dumps({
            'params': [self._user, {'password': self._passwd}],
            'jsonrpc': "2.0",
            'method': 'common.db.login',
            'id': 1,
        })
        headers = {'content-type': 'application/json'}
        result = requests.post(self._url,
                               data=payload,
                               headers=headers)
        if result.status_code in [500, 401]:
            raise Exception(result.text)

        if 'json' in result:
            self._session = result.json()['result']
        else:
            self._session = json.loads(result.text)

        return self._session

    def call(self, prefix, method, params=[[], {}, {}]):
        """RPC Call
        """
        method = '{}.{}'.format(prefix, method)
        payload = json.dumps({
            'params': params,
            'method': method,
            'id': self.get_id(),
         })
        auth = "%s:%s:%s" % (self._user, self._session[0], self._session[1])
        authorization = base64.b64encode(auth.encode('utf-8'))
        headers = {
        'Content-Type': 'application/json',
        'Authorization': b'Session ' + authorization
        }

        response = requests.post(self._url,
                                 data=payload,
                                 headers=headers)
        if response.status_code in [500, 401]:
            raise Exception(response.text)
        return response.json()

    def model(self, model, method, args=[], kwargs={}):
        return self.call('model.%s' % model, method, (args, kwargs, {}))

    def system(self, method):
        return self.call('system', method, params=[])

the key point is the call that must be done with the context in order to be executed in the right way !!

    def model(self, model, method, args=[], kwargs={}):
        return self.call('model.%s' % model, method, (args, kwargs, {}))

hope it helps
regards