问:
Selecting row with multiple parameters (ajax and PHP)
Good Day,
I'm new to PHP/MySQL and I try to send a request from ajax and select a row in a database with multiple parameters.
Is this the good way to do that ?

AJAX (Jquery):

```<code>function readLine(name, firstname) {
$.ajax({
        type: "post",
        url: "./php/readLine.php",
        dataType: 'json',
        data: { name: name, firstname: firstname },
        success: function(data) {
         console.log(data);
        }
        error: function(data) {
         console.log("An error occured!");
        }
});
}
</code>```

PHP:

```<code><?php
$sql = "SELECT * FROM table1 WHERE firstname=".intval($_POST['firstname'])." AND name=".intval($_POST['name']);
$con = mysqli_connect("localhost", "root", "", "myDB");
if (!$con) {
  die("Connection failed: " . mysqli_error($con));
}
$result = mysqli_query($con, $sql);
$to_encode = array();
while($row = mysqli_fetch_array($result, MYSQLI_NUM)){
  $to_encode[] = $row;
}
echo json_encode($to_encode);
mysqli_close($con);
?>
</code>```

Thanks for your help.

答:
Firstly, you should use prepared statements instead, as currently the code is susceptible to SQL Injection attacks. I cannot emphasise this enough, an attacker would be able to wreak havoc on your database with the code you currently have.

You should use something like the following (taken from the page linked above, and this comment on the same page). Note that I have removed the intval calls to your POSTed data, as I assume they are strings rather than integers.

```<code>$to_encode = array();
$mysqli = new mysqli("localhost", "root", "password", "myDB");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT * FROM table1 WHERE firstname=? AND name=?")) {

    /* bind parameters for markers */
    $stmt->bind_param("ss", $_POST['firstname'], $_POST['name']);

    /* execute query */
    $stmt->execute();

    /* instead of bind_result: */
    $result = $stmt->get_result();

    /* now you can fetch the results into an array - NICE */
    while ($myrow = $result->fetch_assoc()) {

        // use your $myrow array as you would with any other fetch
        $to_encode[] = $myrow;

    }

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();

echo json_encode($to_encode);
</code>```

Body:
Good Day,
I'm new to PHP/MySQL and I try to send a request from ajax and select a row in a database with multiple parameters.
Is this the good way to do that ?

AJAX (Jquery):

function readLine(name, firstname) {
$.ajax({
        type: "post",
        url: "./php/readLine.php",
        dataType: 'json',
        data: { name: name, firstname: firstname },
        success: function(data) {
         console.log(data);
        }
        error: function(data) {
         console.log("An error occured!");
        }
});
}

PHP:

<?php
$sql = "SELECT * FROM table1 WHERE firstname=".intval($_POST['firstname'])." AND name=".intval($_POST['name']);
$con = mysqli_connect("localhost", "root", "", "myDB");
if (!$con) {
  die("Connection failed: " . mysqli_error($con));
}
$result = mysqli_query($con, $sql);
$to_encode = array();
while($row = mysqli_fetch_array($result, MYSQLI_NUM)){
  $to_encode[] = $row;
}
echo json_encode($to_encode);
mysqli_close($con);
?>

Thanks for your help.

Body:
Firstly, you should use prepared statements instead, as currently the code is susceptible to SQL Injection attacks. I cannot emphasise this enough, an attacker would be able to wreak havoc on your database with the code you currently have.

You should use something like the following (taken from the page linked above, and this comment on the same page). Note that I have removed the intval calls to your POSTed data, as I assume they are strings rather than integers.

$to_encode = array();
$mysqli = new mysqli("localhost", "root", "password", "myDB");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT * FROM table1 WHERE firstname=? AND name=?")) {

    /* bind parameters for markers */
    $stmt->bind_param("ss", $_POST['firstname'], $_POST['name']);

    /* execute query */
    $stmt->execute();

    /* instead of bind_result: */
    $result = $stmt->get_result();

    /* now you can fetch the results into an array - NICE */
    while ($myrow = $result->fetch_assoc()) {

        // use your $myrow array as you would with any other fetch
        $to_encode[] = $myrow;

    }

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();

echo json_encode($to_encode);


来源: stackexchange

答:
You can do it using PDO with prepared statements, that'll make sure the user input is made safe. Like this:

```<code>try {
    $db = new PDO('mysql:dbname=db_name;host=localhost', 'db_user', 'db_password');
} catch (PDOException $e) {
    die('Connection failed: ' . $e->getMessage());
}

$sql = "SELECT * FROM table1 WHERE firstname=:firstname AND name=:name";
$stmt = $db->prepare($sql);
$stmt->bindParam(':firstname', $_POST['firstname'], PDO::PARAM_STRING);
$stmt->bindParam(':name', $_POST['name'], PDO::PARAM_STRING);
$stmt->execute();
$result = $stmt->fetchAll();

echo json_encode($result);
</code>```

Move the first 5 lines into an include, then you only need this code once.

ContentLicense: CC BY-SA 3.0

Title: Selecting row with multiple parameters (ajax and PHP)

Body:
You can do it using PDO with prepared statements, that'll make sure the user input is made safe. Like this:

try {
    $db = new PDO('mysql:dbname=db_name;host=localhost', 'db_user', 'db_password');
} catch (PDOException $e) {
    die('Connection failed: ' . $e->getMessage());
}

$sql = "SELECT * FROM table1 WHERE firstname=:firstname AND name=:name";
$stmt = $db->prepare($sql);
$stmt->bindParam(':firstname', $_POST['firstname'], PDO::PARAM_STRING);
$stmt->bindParam(':name', $_POST['name'], PDO::PARAM_STRING);
$stmt->execute();
$result = $stmt->fetchAll();

echo json_encode($result);

Move the first 5 lines into an include, then you only need this code once.


问:
Missing dependency for method public javax.ws.rs.core.Response (Upload File JAX-RS)
I found an error when create method POST for upload file function. how to solve this problem? Thanks.

this log error:

Jul 05, 2017 4:20:23 PM org.apache.coyote.AbstractProtocol init INFO:
  Initializing ProtocolHandler ["http-bio-8087"] Jul 05, 2017 4:20:23 PM
  org.apache.catalina.core.StandardService startInternal INFO: Starting
  service Tomcat Jul 05, 2017 4:20:23 PM
  org.apache.catalina.core.StandardEngine startInternal INFO: Starting
  Servlet Engine: Apache Tomcat/7.0.47 Jul 05, 2017 4:20:27 PM
  com.sun.jersey.api.core.PackagesResourceConfig init INFO: Scanning for
  root resource and provider classes in the packages:

  org.arpit.java2blog.controller Jul 05, 2017 4:20:28 PM
  com.sun.jersey.api.core.ScanningResourceConfig logClasses INFO: Root
  resource classes found:   class
  org.arpit.java2blog.controller.FileUploadController   class
  org.arpit.java2blog.controller.CountryController   class
  org.arpit.java2blog.controller.KasusController Jul 05, 2017 4:20:28 PM
  com.sun.jersey.api.core.ScanningResourceConfig init INFO: No provider
  classes found. Jul 05, 2017 4:20:28 PM
  com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
  INFO: Initiating Jersey application, version 'Jersey: 1.19.3
  10/24/2016 03:43 PM' Jul 05, 2017 4:20:29 PM
  com.sun.jersey.spi.inject.Errors processErrorMessages SEVERE: The
  following errors and warnings have been detected with resource and/or
  provider classes:   SEVERE: Missing dependency for method public
  javax.ws.rs.core.Response
  org.arpit.java2blog.controller.FileUploadController.uploadFile(java.io.InputStream,org.glassfish.jersey.media.multipart.FormDataContentDisposition)
  at parameter at index 0   SEVERE: Missing dependency for method public
  javax.ws.rs.core.Response
  org.arpit.java2blog.controller.FileUploadController.uploadFile(java.io.InputStream,org.glassfish.jersey.media.multipart.FormDataContentDisposition)
  at parameter at index 1   SEVERE: Method, public
  javax.ws.rs.core.Response
  org.arpit.java2blog.controller.FileUploadController.uploadFile(java.io.InputStream,org.glassfish.jersey.media.multipart.FormDataContentDisposition),
  annotated with POST of resource, class
  org.arpit.java2blog.controller.FileUploadController, is not recognized
  as valid resource method. Jul 05, 2017 4:20:29 PM
  org.apache.catalina.core.ApplicationContext log SEVERE:
  StandardWrapper.Throwable
  com.sun.jersey.spi.inject.Errors$ErrorMessagesException   at
  com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
    at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)    at
  com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199)
    at
  com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:795)
    at
  com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:790)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:509)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:339)
    at
  com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
    at
  com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:207)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:394)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:577)
    at javax.servlet.GenericServlet.init(GenericServlet.java:160)   at
  org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280)
    at
  org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193)
    at
  org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088)
    at
  org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5176)
    at
  org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5460)
    at
  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)     at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748)

Jul 05, 2017 4:20:29 PM org.apache.catalina.core.StandardContext
  loadOnStartup SEVERE: Servlet /JSONExampleJAXB threw load() exception
  com.sun.jersey.spi.inject.Errors$ErrorMessagesException   at
  com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
    at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)    at
  com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199)
    at
  com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:795)
    at
  com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:790)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:509)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:339)
    at
  com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
    at
  com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:207)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:394)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:577)
    at javax.servlet.GenericServlet.init(GenericServlet.java:160)   at
  org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280)
    at
  org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193)
    at
  org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088)
    at
  org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5176)
    at
  org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5460)
    at
  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)     at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748)

my pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.project</groupId>
    <artifactId>JSONExampleJAXB</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>JSONExampleJAXB Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <jersey.version>1.19.3</jersey.version>
        <java-version>1.8</java-version>
        <org.springframework-version>4.3.8.RELEASE</org.springframework-version>
        <jackson.version>2.7.5</jackson.version>
        <jaxb-api.version>2.2.11</jaxb-api.version>
        <hibernate.version>4.3.11.Final</hibernate.version>
        <slf4j.version>1.7.21</slf4j.version>
    </properties>

    <dependencies>
        <!-- Local Libraries -->
        <dependency>
            <groupId>com.sap.hana</groupId>
            <artifactId>ng</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${basedir}/src/main/webapp/WEB-INF/lib/ngdbc-1.0.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>2.1-m05</version>
            <scope>provided</scope>
        </dependency>

        <!-- Dependency untuk mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>

        <!-- JSON Dependency -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.2</version>
        </dependency>

        <!-- Jersey -->
        <dependency>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>jersey-multipart</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-servlet</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <!-- Mimepull untuk prerequisites upload file -->
        <dependency>
            <groupId>org.jvnet.mimepull</groupId>
            <artifactId>mimepull</artifactId>
            <version>1.9.4</version>
        </dependency>

        <!--  -->
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>2.2.1.GA</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxb-provider</artifactId>
            <version>2.2.0.GA</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jettison-provider</artifactId>
            <version>2.2.0.GA</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.persistence/persistence-api -->
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>2.10</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-multipart</artifactId>
            <version>2.10</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-jdk-http</artifactId>
            <version>2.10</version>
        </dependency>

    </dependencies>
    <build>
        <finalName>JSONExampleJAXB</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <port>8087</port>
                    <path>/JSONExampleJAXB</path>
                </configuration>
            </plugin>
        </plugins>

    </build>
</project>
</code>```

my web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>Archetype Created Web Application</display-name>
    <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>

        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>org.arpit.java2blog.controller</param-value>
        </init-param>

        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>

        <init-param>
            <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
            <param-value>org.arpit.java2blog.config.CORSFilter</param-value>
        </init-param>

        <init-param>
            <param-name>org.arpit.java2blog.controller.FileUploadController</param-name>
            <param-value>org.glassfish.jersey.filter.LoggingFilter;
             org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
        </init-param>

        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>
</code>```

FileUploadController.java

```<code>package org.arpit.java2blog.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;

@Path("/files")
public class FileUploadController {

    @POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(
            @FormDataParam("file") InputStream uploadedInputStream,
            @FormDataParam("file") FormDataContentDisposition fileDetail) {
            String fileLocation = "d://" + fileDetail.getFileName();
                    //saving file
            try {
                FileOutputStream out = new FileOutputStream(new File(fileLocation));
                int read = 0;
                byte[] bytes = new byte[1024];
                out = new FileOutputStream(new File(fileLocation));
                while ((read = uploadedInputStream.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }
                out.flush();
                out.close();
            } catch (IOException e) {e.printStackTrace();}
            String output = "File successfully uploaded to : " + fileLocation;
            return Response.status(200).entity(output).build();
        }

}
</code>```

答:
this is my new pom.xml:</p>

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.project</groupId>
    <artifactId>JSONExampleJAXB</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>JSONExampleJAXB Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <jersey.version>1.8</jersey.version>
        <java-version>1.8</java-version>
        <org.springframework-version>4.3.8.RELEASE</org.springframework-version>
        <jackson.version>2.7.5</jackson.version>
        <jaxb-api.version>2.2.11</jaxb-api.version>
        <hibernate.version>4.3.11.Final</hibernate.version>
        <slf4j.version>1.7.21</slf4j.version>
    </properties>

    <dependencies>
        <!-- Local Libraries -->
        <dependency>
            <groupId>com.sap.hana</groupId>
            <artifactId>ng</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${basedir}/src/main/webapp/WEB-INF/lib/ngdbc-1.0.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>2.1-m05</version>
            <scope>provided</scope>
        </dependency>

        <!-- Dependency untuk mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>

        <!-- JSON Dependency -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.2</version>
        </dependency>

        <!-- Jersey -->
        <dependency>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>jersey-multipart</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-servlet</artifactId>
            <version>1.19.3</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <!-- Mimepull untuk prerequisites upload file -->
        <dependency>
            <groupId>org.jvnet.mimepull</groupId>
            <artifactId>mimepull</artifactId>
            <version>1.9.4</version>
        </dependency>

        <!-- JBoss -->
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>2.2.1.GA</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxb-provider</artifactId>
            <version>2.2.0.GA</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jettison-provider</artifactId>
            <version>2.2.0.GA</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.persistence/persistence-api -->
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>2.10</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-multipart</artifactId>
            <version>2.10</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-jdk-http</artifactId>
            <version>2.10</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>2.6</version>
        </dependency>

    </dependencies>
    <build>
        <finalName>JSONExampleJAXB</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <port>8087</port>
                    <path>/JSONExampleJAXB</path>
                </configuration>
            </plugin>
        </plugins>

    </build>
</project>
</code>```

Body:
I found an error when create method POST for upload file function. how to solve this problem? Thanks.

this log error:

Jul 05, 2017 4:20:23 PM org.apache.coyote.AbstractProtocol init INFO:
  Initializing ProtocolHandler ["http-bio-8087"] Jul 05, 2017 4:20:23 PM
  org.apache.catalina.core.StandardService startInternal INFO: Starting
  service Tomcat Jul 05, 2017 4:20:23 PM
  org.apache.catalina.core.StandardEngine startInternal INFO: Starting
  Servlet Engine: Apache Tomcat/7.0.47 Jul 05, 2017 4:20:27 PM
  com.sun.jersey.api.core.PackagesResourceConfig init INFO: Scanning for
  root resource and provider classes in the packages:

  org.arpit.java2blog.controller Jul 05, 2017 4:20:28 PM
  com.sun.jersey.api.core.ScanningResourceConfig logClasses INFO: Root
  resource classes found:   class
  org.arpit.java2blog.controller.FileUploadController   class
  org.arpit.java2blog.controller.CountryController   class
  org.arpit.java2blog.controller.KasusController Jul 05, 2017 4:20:28 PM
  com.sun.jersey.api.core.ScanningResourceConfig init INFO: No provider
  classes found. Jul 05, 2017 4:20:28 PM
  com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
  INFO: Initiating Jersey application, version 'Jersey: 1.19.3
  10/24/2016 03:43 PM' Jul 05, 2017 4:20:29 PM
  com.sun.jersey.spi.inject.Errors processErrorMessages SEVERE: The
  following errors and warnings have been detected with resource and/or
  provider classes:   SEVERE: Missing dependency for method public
  javax.ws.rs.core.Response
  org.arpit.java2blog.controller.FileUploadController.uploadFile(java.io.InputStream,org.glassfish.jersey.media.multipart.FormDataContentDisposition)
  at parameter at index 0   SEVERE: Missing dependency for method public
  javax.ws.rs.core.Response
  org.arpit.java2blog.controller.FileUploadController.uploadFile(java.io.InputStream,org.glassfish.jersey.media.multipart.FormDataContentDisposition)
  at parameter at index 1   SEVERE: Method, public
  javax.ws.rs.core.Response
  org.arpit.java2blog.controller.FileUploadController.uploadFile(java.io.InputStream,org.glassfish.jersey.media.multipart.FormDataContentDisposition),
  annotated with POST of resource, class
  org.arpit.java2blog.controller.FileUploadController, is not recognized
  as valid resource method. Jul 05, 2017 4:20:29 PM
  org.apache.catalina.core.ApplicationContext log SEVERE:
  StandardWrapper.Throwable
  com.sun.jersey.spi.inject.Errors$ErrorMessagesException   at
  com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
    at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)    at
  com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199)
    at
  com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:795)
    at
  com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:790)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:509)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:339)
    at
  com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
    at
  com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:207)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:394)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:577)
    at javax.servlet.GenericServlet.init(GenericServlet.java:160)   at
  org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280)
    at
  org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193)
    at
  org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088)
    at
  org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5176)
    at
  org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5460)
    at
  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)     at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748)

Jul 05, 2017 4:20:29 PM org.apache.catalina.core.StandardContext
  loadOnStartup SEVERE: Servlet /JSONExampleJAXB threw load() exception
  com.sun.jersey.spi.inject.Errors$ErrorMessagesException   at
  com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
    at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)    at
  com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199)
    at
  com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:795)
    at
  com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:790)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:509)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:339)
    at
  com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
    at
  com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:207)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:394)
    at
  com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:577)
    at javax.servlet.GenericServlet.init(GenericServlet.java:160)   at
  org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280)
    at
  org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193)
    at
  org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088)
    at
  org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5176)
    at
  org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5460)
    at
  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)     at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748)

my pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.project</groupId>
    <artifactId>JSONExampleJAXB</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>JSONExampleJAXB Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <jersey.version>1.19.3</jersey.version>
        <java-version>1.8</java-version>
        <org.springframework-version>4.3.8.RELEASE</org.springframework-version>
        <jackson.version>2.7.5</jackson.version>
        <jaxb-api.version>2.2.11</jaxb-api.version>
        <hibernate.version>4.3.11.Final</hibernate.version>
        <slf4j.version>1.7.21</slf4j.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>com.sap.hana</groupId>
            <artifactId>ng</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${basedir}/src/main/webapp/WEB-INF/lib/ngdbc-1.0.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>2.1-m05</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>jersey-multipart</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-servlet</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>org.jvnet.mimepull</groupId>
            <artifactId>mimepull</artifactId>
            <version>1.9.4</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>2.2.1.GA</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxb-provider</artifactId>
            <version>2.2.0.GA</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jettison-provider</artifactId>
            <version>2.2.0.GA</version>
        </dependency>

        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>2.10</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-multipart</artifactId>
            <version>2.10</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-jdk-http</artifactId>
            <version>2.10</version>
        </dependency>

    </dependencies>
    <build>
        <finalName>JSONExampleJAXB</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <port>8087</port>
                    <path>/JSONExampleJAXB</path>
                </configuration>
            </plugin>
        </plugins>

    </build>
</project>

my web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>Archetype Created Web Application</display-name>
    <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>

        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>org.arpit.java2blog.controller</param-value>
        </init-param>

        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>

        <init-param>
            <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
            <param-value>org.arpit.java2blog.config.CORSFilter</param-value>
        </init-param>

        <init-param>
            <param-name>org.arpit.java2blog.controller.FileUploadController</param-name>
            <param-value>org.glassfish.jersey.filter.LoggingFilter;
             org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
        </init-param>

        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>

FileUploadController.java

package org.arpit.java2blog.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;

@Path("/files")
public class FileUploadController {

    @POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(
            @FormDataParam("file") InputStream uploadedInputStream,
            @FormDataParam("file") FormDataContentDisposition fileDetail) {
            String fileLocation = "d://" + fileDetail.getFileName();
                    //saving file
            try {
                FileOutputStream out = new FileOutputStream(new File(fileLocation));
                int read = 0;
                byte[] bytes = new byte[1024];
                out = new FileOutputStream(new File(fileLocation));
                while ((read = uploadedInputStream.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }
                out.flush();
                out.close();
            } catch (IOException e) {e.printStackTrace();}
            String output = "File successfully uploaded to : " + fileLocation;
            return Response.status(200).entity(output).build();
        }

}

Body:
this is my new pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.project</groupId>
    <artifactId>JSONExampleJAXB</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>JSONExampleJAXB Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <jersey.version>1.8</jersey.version>
        <java-version>1.8</java-version>
        <org.springframework-version>4.3.8.RELEASE</org.springframework-version>
        <jackson.version>2.7.5</jackson.version>
        <jaxb-api.version>2.2.11</jaxb-api.version>
        <hibernate.version>4.3.11.Final</hibernate.version>
        <slf4j.version>1.7.21</slf4j.version>
    </properties>

    <dependencies>
        <!-- Local Libraries -->
        <dependency>
            <groupId>com.sap.hana</groupId>
            <artifactId>ng</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${basedir}/src/main/webapp/WEB-INF/lib/ngdbc-1.0.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>2.1-m05</version>
            <scope>provided</scope>
        </dependency>

        <!-- Dependency untuk mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>

        <!-- JSON Dependency -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.2</version>
        </dependency>

        <!-- Jersey -->
        <dependency>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>jersey-multipart</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-servlet</artifactId>
            <version>1.19.3</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <!-- Mimepull untuk prerequisites upload file -->
        <dependency>
            <groupId>org.jvnet.mimepull</groupId>
            <artifactId>mimepull</artifactId>
            <version>1.9.4</version>
        </dependency>

        <!-- JBoss -->
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>2.2.1.GA</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxb-provider</artifactId>
            <version>2.2.0.GA</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jettison-provider</artifactId>
            <version>2.2.0.GA</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.persistence/persistence-api -->
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>2.10</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-multipart</artifactId>
            <version>2.10</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-jdk-http</artifactId>
            <version>2.10</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>2.6</version>
        </dependency>

    </dependencies>
    <build>
        <finalName>JSONExampleJAXB</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <port>8087</port>
                    <path>/JSONExampleJAXB</path>
                </configuration>
            </plugin>
        </plugins>

    </build>
</project>


问:
How do you store a list of directories into an array in Bash (and then print them out)?
I want to write a shell script to show a list of directories entered by a user and then for a user to select one of the directories with an index number based on how many directories there are

I'm thinking this is some kind of array operation, but im not sure how to do this in shell script

example:

```<code>> whichdir
There are 3 dirs in the current path
1 dir1
2 dir2
3 dir3
which dir do you want?
> 3
you selected dir3!
</code>```

答:
```<code>#! /bin/bash

declare -a dirs
i=1
for d in */
do
    dirs[i++]="${d%/}"
done
echo "There are ${#dirs[@]} dirs in the current path"
for((i=1;i<=${#dirs[@]};i++))
do
    echo $i "${dirs[i]}"
done
echo "which dir do you want?"
echo -n "> "
read i
echo "you selected ${dirs[$i]}"
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I want to write a shell script to show a list of directories entered by a user and then for a user to select one of the directories with an index number based on how many directories there are

I'm thinking this is some kind of array operation, but im not sure how to do this in shell script

example:

> whichdir
There are 3 dirs in the current path
1 dir1
2 dir2
3 dir3
which dir do you want?
> 3
you selected dir3!


问:
Random number generation in R with multiple conditions
I have this problem below to address. Your inputs/pointers are very much appreciated.Thanks in advance!

I have a data.table called Defect. And the first column is Length

```<code>Defect Table :

Length

6355
6236
1345
3123
</code>```

I want to add two more columns called DefectStarts and DefectEnds. I would like to use random function to determine where the defect starts and where it ends.

Basic criteria is as follows:

```<code> DefectStarts and DefectEnds <= Length

 DefectEnds > DefectStarts

 DefectEnds - DefectStarts <= Length
</code>```

Final data should something like this(values could be different as long as it satisfies above conditions)

```<code> Defect table:

Length     DefectStarts     DefectEnds

6355         1234             4356

6236         2000             4567

1345         500               689

3123         342               3120
</code>```

答:
After some messing around with the code, this seemed to do the job :

Defect <- Defect[,DefectStarts:=runif(row_count,min=1,max=Defect$Length)]

Defect <-
 Defect[,DefectEnds:=runif(row_count,min=Defect$DefectStarts,max=Defect$Length)]

Thanks again for your support! Much appreciated. And please do suggest if there are any better ways to do this.

Body:
I have this problem below to address. Your inputs/pointers are very much appreciated.Thanks in advance!

I have a data.table called Defect. And the first column is Length

Defect Table :

Length

6355
6236
1345
3123

I want to add two more columns called DefectStarts and DefectEnds. I would like to use random function to determine where the defect starts and where it ends.

Basic criteria is as follows:

 DefectStarts and DefectEnds <= Length

 DefectEnds > DefectStarts

 DefectEnds - DefectStarts <= Length

Final data should something like this(values could be different as long as it satisfies above conditions)

 Defect table:

Length     DefectStarts     DefectEnds

6355         1234             4356

6236         2000             4567

1345         500               689

3123         342               3120


问:
How can I get a parent object of a method?
If I have been passed a method as follows:

```<code>my_function(MyObject.method)
</code>```

Can I access MyObject from inside my_function, such that I can call MyObject.some_other_method()?

Please distinguish whether it's possible to do this on a class level and an instance level.

答:
I definitely wouldn't recommend doing this but after a little poking around, you can access the object a function is bound to:</p>

```<code>class C:
    def __init__(self, _id):
        self._id = _id
    def a(self):
        pass
    def b(self):
        print("b: {}".format(self._id))

c = C('test')

# you can access the object the function is bound to with __self__
c.a.__self__.b()

def my_function(fn):
    fn.__self__.b()

my_function(c.a)  #  "b: test"
</code>```

Body:
If I have been passed a method as follows:

my_function(MyObject.method)

Can I access MyObject from inside my_function, such that I can call MyObject.some_other_method()?

Please distinguish whether it's possible to do this on a class level and an instance level.

Body:
I definitely wouldn't recommend doing this but after a little poking around, you can access the object a function is bound to:

class C:
    def __init__(self, _id):
        self._id = _id
    def a(self):
        pass
    def b(self):
        print("b: {}".format(self._id))

c = C('test')

# you can access the object the function is bound to with __self__
c.a.__self__.b()

def my_function(fn):
    fn.__self__.b()

my_function(c.a)  #  "b: test"


问:
tel and mailto Links Stopped Working in cordova app
I developing hybrid mobile application with help of cordova.
I am using cordova version 7.0.1, tel & mailto links are not working in android app, below is the code.

```<code><a href="tel:+442079398514">+44 20 7939 8514</a>
<a href="mailto:gsc@travelsecurity.com">gsc@travelsecurity.com</a>
</code>```

for this have update following changes,
added inappbrowser plugin, updated config.xml,

```<code><access origin="*" />

<access launch-external="yes" origin="mailto:*" />

<access launch-external="yes" origin="tel:*" />
</code>```

Please check where I did wrong and let me know.

Thanks in advance!

答:
I ran into the same bug today.
Fixed it by sending the emails like this:</p>

```<code>window.open('mailto:john@doe.com?body=test", '_system');
</code>```

Body:
I developing hybrid mobile application with help of cordova.
I am using cordova version 7.0.1, tel & mailto links are not working in android app, below is the code.

+44 20 7939 8514
gsc@travelsecurity.com

for this have update following changes,
added inappbrowser plugin, updated config.xml,

<access origin="*" />

<access launch-external="yes" origin="mailto:*" />

<access launch-external="yes" origin="tel:*" />

Please check where I did wrong and let me know.

Thanks in advance!

Body:
I ran into the same bug today.
Fixed it by sending the emails like this:

window.open('mailto:john@doe.com?body=test", '_system');


问:
TuesPechkin adding Â in front of Currency £ Symbol
I have been using Tues Pechkin for html to PDF Conversion
 But there is one issue
 Tues Pechkin is adding by default Â this symbol in front of  £ Symbol

Example :- Â£85,000

```<code>var document = new HtmlToPdfDocument
            {
                GlobalSettings =
    {
        ProduceOutline = true,
        DocumentTitle = "TEST",
        PaperSize = PaperKind.A4, // Implicit conversion to PechkinPaperSize
        Margins =
        {
            All = 1.375,
            Unit = Unit.Centimeters
        }
}}
</code>```

Please help
Thanku.

答:
added a new Websettings

```<code>new ObjectSettings { HtmlText = strContent,
         WebSettings = new WebSettings
                        {
                            DefaultEncoding = "UTF-8",
                            LoadImages = true,
                            PrintBackground = true
                        }
                    }
</code>```

So that it can accept UTF-8 character ,And it is resolved. Thanku

Body:
I have been using Tues Pechkin for html to PDF Conversion
 But there is one issue
 Tues Pechkin is adding by default Â this symbol in front of  £ Symbol

Example :- Â£85,000

var document = new HtmlToPdfDocument
            {
                GlobalSettings =
    {
        ProduceOutline = true,
        DocumentTitle = "TEST",
        PaperSize = PaperKind.A4, // Implicit conversion to PechkinPaperSize
        Margins =
        {
            All = 1.375,
            Unit = Unit.Centimeters
        }
}}

Please help
Thanku.

Body:
added a new Websettings

new ObjectSettings { HtmlText = strContent,
         WebSettings = new WebSettings
                        {
                            DefaultEncoding = "UTF-8",
                            LoadImages = true,
                            PrintBackground = true
                        }
                    }

So that it can accept UTF-8 character ,And it is resolved. Thanku


问:
How to config Hidden Layers in DNNClassifier
Im new to Tensorflow&ML and following this example:
https://www.tensorflow.org/get_started/tflearn

It works very well until change hidden_units parameter here:

```<code>classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,
                                        hidden_units=[10, 20, 10],
                                        n_classes=3,
                                        model_dir="/tmp/iris_model")
</code>```

When i try anything, for example hidden_units = [20, 40, 20] or hidden_units = [20] it throws an error.

I tried to find out on my own but unsuccessfully so far and thought someone here can help.
The question is how to chose a number of hidden layers for DNN Classifier and why two my examples above do not work?

Here is a full code:

```<code>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import urllib

import tensorflow as tf
import numpy as np

IRIS_TRAINING = "iris_training.csv"
IRIS_TRAINING_URL = "http://download.tensorflow.org/data/iris_training.csv"

IRIS_TEST = "iris_test.csv"
IRIS_TEST_URL = "http://download.tensorflow.org/data/iris_test.csv"

if not os.path.exists(IRIS_TRAINING):
  raw = urllib.request.urlopen(IRIS_TRAINING_URL).read()
  with open(IRIS_TRAINING,'wb') as f:
    f.write(raw)

if not os.path.exists(IRIS_TEST):
  raw = urllib.request.urlopen(IRIS_TEST_URL).read()
  with open(IRIS_TEST,'wb') as f:
    f.write(raw)

# Load datasets.
training_set = tf.contrib.learn.datasets.base.load_csv_with_header(
    filename=IRIS_TRAINING,
    target_dtype=np.int,
    features_dtype=np.float32)
test_set = tf.contrib.learn.datasets.base.load_csv_with_header(
    filename=IRIS_TEST,
    target_dtype=np.int,
    features_dtype=np.float32)

# Specify that all features have real-value data
feature_columns = [tf.contrib.layers.real_valued_column("", dimension=4)]

# Build 3 layer DNN with 10, 20, 10 units respectively.
classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,
                                            hidden_units=[10, 20, 10],
                                            n_classes=3,
                                            model_dir="/tmp/iris_model")
# Define the training inputs
def get_train_inputs():
  x = tf.constant(training_set.data)
  y = tf.constant(training_set.target)

  return x, y

# Fit model.
classifier.fit(input_fn=get_train_inputs, steps=2000)
# Define the test inputs
def get_test_inputs():
  x = tf.constant(test_set.data)
  y = tf.constant(test_set.target)

  return x, y

# Evaluate accuracy.
accuracy_score = classifier.evaluate(input_fn=get_test_inputs,
                                     steps=1)["accuracy"]

print("\nTest Accuracy: {0:f}\n".format(accuracy_score))
</code>```

答:
Found it,
if model_dir is not specified than moel works just fine with new hidden_units

Body:
Im new to Tensorflow&ML and following this example:
https://www.tensorflow.org/get_started/tflearn

It works very well until change hidden_units parameter here:

classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,
                                        hidden_units=[10, 20, 10],
                                        n_classes=3,
                                        model_dir="/tmp/iris_model")

When i try anything, for example hidden_units = [20, 40, 20] or hidden_units = [20] it throws an error.

I tried to find out on my own but unsuccessfully so far and thought someone here can help.
The question is how to chose a number of hidden layers for DNN Classifier and why two my examples above do not work?

Here is a full code:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import urllib

import tensorflow as tf
import numpy as np

IRIS_TRAINING = "iris_training.csv"
IRIS_TRAINING_URL = "http://download.tensorflow.org/data/iris_training.csv"

IRIS_TEST = "iris_test.csv"
IRIS_TEST_URL = "http://download.tensorflow.org/data/iris_test.csv"

if not os.path.exists(IRIS_TRAINING):
  raw = urllib.request.urlopen(IRIS_TRAINING_URL).read()
  with open(IRIS_TRAINING,'wb') as f:
    f.write(raw)

if not os.path.exists(IRIS_TEST):
  raw = urllib.request.urlopen(IRIS_TEST_URL).read()
  with open(IRIS_TEST,'wb') as f:
    f.write(raw)

# Load datasets.
training_set = tf.contrib.learn.datasets.base.load_csv_with_header(
    filename=IRIS_TRAINING,
    target_dtype=np.int,
    features_dtype=np.float32)
test_set = tf.contrib.learn.datasets.base.load_csv_with_header(
    filename=IRIS_TEST,
    target_dtype=np.int,
    features_dtype=np.float32)

# Specify that all features have real-value data
feature_columns = [tf.contrib.layers.real_valued_column("", dimension=4)]

# Build 3 layer DNN with 10, 20, 10 units respectively.
classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,
                                            hidden_units=[10, 20, 10],
                                            n_classes=3,
                                            model_dir="/tmp/iris_model")
# Define the training inputs
def get_train_inputs():
  x = tf.constant(training_set.data)
  y = tf.constant(training_set.target)

  return x, y

# Fit model.
classifier.fit(input_fn=get_train_inputs, steps=2000)
# Define the test inputs
def get_test_inputs():
  x = tf.constant(test_set.data)
  y = tf.constant(test_set.target)

  return x, y

# Evaluate accuracy.
accuracy_score = classifier.evaluate(input_fn=get_test_inputs,
                                     steps=1)["accuracy"]

print("\nTest Accuracy: {0:f}\n".format(accuracy_score))


问:
Normalize data range of "180 - 360" to the range "0 - 100" - jQuery/JS
I have a image that I am rotating, but it can only rotate between 180deg and 360deg. But I need the targetValue that is entered to be between 0 - 100.

So if you enter a targetValue of 20, it will then rotate the image 20% of the range 180deg - 360deg.

I have attached a snippet of the code that I have already -

Any help would be appreciated!

CODE -

var targetValue = 100; //CAN ONLY BE BETWEEN 0 & 100

console.log(targetValue);

function targetChange(){
    $('#target').css('transform', 'rotate(' + targetValue + 'deg' + ')');
    console.log('hello');
}
targetChange();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.target {
    position: absolute;
 width: 100%;
    height: 100%;
    z-index: 2;
    transform: rotate(180deg);
}</code>```

```

答:
This is as simple as

Take the input value (0-100)

Find the proportion of 180 degrees

Add that to 180 to give a value in the range 180-360

This is demonstrated below

$('#input').on("change", function(){
    var val = +$(this).val();
    var rotAmount = 180 + ((val/100) * 180)
    $('#output').val(rotAmount);
    $('#target').css('transform', 'rotate(' + rotAmount + 'deg' + ')');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.target {
    position: relative;
 width: 100%;
    height: 100%;
    z-index: 2;
    transform: rotate(180deg);
}</code>```

Enter value between 0-100 <input id="input" type="number" min="0" max="100">

Rotation: <input type="text" id="output">

```

Body:
I have a image that I am rotating, but it can only rotate between 180deg and 360deg. But I need the targetValue that is entered to be between 0 - 100.

So if you enter a targetValue of 20, it will then rotate the image 20% of the range 180deg - 360deg.

I have attached a snippet of the code that I have already -

Any help would be appreciated!

CODE -

var targetValue = 100; //CAN ONLY BE BETWEEN 0 & 100

console.log(targetValue);

function targetChange(){
    $('#target').css('transform', 'rotate(' + targetValue + 'deg' + ')');
    console.log('hello');
}
targetChange();

.target {
    position: absolute;
 width: 100%;
    height: 100%;
    z-index: 2;
    transform: rotate(180deg);
}

Body:
This is as simple as

Take the input value (0-100)

Find the proportion of 180 degrees

Add that to 180 to give a value in the range 180-360

This is demonstrated below

$('#input').on("change", function(){
    var val = +$(this).val();
    var rotAmount = 180 + ((val/100) * 180)
    $('#output').val(rotAmount);
    $('#target').css('transform', 'rotate(' + rotAmount + 'deg' + ')');
});

.target {
    position: relative;
 width: 100%;
    height: 100%;
    z-index: 2;
    transform: rotate(180deg);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter value between 0-100 <input id="input" type="number" min="0" max="100">
<br>
Rotation: <input type="text" id="output">
<hr>
<img class="target" id="target" src="http://i65.tinypic.com/oarptf.png">


问:
Deserialize Protobuf 3 bytearray in python
How to read Protobuf message through bytearray response as string?

I tried looking up Protobuf library.
https://developers.google.com/protocol-buffers/docs/reference/python/google.protobuf.message-pysrc#Message.MergeFrom

When I tried mergeFrom , mergeFromString to fetch response back.  I am getting below error.

TypeError: Parameter to MergeFrom() must be instance of same class: expected GetUpdateResponseMsg got bytes.

I tried ParseFromString api and got None response back.

I am trying to deserialize Protobuf back to human readable format.

Is there anything else I can try?

答:
You need to deserialize the response. Pass in the class/protobuf type along with message and you should get the response in the format..
Sample example would be:

```<code>from BusinessLayer.py.GetDealUpdateData_pb2 import GetDealUpdateResponseDM
from importlib import import_module
def deserialize(byte_message, proto_type):
    module_, class_ = proto_type.rsplit('.', 1)
    class_ = getattr(import_module(module_), class_)
    rv = class_()
    rv.ParseFromString(byte_message)
    return rv

print (deserialize(byte_message, 'BusinessLayer.py.GetDealUpdateData_pb2.GetDealUpdateResponseDM'))
</code>```

byte_message is message which you will get as response.

Let me know if you have any questions.

Body:
You need to deserialize the response. Pass in the class/protobuf type along with message and you should get the response in the format..
Sample example would be:

from BusinessLayer.py.GetDealUpdateData_pb2 import GetDealUpdateResponseDM
from importlib import import_module
def deserialize(byte_message, proto_type):
    module_, class_ = proto_type.rsplit('.', 1)
    class_ = getattr(import_module(module_), class_)
    rv = class_()
    rv.ParseFromString(byte_message)
    return rv

print (deserialize(byte_message, 'BusinessLayer.py.GetDealUpdateData_pb2.GetDealUpdateResponseDM'))

byte_message is message which you will get as response.

Let me know if you have any questions.


问:
Unable to run the session when trying to run ARKit Test
I'm trying to figure out how ARKit works. Therefore, I download a two different project from GitHub.

1-)https://github.com/brianadvent/Simple-ARKit-Game

2-)https://github.com/exyte/ARTetris

Both of them I'm getting " Unable to run the session, configuration is not supported on this device:
" error.
I'm running latest version of betas both in Xcode and iOS.

Edit: I have this code in Viewcontroller. Shouldn't It work?

```<code>private func getSessionConfiguration() -> ARSessionConfiguration {
    if ARWorldTrackingSessionConfiguration.isSupported {
        // Create a session configuration
        let configuration = ARWorldTrackingSessionConfiguration()
        configuration.planeDetection = .horizontal
        return configuration;
    } else {
        // Slightly less immersive AR experience due to lower end processor
        return ARSessionConfiguration()
    }
}
</code>```

答:
You have to change the Variable ARWorldTrackingSessionConfiguration which is set as configuration in both Projects to a normal ARSessionConfiguration. Consider, that if you are doing that, you can only get the Orientation of the device and not its Position in the real World! So it could might be, that the applications are not working proberly. You could also change to another Device, which supports the ARWorldTrackingSessionConfiguration then everything should be fine, but the iPhone 6 for example cant do that.

As karthik mentioned only  6s and 6s plus , 7 and 7s plus support the WorldTracking Configuration. It is also working on iPad (5th. Gen.) AFAIK.

Update:
I think the Problem is, that the iPhone 6 just has a A8 processor. The ARKit Module has an important notice which says:

Important
  ARKit requires an iOS device with an A9 or later processor.

To make your app available only on devices supporting ARKit, use the arkit key in the UIRequiredDeviceCapabilities section of your app's Info.plist. If augmented reality is a secondary feature of your app, use the
  isSupported
   property to determine whether the current device supports the session configuration you want to use.

If you look at the Simple-ARGame you can see, that the Touches will be listened but are computed extremely slow. I looked at an Technical Dokumentation of the iPhone 6 where it says, that it only has an A8 processor. So probably you have to test ARKit with another Device.

Body:
I'm trying to figure out how ARKit works. Therefore, I download a two different project from GitHub.

1-)https://github.com/brianadvent/Simple-ARKit-Game

2-)https://github.com/exyte/ARTetris

Both of them I'm getting " Unable to run the session, configuration is not supported on this device:
" error.
I'm running latest version of betas both in Xcode and iOS.

Edit: I have this code in Viewcontroller. Shouldn't It work?

private func getSessionConfiguration() -> ARSessionConfiguration {
    if ARWorldTrackingSessionConfiguration.isSupported {
        // Create a session configuration
        let configuration = ARWorldTrackingSessionConfiguration()
        configuration.planeDetection = .horizontal
        return configuration;
    } else {
        // Slightly less immersive AR experience due to lower end processor
        return ARSessionConfiguration()
    }
}


问:
Where I must put my jsp files in SpringBoot?
I am writting to you because I don't know where I must put my JSP files in a SpringBoot application..

A screen of my application's files

Thank you in advance for your response,
Noman.

PS: Sorry I can't say Hello at the beginning of my post, it is always deleted..

答:
You should put your files to src/main/resources/static (or src/main/resources/public or src/main/resources/resources). All those are registered by Spring Boot autoconfig.

Also you should add following property to application.properties

```<code>spring.mvc.view.suffix=.jsp
</code>```

Body:
You should put your files to src/main/resources/static (or src/main/resources/public or src/main/resources/resources). All those are registered by Spring Boot autoconfig.

Also you should add following property to application.properties

spring.mvc.view.suffix=.jsp


问:
Convert simple array into two-dimensional array (matrix)
Imagine I have an array:

```<code>A = Array(1, 2, 3, 4, 5, 6, 7, 8, 9);
</code>```

And I want it to convert into 2-dimensional array (matrix of N x M), for instance like this:

```<code>A = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9));
</code>```

Note, that rows and columns of the matrix is changeable.

答:
This code is generic no need to worry about size and array, works universally

```<code>  function TwoDimensional(arr, size)
    {
      var res = [];
      for(var i=0;i < arr.length;i = i+size)
      res.push(arr.slice(i,i+size));
      return res;
    }
</code>```

Defining empty array.

Iterate according to the size so we will get specified chunk.That's why I am  incrementing i with size, because size can be 2,3,4,5,6......

Here, first I am slicing from i to (i+size) and then I am pushing it to empty array res.

Return the two-dimensional array.

ContentLicense: CC BY-SA 4.0

Body:
Imagine I have an array:

A = Array(1, 2, 3, 4, 5, 6, 7, 8, 9);

And I want it to convert into 2-dimensional array (matrix of N x M), for instance like this:

A = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9));

Note, that rows and columns of the matrix is changeable.

Body:
This code is generic no need to worry about size and array, works universally

  function TwoDimensional(arr, size)
    {
      var res = [];
      for(var i=0;i < arr.length;i = i+size)
      res.push(arr.slice(i,i+size));
      return res;
    }

Defining empty array.

Iterate according to the size so we will get specified chunk.That's why I am  incrementing i with size, because size can be 2,3,4,5,6......

Here, first I am slicing from i to (i+size) and then I am pushing it to empty array res.

Return the two-dimensional array.


问:
Display polygon coordinates inserted from keyboard
```<code>#include <iostream>
using namespace std;

class Polygon {
  private:

     int nrVarfuri, x[10], y[10];

  public:
    Polygon(){}
    Polygon(const Polygon &p){}

    void show()
    {
        cout<<"Number of tips: "<<nrVarfuri<<endl;

        for(int i=1;i<=nrVarfuri;i++){
            cout<<"X ["<<i<<"]="<<x[i]<<endl;
            cout<<"Y ["<<i<<"]="<<y[i]<<endl;
        }
    };
    void setValues (int nrVal, int XO[], int YO[]){
        nrVarfuri = nrVal;
        for(int i=1;i<=nrVal;i++){
            x[i]=XO[i];
            y[i]=YO[i];
        }
    };
};

int main ()
{
    int poly,i,tips,j;
    int x[tips],y[tips];
    cout<<"Insert the number of polygons: "<<endl;cin>>poly;

    Polygon tabPoligon[poly];
    Polygon p;
    for(i=0;i<poly;i++){
       // cout<<"Insert the number of tips: "<<endl; cin>>tips;
        cout<<"Numarul de varfuri: "<<endl; cin>>tips;
        for(j=1;j<=tips;j++)
        {
            cout<<"X["<<j<<"]:";cin>>x[j];
            cout<<"Y["<<j<<"]:";cin>>y[j];
        }
        p.setValues(tips,x,y);
        tabPoligon[i]=p;

    for(int i=0;i<poly;i++){
     cout<<"\n\nThe polygon have the folowing coordinates: "<<endl;

    }
     tabPoligon[i].show();

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

I have to insert the number of figures, insert the coordinates from keyboard and print them. The program is showing the coordinates after reading them from keyboard and is not waiting to insert the another polygon coordinates, what is the issue?

答:
You have numerous problems in your code. The 2 majors are:

Variable length arrays are not allowed in C++: int x[tips],y[tips]; is likely to initialize an array of size 1 or 0, same for Polygon tabPoligon[poly];

indexes run from 0 in C++ : for(j=1;j<=tips;j++) should be for(j=0;j<tips;j++) (in many places)

This 2 problems are enough to write past the actual end of your arrays invoking Undefined Behaviour.

Once this is fixed, you will just have to close the first for(i=0...) loop used to load the data before opening the showing one as suggested by alexeykuzmin0 in its comment.

For the arrays, a quick fix would be to use const dimension as you do in your class: int x[10], y[10]. For the tabPolygon array, you could use dynamic allocation:

```<code>Polygon *tabPoligon = new Polygon[poly];
</code>```

and do not forget to free it before return with delete[] tabPoligon;

But the C++ way would be to use a std::vector here.

Body:
#include <iostream>
using namespace std;

class Polygon {
  private:

     int nrVarfuri, x[10], y[10];

  public:
    Polygon(){}
    Polygon(const Polygon &p){}

    void show()
    {
        cout<<"Number of tips: "<<nrVarfuri<<endl;

        for(int i=1;i<=nrVarfuri;i++){
            cout<<"X ["<<i<<"]="<<x[i]<<endl;
            cout<<"Y ["<<i<<"]="<<y[i]<<endl;
        }
    };
    void setValues (int nrVal, int XO[], int YO[]){
        nrVarfuri = nrVal;
        for(int i=1;i<=nrVal;i++){
            x[i]=XO[i];
            y[i]=YO[i];
        }
    };
};

int main ()
{
    int poly,i,tips,j;
    int x[tips],y[tips];
    cout<<"Insert the number of polygons: "<<endl;cin>>poly;

    Polygon tabPoligon[poly];
    Polygon p;
    for(i=0;i<poly;i++){
       // cout<<"Insert the number of tips: "<<endl; cin>>tips;
        cout<<"Numarul de varfuri: "<<endl; cin>>tips;
        for(j=1;j<=tips;j++)
        {
            cout<<"X["<<j<<"]:";cin>>x[j];
            cout<<"Y["<<j<<"]:";cin>>y[j];
        }
        p.setValues(tips,x,y);
        tabPoligon[i]=p;

    for(int i=0;i<poly;i++){
     cout<<"\n\nThe polygon have the folowing coordinates: "<<endl;

    }
     tabPoligon[i].show();

  }
  return 0;
}

I have to insert the number of figures, insert the coordinates from keyboard and print them. The program is showing the coordinates after reading them from keyboard and is not waiting to insert the another polygon coordinates, what is the issue?

Body:
You have numerous problems in your code. The 2 majors are:

Variable length arrays are not allowed in C++: int x[tips],y[tips]; is likely to initialize an array of size 1 or 0, same for Polygon tabPoligon[poly];

indexes run from 0 in C++ : for(j=1;j<=tips;j++) should be for(j=0;j<tips;j++) (in many places)

This 2 problems are enough to write past the actual end of your arrays invoking Undefined Behaviour.

Once this is fixed, you will just have to close the first for(i=0...) loop used to load the data before opening the showing one as suggested by alexeykuzmin0 in its comment.

For the arrays, a quick fix would be to use const dimension as you do in your class: int x[10], y[10]. For the tabPolygon array, you could use dynamic allocation:

Polygon *tabPoligon = new Polygon[poly];

and do not forget to free it before return with delete[] tabPoligon;

But the C++ way would be to use a std::vector here.


问:
Abstracting try/catch PHP - stripe error handling
I am handling errors from the Stripe API - everything works fine using the standard try/catch block provided in the Stripe docs:

```<code>try {

  // Use Stripe's library to make requests...

} catch(\Stripe\Error\Card $e) {

  //card errors

  $body = $e->getJsonBody();
  $err  = $body['error'];

  print('Status is:' . $e->getHttpStatus() . "\n");
  print('Type is:' . $err['type'] . "\n");
  print('Code is:' . $err['code'] . "\n");
  print('Param is:' . $err['param'] . "\n");
  print('Message is:' . $err['message'] . "\n");

} catch (\Stripe\Error\RateLimit $e) {
  // Too many requests made to the API too quickly
} catch (\Stripe\Error\InvalidRequest $e) {
  // Invalid parameters were supplied to Stripe's API
} catch (\Stripe\Error\Authentication $e) {
  // Authentication with Stripe's API failed
  // (maybe you changed API keys recently)
} catch (\Stripe\Error\ApiConnection $e) {
  // Network communication with Stripe failed
} catch (\Stripe\Error\Base $e) {
  // Display a very generic error to the user, and maybe send
  // yourself an email
} catch (Exception $e) {
  // Something else happened, completely unrelated to Stripe
}
</code>```

However, this is a lot of code and I find myself repeating it. I'm a bit stuck on how to neaten it up. Something like this would be ideal:

```<code>try {

  // Use Stripe's library to make requests...

} // catch all errors in one line
</code>```

答:
Have a function that handles it for you:

```<code>function makeStripeApiCall($method, $args) {
    try {
        // call method
    } catch (...) {
        // handle error type 1
    } catch (...) {
        // handle error type 2
    } ...
}
</code>```

Now:

How to pass the $method? There are several ways to do that; for example:

```<code>$method = 'charge';
$this->stripe->{$method}($args);
</code>```

```<code>$method = [$stripe, 'charge'];
call_user_func_array($method, $args);
</code>```

```<code>$method = function () use ($stripe, $args) { return $stripe->charge($args); };
$method();
</code>```

Choose what fits your situation best.

How to handle errors exactly?

You should catch the specific Stripe exceptions and convert them to your own internal exception types as appropriate. There are a few broad types of problems you'd want to handle differently:

bad requests, e.g. card declined: you want to catch those errors in the calling business logic code directly and do something based on the specific issue

service down, e.g. Stripe\Error\ApiConnection or rate throttling: you can't do much with those except try again later, you'll want to catch those errors somewhere higher up and present the user with a "sorry, try again later" message

bad configuration, e.g. Stripe\Error\Authentication: nothing much that can be done automatically, you can present the user with a 500 HTTP server error, ring the alarm bells and get a devop to fix the authentication keys

These are basically the kinds of exception types you want to define internally and then catch them as appropriate. E.g.:

```<code>...
catch (\Stripe\Error\ApiConnection $e) {
    trigger_error($e->getMessage(), E_USER_WARNING);
    throw new TransientError($e);
}
...
</code>```

After all this, you will have reduced API calls to something like this:

```<code>try {
    return makeStripeApiCall('charge', $args);
} catch (BadRequestError $e) {
    echo 'Card number invalid: ', $e->getMessage();
}
// don't catch other kinds of exception here,
// let a higher up caller worry about graver issues
</code>```

Body:
I am handling errors from the Stripe API - everything works fine using the standard try/catch block provided in the Stripe docs:

try {

  // Use Stripe's library to make requests...

} catch(\Stripe\Error\Card $e) {

  //card errors

  $body = $e->getJsonBody();
  $err  = $body['error'];

  print('Status is:' . $e->getHttpStatus() . "\n");
  print('Type is:' . $err['type'] . "\n");
  print('Code is:' . $err['code'] . "\n");
  print('Param is:' . $err['param'] . "\n");
  print('Message is:' . $err['message'] . "\n");

} catch (\Stripe\Error\RateLimit $e) {
  // Too many requests made to the API too quickly
} catch (\Stripe\Error\InvalidRequest $e) {
  // Invalid parameters were supplied to Stripe's API
} catch (\Stripe\Error\Authentication $e) {
  // Authentication with Stripe's API failed
  // (maybe you changed API keys recently)
} catch (\Stripe\Error\ApiConnection $e) {
  // Network communication with Stripe failed
} catch (\Stripe\Error\Base $e) {
  // Display a very generic error to the user, and maybe send
  // yourself an email
} catch (Exception $e) {
  // Something else happened, completely unrelated to Stripe
}

However, this is a lot of code and I find myself repeating it. I'm a bit stuck on how to neaten it up. Something like this would be ideal:

try {

  // Use Stripe's library to make requests...

} // catch all errors in one line

Body:
Have a function that handles it for you:

function makeStripeApiCall($method, $args) {
    try {
        // call method
    } catch (...) {
        // handle error type 1
    } catch (...) {
        // handle error type 2
    } ...
}

Now:

How to pass the $method? There are several ways to do that; for example:

$method = 'charge';
$this->stripe->{$method}($args);

$method = [$stripe, 'charge'];
call_user_func_array($method, $args);

$method = function () use ($stripe, $args) { return $stripe->charge($args); };
$method();

Choose what fits your situation best.

How to handle errors exactly?

You should catch the specific Stripe exceptions and convert them to your own internal exception types as appropriate. There are a few broad types of problems you'd want to handle differently:

bad requests, e.g. card declined: you want to catch those errors in the calling business logic code directly and do something based on the specific issue

service down, e.g. Stripe\Error\ApiConnection or rate throttling: you can't do much with those except try again later, you'll want to catch those errors somewhere higher up and present the user with a "sorry, try again later" message

bad configuration, e.g. Stripe\Error\Authentication: nothing much that can be done automatically, you can present the user with a 500 HTTP server error, ring the alarm bells and get a devop to fix the authentication keys

These are basically the kinds of exception types you want to define internally and then catch them as appropriate. E.g.:

...
catch (\Stripe\Error\ApiConnection $e) {
    trigger_error($e->getMessage(), E_USER_WARNING);
    throw new TransientError($e);
}
...

After all this, you will have reduced API calls to something like this:

try {
    return makeStripeApiCall('charge', $args);
} catch (BadRequestError $e) {
    echo 'Card number invalid: ', $e->getMessage();
}
// don't catch other kinds of exception here,
// let a higher up caller worry about graver issues


问:
How to covert string value to datetime
I have a csv file where the date is stored in mm/dd/yyyy format 8/18/2015  12:23:57 PM. When I import this file, it gets imported in string format.

How to convert this to datetime value after importing? I tried to convert while importing, but all the values were as NA.

答:
We can do this with POSIXct

```<code>as.POSIXct(str1, format = "%m/%d/%Y %I:%M:%S %p")
</code>```

data

```<code>str1 <- "8/18/2015 12:23:57 PM"
</code>```

Title: How to covert string value to datetime

Body:
We can do this with POSIXct

as.POSIXct(str1, format = "%m/%d/%Y %I:%M:%S %p")

data

str1 <- "8/18/2015 12:23:57 PM"


问:
java 8 parallel stream, blockingcode possible?
My situation is quite simple.

I have a list I want to perform logic on each item asynchronically.

when all the threads are done, i want to call a close connection.

like so:

```<code>bucketsList.parallelStream().forEach(t -> {
//some logic
});
 try {
 RestApi.getInstance().closeClientConnection();
 } catch (IOException e) {
     e.printStackTrace();
 }
</code>```

is there a way to make the closeConnection part wait for the parallel Stream to finish going through all of its objects?

EDIT:
I cannot use CountDownLatch as i dont know how many items i will have in bucketsList

答:
An operation on a ParallelStream is still blocking and will wait for all the threads it spawned to finish. These threads are executed asynchronously (they don't wait for a previous one to finish), but that doesn't mean your whole code  starts behaving asynchronously !

If you're actually making asynchronous calls and working on the resulting CompletableFuture<T> in your forEach, you should instead make your terminal operation a reduce producing a single CompletableFuture<T>. Intermediate operations could be a peek or an identity map with side-effects (both are frowned upon, but I don't know any best-practice solution). You would close the connection upon resolve of the single resulting CompletableFuture<T>.

If you're not, then your code looks good enough, as the closeClientConnection() will only be executed once the ParallelStream has been processed.

Body:
My situation is quite simple.

I have a list I want to perform logic on each item asynchronically.

when all the threads are done, i want to call a close connection.

like so:

bucketsList.parallelStream().forEach(t -> {
//some logic
});
 try {
 RestApi.getInstance().closeClientConnection();
 } catch (IOException e) {
     e.printStackTrace();
 }

is there a way to make the closeConnection part wait for the parallel Stream to finish going through all of its objects?

EDIT:
I cannot use CountDownLatch as i dont know how many items i will have in bucketsList


问:
Flowplayer pauses at different times with cuepoint
Good morning. I have a Flowplayer video with cuepoints ex [5, 10]. Here, my video starts from 5th second and pauses at 10th second. So it works. However, video sometimes pauses at 9th second and sometimes on 10th second. So it looks like a flowplayer bug.

I'd appreciate a hint or solution, how I can make the video always pause at exact time everytime.

here is the code snippet

```<code>flowplayer(flowplayerObject, {
        hlsjs: {
          xhrSetup: function (xhr) {
            xhr.withCredentials = true;
          }
        },
        swf: ------,
        swfHls: -------,
        clip: {
          cuepoints:[videoStartTime,videoEndTime],
          sources: [
            {type: "application/x-mpegURL", src: -------l},
            {type: "video/mp4", src: -------}
          ]
        }
      }).one("ready", function (e, api, video){
        api.seek(parseInt(videoStartTime));
      }).on("cuepoint", function (e, api, cuepoint) {
         if (cuepoint.index === 1) {
          api.pause();
        };
      }) ;
</code>```

Thank you

答:
Thanks for your answer ami91. This is what I got from flowplayer devevelopers:

There's a limit to the granularity of the progress event (for memory reasons) of 250ms which triggers the cuepoint events.
The video you are using has a frame rate of 25 fps, so a cuepoint of 7.0s sits exactly on the frame boarder, and may therefore be trigger too early if the progress event triggering the cuepoint is below 125ms before 7.0.
Setting the cuepoint a tiny bit later should have the desired effect.
You won't get total precision because firing an event every 0.04 sec – or even more

So, I just added 0.5 sec to the end of the video.

Body:
Good morning. I have a Flowplayer video with cuepoints ex [5, 10]. Here, my video starts from 5th second and pauses at 10th second. So it works. However, video sometimes pauses at 9th second and sometimes on 10th second. So it looks like a flowplayer bug.

I'd appreciate a hint or solution, how I can make the video always pause at exact time everytime.

here is the code snippet

flowplayer(flowplayerObject, {
        hlsjs: {
          xhrSetup: function (xhr) {
            xhr.withCredentials = true;
          }
        },
        swf: ------,
        swfHls: -------,
        clip: {
          cuepoints:[videoStartTime,videoEndTime],
          sources: [
            {type: "application/x-mpegURL", src: -------l},
            {type: "video/mp4", src: -------}
          ]
        }
      }).one("ready", function (e, api, video){
        api.seek(parseInt(videoStartTime));
      }).on("cuepoint", function (e, api, cuepoint) {
         if (cuepoint.index === 1) {
          api.pause();
        };
      }) ;

Thank you


问:
Add custom html after the last child of my list using javascript
I'm trying to use javascript to add a custom div after my last child of a unordered list, the result should basically look like this.

```<code><ul class="mylist">
 <li> content </li>
 <li> content </li>
 <li> content </li>
 <li> content </li>
 <div>custom div</div>
<ul>
</code>```

I am getting this far, but don't know if it's close to be the right solution.
I cant get it to work

```<code>$( document ).ready(function() {
document.getElementByClassName("myList").lastChild.innerHTML = "<h1>test</h1>";
}
</code>```

答:
a div as a child of ul is not valid in html for you to insert the div you need to first add list then have the div inside of the list something like this

```<code><ul class="mylist">
 <li> content </li>
 <li> content </li>
 <li> content </li>
 <li> content </li>
 <li>
     <div>custom div</div>
</li>
<ul>
</code>```

since yyour list child is a list then you script that could either append hence replacing
custom div
 with
test
 should be something like this since we are appending inside of the last li tag

```<code>$( document ).ready(function() {
document.getElementByClassName("myList")
 .lastChild.innerHTML = "<h1>test</h1>";
}
</code>```

that way your markup is valid and and test is rendered on browser

Body:
I'm trying to use javascript to add a custom div after my last child of a unordered list, the result should basically look like this.

 content

 content

 content

 content

custom div

I am getting this far, but don't know if it's close to be the right solution.
I cant get it to work

$( document ).ready(function() {
document.getElementByClassName("myList").lastChild.innerHTML = "
test
";
}

Body:
a div as a child of ul is not valid in html for you to insert the div you need to first add list then have the div inside of the list something like this

<ul class="mylist">
 <li> content </li>
 <li> content </li>
 <li> content </li>
 <li> content </li>
 <li>
     <div>custom div</div>
</li>
<ul>

since yyour list child is a list then you script that could either append hence replacing <div>custom div</div> with <h1>test</h1> should be something like this since we are appending inside of the last li tag

$( document ).ready(function() {
document.getElementByClassName("myList")
 .lastChild.innerHTML = "<h1>test</h1>";
}

that way your markup is valid and and test is rendered on browser


问:
Google Places API: Text Search does not return rating field in results anymore
A few days ago I ran the following query: https://maps.googleapis.com/maps/api/place/textsearch/json?query=amusement+parks+in+delhi&key=API_KEY.

This returned some results which I could then display in a list view.
But, today when I ran the program again, I noticed that the rating field in the response was missing. Due to this the ratings in the list view was null for all list items. Few days ago the same had a numeric rating which was being displayed for every list item.

Unfortunately, I don't have the screenshots of the previous version's response and I wasn't aware that such a situation could arise. Currently, this is the response I get from text search.

Due to this, the resulting application.

So, is it possible that google changed their API responses somehow?

If so, shouldn't they notify the users?

Is there any way I can fix this, without using place details API call?

答: This appears to be currently a bug in the Places API: https://issuetracker.google.com/issues/62788930</p>