问:
Read JSON from Server (Java)
First of all, sorry for this silly question.

Can anyone help me out with the code about how to read this JSON file from server? I have messed up my java code after watching several tutorials.

```<code>[
  {
    "name": "Coleen Sanford",
    "location": {
      "latitude": -60.489023,
      "longitude": -32.311668
    }
  },
  {
    "name": "Bethany Church",
    "location": {
      "latitude": -1.304805,
      "longitude": -80.670287
    }
  },
  {
    "name": "Kristy Ware",
    "location": {
      "latitude": -46.443562,
      "longitude": -46.426997
    }
  },
  {
    "name": "Avery Navarro",
    "location": {
      "latitude": 35.719469,
      "longitude": -172.783006
    }
  },
  {
    "name": "Robyn Cruz",
    "location": null
  },
  {
    "name": "Vinson Hays",
    "location": null
  }
]
</code>```

This is my code:

```<code>/**
 * Async task class to get json by making HTTP call
 */
private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray  contacts = new JSONArray (jsonStr);

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    String name = c.getString("name");

                    // Phone node is JSON Object
                    JSONObject phone = c.getJSONObject("location");
                    String latitude = phone.getString("latitude");
                    String longitude = phone.getString("longitude");

                    // tmp hash map for single contact
                    HashMap<String, String> contact = new HashMap<>();

                    // adding each child node to HashMap key => value
                    contact.put("name", name);
                    contact.put("latitude", latitude);
                    contact.put("longitude", longitude);

                    // adding contact to contact list
                    contactList.add(contact);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                MainActivity.this, contactList,
                R.layout.list_item, new String[]{"name", "latitude",
                "longitude"}, new int[]{R.id.name,
                R.id.latitude, R.id.longitude});

        lv.setAdapter(adapter);
    }

}}
</code>```

答:
Try this
You should get contact array correctly and also Latitude and Longitude which is a double type</p>

```<code> if (jsonStr != null) {
        try {
            JSONObject jsonObj = new JSONObject(jsonStr);
            // Getting JSON Array node
            JSONArray contacts = new JSONArray ();
            contacts=jsonObj.getJSONArray("keyforarray")
            // looping through All Contacts
            for (int i = 0; i < contacts.length(); i++) {
                JSONObject c = contacts.getJSONObject(i);
                String name = c.getString("name");
                // Phone node is JSON Object
                JSONObject phone = c.getJSONObject("location");
                double latitude = phone.getDouble("latitude");
                double longitude = phone.getDouble("longitude");
                // tmp hash map for single contact
                HashMap<String, String> contact = new HashMap<>();
                // adding each child node to HashMap key => value
                contact.put("name", name);
                contact.put("latitude", String.valueOf(latitude));
                contact.put("longitude", String.valueOf(longitude));
                // adding contact to contact list
                contactList.add(contact);
            }
        } catch (final JSONException e) {
            Log.e(TAG, "Json parsing error: " + e.getMessage());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Json parsing error: " + e.getMessage(),
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }
    }
</code>```

Title: Read JSON from Server (Java)

Body:
First of all, sorry for this silly question.

Can anyone help me out with the code about how to read this JSON file from server? I have messed up my java code after watching several tutorials.

[
  {
    "name": "Coleen Sanford",
    "location": {
      "latitude": -60.489023,
      "longitude": -32.311668
    }
  },
  {
    "name": "Bethany Church",
    "location": {
      "latitude": -1.304805,
      "longitude": -80.670287
    }
  },
  {
    "name": "Kristy Ware",
    "location": {
      "latitude": -46.443562,
      "longitude": -46.426997
    }
  },
  {
    "name": "Avery Navarro",
    "location": {
      "latitude": 35.719469,
      "longitude": -172.783006
    }
  },
  {
    "name": "Robyn Cruz",
    "location": null
  },
  {
    "name": "Vinson Hays",
    "location": null
  }
]

This is my code:

/**
 * Async task class to get json by making HTTP call
 */
private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray  contacts = new JSONArray (jsonStr);

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    String name = c.getString("name");

                    // Phone node is JSON Object
                    JSONObject phone = c.getJSONObject("location");
                    String latitude = phone.getString("latitude");
                    String longitude = phone.getString("longitude");

                    // tmp hash map for single contact
                    HashMap<String, String> contact = new HashMap<>();

                    // adding each child node to HashMap key => value
                    contact.put("name", name);
                    contact.put("latitude", latitude);
                    contact.put("longitude", longitude);

                    // adding contact to contact list
                    contactList.add(contact);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                MainActivity.this, contactList,
                R.layout.list_item, new String[]{"name", "latitude",
                "longitude"}, new int[]{R.id.name,
                R.id.latitude, R.id.longitude});

        lv.setAdapter(adapter);
    }

}}

Body:
Try this
You should get contact array correctly and also Latitude and Longitude which is a double type

 if (jsonStr != null) {
        try {
            JSONObject jsonObj = new JSONObject(jsonStr);
            // Getting JSON Array node
            JSONArray contacts = new JSONArray ();
            contacts=jsonObj.getJSONArray("keyforarray")
            // looping through All Contacts
            for (int i = 0; i < contacts.length(); i++) {
                JSONObject c = contacts.getJSONObject(i);
                String name = c.getString("name");
                // Phone node is JSON Object
                JSONObject phone = c.getJSONObject("location");
                double latitude = phone.getDouble("latitude");
                double longitude = phone.getDouble("longitude");
                // tmp hash map for single contact
                HashMap<String, String> contact = new HashMap<>();
                // adding each child node to HashMap key => value
                contact.put("name", name);
                contact.put("latitude", String.valueOf(latitude));
                contact.put("longitude", String.valueOf(longitude));
                // adding contact to contact list
                contactList.add(contact);
            }
        } catch (final JSONException e) {
            Log.e(TAG, "Json parsing error: " + e.getMessage());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Json parsing error: " + e.getMessage(),
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }
    }


来源: stackexchange

问:
How to change button URL through JS?
I have been spending a lot of time researching how to change a button href dynamically in my website using JS.  I have a functioning Wordpress website, but would like to add some small additional functionality using JS to change a button's link based on a few user options.

I have researched this and found answers, but I absolutely cannot get the solutions to work on my site.

One of the simplest solutions that should work was found here:
  How to make option selection change button link?

I can't understand what is different between what I am trying to accomplish and what the accepted answer proposed.  I added window.onload() to prevent the JS from running before elements were loaded.

I am trying to do something similar with the following HTML & JS code:

HTML Code:

```<code><input type="hidden" id="input-book-type" value="GlassCrystal">

<br><br>

<select id="select-page-size">
<option value="6x6">6" x 6"</option>
<option value="10x10">10" x 10"</option>
</select>

<br><br>

<input id="input-project-title" value="Optional Project Title">

<br><br>

<a class="button" id="design-button" href="http://">Design Now</a>
</code>```

JS Code:

```<code>window.onload = function() {

document.getElementById("design-button").onclick = function() {
var booktype = document.getElementById("input-book-type");
var pagesize = document.getElementById("select-page-size");
var projtitle = document.getElementById("input-project-title");

this.href = "http://test/?sessionid=guest&ref="+booktype.value+pagesize.value+"&projectName="+projtitle.value+"/";
};

}
</code>```

JS Fiddle:
https://jsfiddle.net/w65c9x2d/

答:
I recommend using jQuery.

```<code>$("#submit").on('click', function(event) {
                event.preventDefault();
                data = $("#link").val();
                $("#frame").attr({
                    src: "http://"+data});
            });
</code>```

When the submit  button is clicked, it changed the iframe url which changed the content of the iframe automatically.

I don't really understand what you are trying to ask, but try to modfiy the code above :)

ContentLicense: CC BY-SA 3.0

Title: How to change button URL through JS?

Body:
I have been spending a lot of time researching how to change a button href dynamically in my website using JS.  I have a functioning Wordpress website, but would like to add some small additional functionality using JS to change a button's link based on a few user options.

I have researched this and found answers, but I absolutely cannot get the solutions to work on my site.

One of the simplest solutions that should work was found here:
  How to make option selection change button link?

I can't understand what is different between what I am trying to accomplish and what the accepted answer proposed.  I added window.onload() to prevent the JS from running before elements were loaded.

I am trying to do something similar with the following HTML & JS code:

HTML Code:

<input type="hidden" id="input-book-type" value="GlassCrystal">

<select id="select-page-size">
<option value="6x6">6" x 6"</option>
<option value="10x10">10" x 10"</option>
</select>

<input id="input-project-title" value="Optional Project Title">

Design Now

JS Code:

window.onload = function() {

document.getElementById("design-button").onclick = function() {
var booktype = document.getElementById("input-book-type");
var pagesize = document.getElementById("select-page-size");
var projtitle = document.getElementById("input-project-title");

this.href = "http://test/?sessionid=guest&ref="+booktype.value+pagesize.value+"&projectName="+projtitle.value+"/";
};

}

JS Fiddle:
https://jsfiddle.net/w65c9x2d/

Body:
I recommend using jQuery.

$("#submit").on('click', function(event) {
                event.preventDefault();
                data = $("#link").val();
                $("#frame").attr({
                    src: "http://"+data});
            });

When the submit  button is clicked, it changed the iframe url which changed the content of the iframe automatically.

I don't really understand what you are trying to ask, but try to modfiy the code above :)


问:
In MySQL queries, why use join instead of where?
It seems like to combine two or more tables, we can either use join or where. What are the advantages of one over the other?</p>

答:
Actually you often need both "WHERE" and "JOIN".

"JOIN" is used to retrieve data from two tables - based ON the values of a common column. If you then want to further filter this result, use the WHERE clause.

For example, "LEFT JOIN" retrieves ALL rows from the left table, plus the matching rows from the right table. But that does not filter the records on any specific value or on other columns that are not part of the JOIN. Thus, if you want to further filter this result, specify the extra filters in the WHERE clause.

ContentLicense: CC BY-SA 2.5


问:
Sorry, this action is not available in simulation
My test invocation name is "Mrs Tang", so i input "Talk to Mrs Tang", but it responds "Sorry, this action is not available in simulation"...

Does anybody know How can I resolve this error?

答: Make sure you are logged into the same account you used to deploy the test action and that the deployment has been done within the past half hour or so. If you have not set all the information on the Actions on Google Console, you may need to use the invocation phrase "Talk to my test app".</p>

ContentLicense: CC BY-SA 4.0


问:
Spring Cannot find class [org.hibernate.ejb.HibernatePersistence]
Im working on a java spring project on eclipse, and while Im trying to run the project through a JUnit test, I get and error : Cannot find class [org.hibernate.ejb.HibernatePersistence] . I looked for a lot of similar problems and no one could resolve mine. I build and rebuild the project properly but still the same problem.

First this my JUnit test :

```<code> @Test
public void test() {
    try {
        ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext(
                new String[] { "applicationContext.xml" });
        assertTrue(true);
    } catch (Exception e) {
        assertTrue(e.getMessage(), false);
    }

}
</code>```

This is the error :

```<code> org.springframework.context.support.ClassPathXmlApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Cannot find class [org.hibernate.ejb.HibernatePersistence]
</code>```

this is my persistence.xml file:

```<code> <?xml version="1.0" encoding="UTF-8"?>
 <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

<persistence-unit name="GK_SHOP" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
        <property name="hibernate.show_sql" value="true"/>
        <property name="hibernate.hbm2ddl.auto" value="update"/>
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>

    </properties>
</persistence-unit>
</code>```

and this is my spring configuration file :

```<code> <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
    http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

<bean id="datasource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    <property name="url" value="jdbc:mysql://localhost:3306/geek2geek"></property>
    <property name="username" value="aymane"></property>
    <property name="password" value="1234567890"></property>

</bean>

<bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="defaultDataSource" ref="datasource"></property>
<property name="persistenceXmlLocations">
<list>
<value>classpath*:META-INF/persistence.xml</value>
</list>
</property>
</bean>

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitManager" ref="persistenceUnitManager" />
    <property name="persistenceUnitName" value="GK_SHOP" />
</bean>

<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</code>```

and this is the maven pom.xml

```<code> <?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.aymane</groupId>
<artifactId>shop</artifactId>
<name>geekShop</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
    <java-version>1.6</java-version>
    <org.springframework-version>4.3.7.RELEASE</org.springframework-version>
    <org.aspectj-version>1.6.10</org.aspectj-version>
    <org.slf4j-version>1.7.25</org.slf4j-version>
</properties>
<dependencies>
    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${org.springframework-version}</version>
        <exclusions>
            <!-- Exclude Commons Logging in favor of SLF4j -->
            <exclusion>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.4.1.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.2.10.Final</version>
    </dependency>

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

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

    <!-- AspectJ -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>${org.aspectj-version}</version>
    </dependency>

    <!-- Logging -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>${org.slf4j-version}</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>${org.slf4j-version}</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>${org.slf4j-version}</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.15</version>
        <exclusions>
            <exclusion>
                <groupId>javax.mail</groupId>
                <artifactId>mail</artifactId>
            </exclusion>
            <exclusion>
                <groupId>javax.jms</groupId>
                <artifactId>jms</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.sun.jdmk</groupId>
                <artifactId>jmxtools</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.sun.jmx</groupId>
                <artifactId>jmxri</artifactId>
            </exclusion>
        </exclusions>
        <scope>runtime</scope>
    </dependency>

    <!-- @Inject -->
    <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
    </dependency>

    <!-- Servlet -->
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.1</version>
    </dependency>
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>taglibs</groupId>
        <artifactId>standard</artifactId>
        <version>1.1.2</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.1.2</version>
    </dependency>

    <!-- Test -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.7</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>4.3.8.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>4.3.8.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.3.8.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>4.3.8.RELEASE</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <artifactId>maven-eclipse-plugin</artifactId>
            <version>2.9</version>
            <configuration>
                <additionalProjectnatures>
                    <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                </additionalProjectnatures>
                <additionalBuildcommands>
                    <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                </additionalBuildcommands>
                <downloadSources>true</downloadSources>
                <downloadJavadocs>true</downloadJavadocs>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.5.1</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
                <compilerArgument>-Xlint:all</compilerArgument>
                <showWarnings>true</showWarnings>
                <showDeprecation>true</showDeprecation>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
                <mainClass>org.test.int1.Main</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

答:
You should use:

```<code>org.hibernate.jpa.HibernatePersistenceProvider
</code>```

instead of

```<code>org.hibernate.ejb.HibernatePersistence
</code>```

Body:
Im working on a java spring project on eclipse, and while Im trying to run the project through a JUnit test, I get and error : Cannot find class [org.hibernate.ejb.HibernatePersistence] . I looked for a lot of similar problems and no one could resolve mine. I build and rebuild the project properly but still the same problem.

First this my JUnit test :

 @Test
public void test() {
    try {
        ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext(
                new String[] { "applicationContext.xml" });
        assertTrue(true);
    } catch (Exception e) {
        assertTrue(e.getMessage(), false);
    }

}

This is the error :

 org.springframework.context.support.ClassPathXmlApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Cannot find class [org.hibernate.ejb.HibernatePersistence]

this is my persistence.xml file:

 <?xml version="1.0" encoding="UTF-8"?>
 <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

<persistence-unit name="GK_SHOP" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
        <property name="hibernate.show_sql" value="true"/>
        <property name="hibernate.hbm2ddl.auto" value="update"/>
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>

    </properties>
</persistence-unit>

and this is my spring configuration file :

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
    http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

<bean id="datasource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    <property name="url" value="jdbc:mysql://localhost:3306/geek2geek"></property>
    <property name="username" value="aymane"></property>
    <property name="password" value="1234567890"></property>

</bean>

<bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="defaultDataSource" ref="datasource"></property>
<property name="persistenceXmlLocations">
<list>
<value>classpath*:META-INF/persistence.xml</value>
</list>
</property>
</bean>

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitManager" ref="persistenceUnitManager" />
    <property name="persistenceUnitName" value="GK_SHOP" />
</bean>

<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>

and this is the maven pom.xml

 <?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.aymane</groupId>
<artifactId>shop</artifactId>
<name>geekShop</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
    <java-version>1.6</java-version>
    <org.springframework-version>4.3.7.RELEASE</org.springframework-version>
    <org.aspectj-version>1.6.10</org.aspectj-version>
    <org.slf4j-version>1.7.25</org.slf4j-version>
</properties>
<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${org.springframework-version}</version>
        <exclusions>

            <exclusion>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.4.1.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.2.10.Final</version>
    </dependency>

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

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

    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>${org.aspectj-version}</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>${org.slf4j-version}</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>${org.slf4j-version}</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>${org.slf4j-version}</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.15</version>
        <exclusions>
            <exclusion>
                <groupId>javax.mail</groupId>
                <artifactId>mail</artifactId>
            </exclusion>
            <exclusion>
                <groupId>javax.jms</groupId>
                <artifactId>jms</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.sun.jdmk</groupId>
                <artifactId>jmxtools</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.sun.jmx</groupId>
                <artifactId>jmxri</artifactId>
            </exclusion>
        </exclusions>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
    </dependency>

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

    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.1</version>
    </dependency>
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>taglibs</groupId>
        <artifactId>standard</artifactId>
        <version>1.1.2</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.1.2</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.7</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>4.3.8.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>4.3.8.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.3.8.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>4.3.8.RELEASE</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <artifactId>maven-eclipse-plugin</artifactId>
            <version>2.9</version>
            <configuration>
                <additionalProjectnatures>
                    <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                </additionalProjectnatures>
                <additionalBuildcommands>
                    <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                </additionalBuildcommands>
                <downloadSources>true</downloadSources>
                <downloadJavadocs>true</downloadJavadocs>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.5.1</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
                <compilerArgument>-Xlint:all</compilerArgument>
                <showWarnings>true</showWarnings>
                <showDeprecation>true</showDeprecation>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
                <mainClass>org.test.int1.Main</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build>

Body:
You should use:

org.hibernate.jpa.HibernatePersistenceProvider

instead of

org.hibernate.ejb.HibernatePersistence


问:
Kotlin with Android DataBinding in Android Studio 3.0 canary 2
my project have 2 modules which are app and apphelper as a library. I have been trying to use kotlin with android Databinding with it but I can't figure it out why it keep showing me these errors when I built project:

FAILURE: Build failed with an exception.

```<code>* What went wrong:
A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:stagingRuntimeClasspath'.
   > Unable to find a matching configuration in project :apphelper:
       - Configuration 'debugApiElements':
           - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'AndroidTypeAttr{name=Aar}' and found compatible value 'AndroidTypeAttr{name=Aar}'.
           - Required com.android.build.gradle.internal.dependency.BuildTypeAttr 'BuildTypeAttr{name=staging}' and found incompatible value 'BuildTypeAttr{name=debug}'.
           - Found com.android.build.gradle.internal.dependency.VariantAttr 'VariantAttr{name=debug}' but wasn't required.
           - Required org.gradle.api.attributes.Usage 'for runtime' and found incompatible value 'for compile'.
       - Configuration 'debugRuntimeElements':
           - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'AndroidTypeAttr{name=Aar}' and found compatible value 'AndroidTypeAttr{name=Aar}'.
           - Required com.android.build.gradle.internal.dependency.BuildTypeAttr 'BuildTypeAttr{name=staging}' and found incompatible value 'BuildTypeAttr{name=debug}'.
           - Found com.android.build.gradle.internal.dependency.VariantAttr 'VariantAttr{name=debug}' but wasn't required.
           - Required org.gradle.api.attributes.Usage 'for runtime' and found compatible value 'for runtime'.
       - Configuration 'releaseApiElements':
           - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'AndroidTypeAttr{name=Aar}' and found compatible value 'AndroidTypeAttr{name=Aar}'.
           - Required com.android.build.gradle.internal.dependency.BuildTypeAttr 'BuildTypeAttr{name=staging}' and found incompatible value 'BuildTypeAttr{name=release}'.
           - Found com.android.build.gradle.internal.dependency.VariantAttr 'VariantAttr{name=release}' but wasn't required.
           - Required org.gradle.api.attributes.Usage 'for runtime' and found incompatible value 'for compile'.
       - Configuration 'releaseRuntimeElements':
           - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'AndroidTypeAttr{name=Aar}' and found compatible value 'AndroidTypeAttr{name=Aar}'.
           - Required com.android.build.gradle.internal.dependency.BuildTypeAttr 'BuildTypeAttr{name=staging}' and found incompatible value 'BuildTypeAttr{name=release}'.
           - Found com.android.build.gradle.internal.dependency.VariantAttr 'VariantAttr{name=release}' but wasn't required.
           - Required org.gradle.api.attributes.Usage 'for runtime' and found compatible value 'for runtime'.
</code>```

The error log above is shown when I simply click on the build button and it is weirder if I click run button to install an app to a device which is like:

```<code>:app:transformDexArchiveWithDexMergerForDebug
AGPBI: {"kind":"error","text":"Error converting bytecode to dex:\nCause: com.android.dex.DexException: Multiple dex files define Lorg/intellij/lang/annotations/PrintFormatPattern;","sources":[{}],"original":"UNEXPECTED TOP-LEVEL EXCEPTION:\ncom.android.dex.DexException: Multiple dex files define Lorg/intellij/lang/annotations/PrintFormatPattern;\n","tool":"Dex"}
AGPBI: {"kind":"error","text":"com.android.dex.DexException: Multiple dex files define Lorg/intellij/lang/annotations/PrintFormatPattern;","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:608)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:563)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:545)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:167)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat com.android.dx.merge.DexMerger.merge(DexMerger.java:194)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat com.android.builder.dexing.DexArchiveMergerCallable.mergeDexes(DexArchiveMergerCallable.java:66)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:54)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:37)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat java.util.concurrent.ForkJoinTask$AdaptedCallable.exec(ForkJoinTask.java:1424)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)","sources":[{}]}

 FAILED
:app:buildInfoGeneratorDebug

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformDexArchiveWithDexMergerForDebug'.
> com.android.build.api.transform.TransformException: com.android.dex.DexException: Multiple dex files define Lorg/intellij/lang/annotations/PrintFormatPattern;

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED in 4s
74 actionable tasks: 7 executed, 67 avoided (91%)
</code>```

I downgrade kotlin version to be '1.1.2-2' to avoid the error and also added 'kotlin.incremental=false' to local.properties

Here are all my build.gradle files:

app Module:

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: 'test-environment.gradle'
apply plugin: 'io.fabric'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

repositories {
    maven { url 'https://maven.fabric.io/public' }
    maven { url "https://jitpack.io" }
    mavenCentral()
}

allprojects {
    repositories {
        jcenter()
        mavenCentral()
        maven { url 'https://maven.fabric.io/public' }

    }
}

android {
    compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION)
    buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION
    defaultConfig {
        applicationId "com.myapp.android"
        minSdkVersion Integer.parseInt(project.ANDROID_BUILD_MIN_SDK_VERSION)
        targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION)
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
        versionCode 1
        versionName "1.0"
    }

    dataBinding {
        enabled = true
    }

    dexOptions {
        jumboMode = true
    }

    if (System.getenv("CIRCLE")) {
        defaultConfig {
            versionCode Integer.parseInt(System.getenv("CIRCLE_BUILD_NUM"))
            versionName "1.0." + System.getenv("CIRCLE_BUILD_NUM")
        }
    } else {
        defaultConfig {
            versionCode 1
            versionName "1.0"
        }
    }

    signingConfigs {
        debug {
            storeFile file("../myappdebug.keystore")
            storePassword "myapprocks"
            keyAlias "myapp"
            keyPassword "myapprocks"
        }
        staging {
            storeFile file("../myapp_staging.keystore")
            storePassword "myapprocks"
            keyAlias "myapp"
            keyPassword "myapprocks"
        }

        release {
            storeFile rootProject.file('myapp.keystore')
            storePassword System.getenv("KEYSTORE_PASS")
            keyAlias System.getenv("ALIAS_NAME")
            keyPassword System.getenv("ALIAS_PASS")
        }
    }

    buildTypes {
        debug {
            ext.betaDistributionNotifications = false
            signingConfig signingConfigs.debug
            applicationIdSuffix ".dev"
            minifyEnabled false
            shrinkResources false
            proguardFile 'proguard-release.cfg'
            testProguardFile 'proguard-release.cfg'
            manifestPlaceholders = [providerSuffix: ".dev"]
        }
        staging {
            ext.betaDistributionEmailsFilePath = "staging_distribution_emails.txt"
            ext.betaDistributionReleaseNotesFilePath = "release_notes.txt"
            signingConfig signingConfigs.staging
            applicationIdSuffix ".staging"
            shrinkResources true
            minifyEnabled true
            proguardFile 'proguard-release.cfg'
            manifestPlaceholders = [providerSuffix: ".staging"]

        }

        release {
            signingConfig signingConfigs.release
            shrinkResources true
            minifyEnabled true
            proguardFile 'proguard-release.cfg'

        }
    }
}

kapt {
    generateStubs = true
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    api project(':apphelper')
    compile 'com.android.support:appcompat-v7:' + project.ANDROID_SUPPORT_LIBRARY_VERSION
    compile 'com.android.support:cardview-v7:' + project.ANDROID_SUPPORT_LIBRARY_VERSION
    compile 'com.android.support:design:' + project.ANDROID_SUPPORT_LIBRARY_VERSION
    compile 'com.android.support:support-v13:' + project.ANDROID_SUPPORT_LIBRARY_VERSION
    compile 'hanks.xyz:smallbang-library:0.1.2'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.facebook.device.yearclass:yearclass:1.0.1'
    compile 'com.facebook.android:facebook-android-sdk:4.+'
    compile group: 'com.google.code.gson', name: 'gson', version: '2.7'
    compile('com.crashlytics.sdk.android:crashlytics:2.6.2@aar') {
        transitive = true
    }
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    compile "android.arch.lifecycle:runtime:" + project.ANDROID_ARCH_VERSION
    compile "android.arch.lifecycle:extensions:" + project.ANDROID_ARCH_VERSION
    annotationProcessor "android.arch.lifecycle:compiler:" + project.ANDROID_ARCH_VERSION
    compile "android.arch.persistence.room:runtime:" + project.ANDROID_ARCH_VERSION
    annotationProcessor "android.arch.persistence.room:compiler:" + project.ANDROID_ARCH_VERSION
    kapt "com.android.databinding:compiler:$android_plugin_version"

}
</code>```

library module:

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

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION)
    buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION

    defaultConfig {
        minSdkVersion Integer.parseInt(project.ANDROID_BUILD_MIN_SDK_VERSION)
        targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION)
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'
        exclude 'META-INF/maven/com.squareup.okio/okio/pom.properties'
        exclude 'META-INF/maven/com.squareup.okio/okio/pom.xml'
        exclude 'META-INF/maven/com.squareup.retrofit/retrofit/pom.xml'
        exclude 'META-INF/maven/com.squareup.retrofit/retrofit/pom.properties'
    }
}

kapt {
    generateStubs = true
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile group: 'com.squareup.retrofit2', name: 'converter-gson', version: '2.1.0'
    compile group: 'com.squareup.okhttp3', name: 'logging-interceptor', version: '3.4.1'
    compile 'org.jetbrains:annotations-java5:15.0'
    compile 'hanks.xyz:smallbang-library:0.1.2'
    compile 'com.android.support:support-annotations:' + project.ANDROID_SUPPORT_LIBRARY_VERSION
    compile 'com.android.support:support-v13:' + project.ANDROID_SUPPORT_LIBRARY_VERSION
    compile 'com.android.support:appcompat-v7:' + project.ANDROID_SUPPORT_LIBRARY_VERSION
    compile 'com.android.support:design:' + project.ANDROID_SUPPORT_LIBRARY_VERSION
    compile 'com.android.support:customtabs:' + project.ANDROID_SUPPORT_LIBRARY_VERSION
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

    compile 'com.github.bumptech.glide:glide:3.7.0'
}

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

main gradle build script:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.2-2'
    ext.android_plugin_version = '3.0.0-alpha2'

    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }
        maven { url 'https://maven.fabric.io/public' }

    }
    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
        classpath "com.android.tools.build:gradle:$android_plugin_version"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Anyone has same problems as mine please share the solution.
Thanks.

答:
I think, that correct sollution is wait for Google fix it: https://issuetracker.google.com/issues/62170415

or for now use workaround as I described here:
https://stackoverflow.com/a/44346259/4024146

Body:
my project have 2 modules which are app and apphelper as a library. I have been trying to use kotlin with android Databinding with it but I can't figure it out why it keep showing me these errors when I built project:

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:stagingRuntimeClasspath'.
   > Unable to find a matching configuration in project :apphelper:
       - Configuration 'debugApiElements':
           - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'AndroidTypeAttr{name=Aar}' and found compatible value 'AndroidTypeAttr{name=Aar}'.
           - Required com.android.build.gradle.internal.dependency.BuildTypeAttr 'BuildTypeAttr{name=staging}' and found incompatible value 'BuildTypeAttr{name=debug}'.
           - Found com.android.build.gradle.internal.dependency.VariantAttr 'VariantAttr{name=debug}' but wasn't required.
           - Required org.gradle.api.attributes.Usage 'for runtime' and found incompatible value 'for compile'.
       - Configuration 'debugRuntimeElements':
           - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'AndroidTypeAttr{name=Aar}' and found compatible value 'AndroidTypeAttr{name=Aar}'.
           - Required com.android.build.gradle.internal.dependency.BuildTypeAttr 'BuildTypeAttr{name=staging}' and found incompatible value 'BuildTypeAttr{name=debug}'.
           - Found com.android.build.gradle.internal.dependency.VariantAttr 'VariantAttr{name=debug}' but wasn't required.
           - Required org.gradle.api.attributes.Usage 'for runtime' and found compatible value 'for runtime'.
       - Configuration 'releaseApiElements':
           - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'AndroidTypeAttr{name=Aar}' and found compatible value 'AndroidTypeAttr{name=Aar}'.
           - Required com.android.build.gradle.internal.dependency.BuildTypeAttr 'BuildTypeAttr{name=staging}' and found incompatible value 'BuildTypeAttr{name=release}'.
           - Found com.android.build.gradle.internal.dependency.VariantAttr 'VariantAttr{name=release}' but wasn't required.
           - Required org.gradle.api.attributes.Usage 'for runtime' and found incompatible value 'for compile'.
       - Configuration 'releaseRuntimeElements':
           - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'AndroidTypeAttr{name=Aar}' and found compatible value 'AndroidTypeAttr{name=Aar}'.
           - Required com.android.build.gradle.internal.dependency.BuildTypeAttr 'BuildTypeAttr{name=staging}' and found incompatible value 'BuildTypeAttr{name=release}'.
           - Found com.android.build.gradle.internal.dependency.VariantAttr 'VariantAttr{name=release}' but wasn't required.
           - Required org.gradle.api.attributes.Usage 'for runtime' and found compatible value 'for runtime'.

The error log above is shown when I simply click on the build button and it is weirder if I click run button to install an app to a device which is like:

:app:transformDexArchiveWithDexMergerForDebug
AGPBI: {"kind":"error","text":"Error converting bytecode to dex:\nCause: com.android.dex.DexException: Multiple dex files define Lorg/intellij/lang/annotations/PrintFormatPattern;","sources":[{}],"original":"UNEXPECTED TOP-LEVEL EXCEPTION:\ncom.android.dex.DexException: Multiple dex files define Lorg/intellij/lang/annotations/PrintFormatPattern;\n","tool":"Dex"}
AGPBI: {"kind":"error","text":"com.android.dex.DexException: Multiple dex files define Lorg/intellij/lang/annotations/PrintFormatPattern;","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:608)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:563)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:545)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:167)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat com.android.dx.merge.DexMerger.merge(DexMerger.java:194)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat com.android.builder.dexing.DexArchiveMergerCallable.mergeDexes(DexArchiveMergerCallable.java:66)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:54)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:37)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat java.util.concurrent.ForkJoinTask$AdaptedCallable.exec(ForkJoinTask.java:1424)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)","sources":[{}]}
AGPBI: {"kind":"error","text":"\tat java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)","sources":[{}]}

 FAILED
:app:buildInfoGeneratorDebug

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformDexArchiveWithDexMergerForDebug'.
> com.android.build.api.transform.TransformException: com.android.dex.DexException: Multiple dex files define Lorg/intellij/lang/annotations/PrintFormatPattern;

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED in 4s
74 actionable tasks: 7 executed, 67 avoided (91%)

I downgrade kotlin version to be '1.1.2-2' to avoid the error and also added 'kotlin.incremental=false' to local.properties

Here are all my build.gradle files:

app Module:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: 'test-environment.gradle'
apply plugin: 'io.fabric'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

repositories {
    maven { url 'https://maven.fabric.io/public' }
    maven { url "https://jitpack.io" }
    mavenCentral()
}

allprojects {
    repositories {
        jcenter()
        mavenCentral()
        maven { url 'https://maven.fabric.io/public' }

    }
}

android {
    compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION)
    buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION
    defaultConfig {
        applicationId "com.myapp.android"
        minSdkVersion Integer.parseInt(project.ANDROID_BUILD_MIN_SDK_VERSION)
        targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION)
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
        versionCode 1
        versionName "1.0"
    }

    dataBinding {
        enabled = true
    }

    dexOptions {
        jumboMode = true
    }

    if (System.getenv("CIRCLE")) {
        defaultConfig {
            versionCode Integer.parseInt(System.getenv("CIRCLE_BUILD_NUM"))
            versionName "1.0." + System.getenv("CIRCLE_BUILD_NUM")
        }
    } else {
        defaultConfig {
            versionCode 1
            versionName "1.0"
        }
    }

    signingConfigs {
        debug {
            storeFile file("../myappdebug.keystore")
            storePassword "myapprocks"
            keyAlias "myapp"
            keyPassword "myapprocks"
        }
        staging {
            storeFile file("../myapp_staging.keystore")
            storePassword "myapprocks"
            keyAlias "myapp"
            keyPassword "myapprocks"
        }

        release {
            storeFile rootProject.file('myapp.keystore')
            storePassword System.getenv("KEYSTORE_PASS")
            keyAlias System.getenv("ALIAS_NAME")
            keyPassword System.getenv("ALIAS_PASS")
        }
    }

    buildTypes {
        debug {
            ext.betaDistributionNotifications = false
            signingConfig signingConfigs.debug
            applicationIdSuffix ".dev"
            minifyEnabled false
            shrinkResources false
            proguardFile 'proguard-release.cfg'
            testProguardFile 'proguard-release.cfg'
            manifestPlaceholders = [providerSuffix: ".dev"]
        }
        staging {
            ext.betaDistributionEmailsFilePath = "staging_distribution_emails.txt"
            ext.betaDistributionReleaseNotesFilePath = "release_notes.txt"
            signingConfig signingConfigs.staging
            applicationIdSuffix ".staging"
            shrinkResources true
            minifyEnabled true
            proguardFile 'proguard-release.cfg'
            manifestPlaceholders = [providerSuffix: ".staging"]

        }

        release {
            signingConfig signingConfigs.release
            shrinkResources true
            minifyEnabled true
            proguardFile 'proguard-release.cfg'

        }
    }
}

kapt {
    generateStubs = true
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    api project(':apphelper')
    compile 'com.android.support:appcompat-v7:' + project.ANDROID_SUPPORT_LIBRARY_VERSION
    compile 'com.android.support:cardview-v7:' + project.ANDROID_SUPPORT_LIBRARY_VERSION
    compile 'com.android.support:design:' + project.ANDROID_SUPPORT_LIBRARY_VERSION
    compile 'com.android.support:support-v13:' + project.ANDROID_SUPPORT_LIBRARY_VERSION
    compile 'hanks.xyz:smallbang-library:0.1.2'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.facebook.device.yearclass:yearclass:1.0.1'
    compile 'com.facebook.android:facebook-android-sdk:4.+'
    compile group: 'com.google.code.gson', name: 'gson', version: '2.7'
    compile('com.crashlytics.sdk.android:crashlytics:2.6.2@aar') {
        transitive = true
    }
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    compile "android.arch.lifecycle:runtime:" + project.ANDROID_ARCH_VERSION
    compile "android.arch.lifecycle:extensions:" + project.ANDROID_ARCH_VERSION
    annotationProcessor "android.arch.lifecycle:compiler:" + project.ANDROID_ARCH_VERSION
    compile "android.arch.persistence.room:runtime:" + project.ANDROID_ARCH_VERSION
    annotationProcessor "android.arch.persistence.room:compiler:" + project.ANDROID_ARCH_VERSION
    kapt "com.android.databinding:compiler:$android_plugin_version"

}

library module:

apply plugin: 'com.android.library'

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION)
    buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION

    defaultConfig {
        minSdkVersion Integer.parseInt(project.ANDROID_BUILD_MIN_SDK_VERSION)
        targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION)
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'
        exclude 'META-INF/maven/com.squareup.okio/okio/pom.properties'
        exclude 'META-INF/maven/com.squareup.okio/okio/pom.xml'
        exclude 'META-INF/maven/com.squareup.retrofit/retrofit/pom.xml'
        exclude 'META-INF/maven/com.squareup.retrofit/retrofit/pom.properties'
    }
}

kapt {
    generateStubs = true
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile group: 'com.squareup.retrofit2', name: 'converter-gson', version: '2.1.0'
    compile group: 'com.squareup.okhttp3', name: 'logging-interceptor', version: '3.4.1'
    compile 'org.jetbrains:annotations-java5:15.0'
    compile 'hanks.xyz:smallbang-library:0.1.2'
    compile 'com.android.support:support-annotations:' + project.ANDROID_SUPPORT_LIBRARY_VERSION
    compile 'com.android.support:support-v13:' + project.ANDROID_SUPPORT_LIBRARY_VERSION
    compile 'com.android.support:appcompat-v7:' + project.ANDROID_SUPPORT_LIBRARY_VERSION
    compile 'com.android.support:design:' + project.ANDROID_SUPPORT_LIBRARY_VERSION
    compile 'com.android.support:customtabs:' + project.ANDROID_SUPPORT_LIBRARY_VERSION
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

    compile 'com.github.bumptech.glide:glide:3.7.0'
}

repositories {
    mavenCentral()
}

main gradle build script:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.2-2'
    ext.android_plugin_version = '3.0.0-alpha2'

    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }
        maven { url 'https://maven.fabric.io/public' }

    }
    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
        classpath "com.android.tools.build:gradle:$android_plugin_version"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Anyone has same problems as mine please share the solution.
Thanks.


问:
include sqlite3 lib in c makfile
my makefile can't find my sqlite3 library, I want to link it with a -lsqlite3 flag in the gcc commandline. Can someone tell me want I am doing wrong here.
The error message is the following:

```<code>/usr/bin/ld: cannot find -lsqlite3
</code>```

tom

答:
These days you can just download the amalgamation and build it in with your project.  No more worrying about library locations and architecture matching!

For more details with your exact problem, you'll need to show us the full command line you're using.

Title: include sqlite3 lib in c makfile

Body:
my makefile can't find my sqlite3 library, I want to link it with a -lsqlite3 flag in the gcc commandline. Can someone tell me want I am doing wrong here.
The error message is the following:

/usr/bin/ld: cannot find -lsqlite3

tom


问:
How to handle error : "aws_mobile_analytics_app_id is not defined " while creating ionic3 aws project?
I am new to ionic 3. I tried to create project in ionic 3 .

and selected project type as :

```<code>aws ................ ionic-angular AWS Mobile Hub Starter
</code>```

now  after project get created, when i do 'ionic serve'

its showing error as :

```<code>aws_mobile_analytics_app_id is not defined
</code>```

I don't know what 'aws mobile analytics app id' is and for what pupose it can be use .

Can any one guide me for this one ??
Thanks In advance

答:
Just figured it out myself. Follow the steps below. When you create the ionic project with the aws argument - ionic start myApp aws, it creates a mobile-hub-project.zip file.

Log into your AWS account. In the Mobile Hub dashboard, click the "Import your project" button. Next, find the mobile-hub-project.zip included in this starter project, and drag and drop it to the import modal. Set the name of the project, and then click "Import project."

Once the project is imported, you'll be directed to the dashboard for this Mobile Hub project. To continue configuring the app, you'll need to find the name of the Amazon S3 bucket auto generated through the App Content Delivery system. To do this, click the "Resources" button on the left side of the Mobile Hub project dashboard, find the "Amazon S3 Buckets" card, and then copy the bucket name that contains contents delivery.

To install the AWS CLI, first ensure your pip installation is up to date:

pip install --upgrade pip
Next, install the AWS CLI:

pip install awscli

Next, assuming your terminal is still open inside of the myApp folder, run:

aws s3 cp s3://BUCKET_NAME/aws-config.js src/assets
Replacing BUCKET_NAME with the full name of the S3 bucket found above. This will copy the auto-generated aws-config.js file into the src/assets folder in your Ionic app, which pre-configures all your AWS settings automatically.

Body:
I am new to ionic 3. I tried to create project in ionic 3 .

and selected project type as :

aws ................ ionic-angular AWS Mobile Hub Starter

now  after project get created, when i do 'ionic serve'

its showing error as :

aws_mobile_analytics_app_id is not defined

I don't know what 'aws mobile analytics app id' is and for what pupose it can be use .

Can any one guide me for this one ??
Thanks In advance


问:
REST API - should JSON content be HtmlEncoded?
We have a setup with angular front-end app and asp.net core web api backend. API responds with json.
Question is, should json properties be html encoded or not?

I can see reasons for both: pro and con.

On one hand, REST API should be client agnostic (thus, shouldn't care about html in particular), on the other hand it feels a bit risky to rely on client-side XSS prevention alone.

Thoughts?

答:
Hmm, had to think about it, but I would do:
No additional HTML encoding on top of JSON. Make sure that you set the proper Content Type. If you have "unsafe" data fields, that you consider especially dangerous, then you can specify those in your documentation as HTML encoded without breaking JSON in general.

So both of the following lines are fine:

```<code>{'data': '<script>alert(1)</script>'} # Normal, how I would do it
{'data': '<script>alert(1)</script>'} # unsafe data field which is documented as html encoded
</code>```

Body:
Hmm, had to think about it, but I would do:
No additional HTML encoding on top of JSON. Make sure that you set the proper Content Type. If you have "unsafe" data fields, that you consider especially dangerous, then you can specify those in your documentation as HTML encoded without breaking JSON in general.

So both of the following lines are fine:

{'data': '<script>alert(1)</script>'} # Normal, how I would do it
{'data': '&lt;script&gt;alert(1)&lt;/script&gt;'} # unsafe data field which is documented as html encoded


问:
TypeError when converting an array of floats to ints
I have a smooth function f(x) = sin(x / 5) * exp(x / 10) + 5 * exp(-x / 2)
The task is to explore a non-smooth function h(x) = int(f(x)) on the interval of 1 to 30. In other words, each value of f (x) is converted to type int and the function takes only integer values. I am trying to build h(x) with help of matplotlib.

```<code>import math
import numpy as np
from scipy.optimize import minimize
from scipy.linalg import *
import matplotlib.pyplot as plt

def f(x):
    return np.sin(x / 5.0) * np.exp(x / 10.0) + 5 * np.exp((-x / 2.0))

def h(x):
    return int(f(x))

x = np.arange(1, 30)
y = h(x)

plt.plot(x, y)
plt.show()
</code>```

The code doesn't work. Running the code raises

```<code>TypeError: only length-1 arrays can be converted to Python scalars
</code>```

Using VS I get:

答:
int is a Python class which returns a single int instance.
To convert a NumPy array of floats to a NumPy array of integers, use astype(int):

```<code>import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return np.sin(x / 5.0) * np.exp(x / 10.0) + 5 * np.exp((-x / 2.0))

def h(x):
    return f(x).astype(int)

x = np.arange(1, 30)
y = h(x)

plt.plot(x, y)
plt.show()
</code>```

Body:
I have a smooth function f(x) = sin(x / 5) * exp(x / 10) + 5 * exp(-x / 2)
The task is to explore a non-smooth function h(x) = int(f(x)) on the interval of 1 to 30. In other words, each value of f (x) is converted to type int and the function takes only integer values. I am trying to build h(x) with help of matplotlib.

import math
import numpy as np
from scipy.optimize import minimize
from scipy.linalg import *
import matplotlib.pyplot as plt

def f(x):
    return np.sin(x / 5.0) * np.exp(x / 10.0) + 5 * np.exp((-x / 2.0))

def h(x):
    return int(f(x))

x = np.arange(1, 30)
y = h(x)

plt.plot(x, y)
plt.show()

The code doesn't work. Running the code raises

TypeError: only length-1 arrays can be converted to Python scalars

Using VS I get:

Body:
int is a Python class which returns a single int instance.
To convert a NumPy array of floats to a NumPy array of integers, use astype(int):

import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return np.sin(x / 5.0) * np.exp(x / 10.0) + 5 * np.exp((-x / 2.0))

def h(x):
    return f(x).astype(int)

x = np.arange(1, 30)
y = h(x)

plt.plot(x, y)
plt.show()


问:
Can't figure out how to send HTTP POST request from a JSP- with username/password
I've been banging my head against this one all week and I'm finally one step away from a working POC. Any help with this is appreciated, and hope y'all are having a happy Friday regardless.

My goal is to create a JSP that will:

-Send a predetermined, hardcoded username/password to a Guidewire Servlet via HTTP POST

-At which point the servlet authenticates, logs the user in, and redirects them to the trainingApp login page

-Without any user input, just run it and you'll land on Guidewire already logged in.

I've got it working! However, it's not up to spec. One of my requirements is that the JSP does all of this automatically on run. It's meant to send the same username/password combo every time, with no need for user input.

I've only been able to get the JSP to work as a username/password form with a 'submit' button. like this:

```<code><body>

<%@page import="java.io.*" %>
<%@page import="java.net.*" %>

    <form method="post" action="http://localhost:8180/pc/service/test">
        User:<input name="username"/>
        Password:<input name="password"/>
        <input type="Submit" value="Log in"/>
    </form>

  </body>
</html>
</code>```

This sends the username/password, sure enough, but I need something more like this, and try as I might I can't get it to work.

```<code><%
URLConnection connection = new URL("http://localhost:8180/pc/service/test").openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Authorization", "Basic c3U6Z3c=");
%>
</code>```

I can't seem to get the POST request to fire off and send the auth data without a "submit" button or a form to pass in the username and password. The servlet seems to be working fine, and I'm relieved to be almost done.

Thanks in advance if you can help!

答:
Solved it!

I'm still using the form, HOWEVER:

the inputs are now hidden AND, here's the key:
I added an onload tag to the body to submit the form on page load!

WORKING AS INTENDED.

Body:
I've been banging my head against this one all week and I'm finally one step away from a working POC. Any help with this is appreciated, and hope y'all are having a happy Friday regardless.

My goal is to create a JSP that will:

-Send a predetermined, hardcoded username/password to a Guidewire Servlet via HTTP POST

-At which point the servlet authenticates, logs the user in, and redirects them to the trainingApp login page

-Without any user input, just run it and you'll land on Guidewire already logged in.

I've got it working! However, it's not up to spec. One of my requirements is that the JSP does all of this automatically on run. It's meant to send the same username/password combo every time, with no need for user input.

I've only been able to get the JSP to work as a username/password form with a 'submit' button. like this:

<%@page import="java.io.*" %>
<%@page import="java.net.*" %>

    <form method="post" action="http://localhost:8180/pc/service/test">
        User:<input name="username"/>
        Password:<input name="password"/>
        <input type="Submit" value="Log in"/>
    </form>

This sends the username/password, sure enough, but I need something more like this, and try as I might I can't get it to work.

<%
URLConnection connection = new URL("http://localhost:8180/pc/service/test").openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Authorization", "Basic c3U6Z3c=");
%>

I can't seem to get the POST request to fire off and send the auth data without a "submit" button or a form to pass in the username and password. The servlet seems to be working fine, and I'm relieved to be almost done.

Thanks in advance if you can help!


问:
Adding columns in Spark dataframe based on rules
I have a dataframe df, which contains below data:

```<code>**customers**   **product**   **Val_id**
     1               A            1
     2               B            X
     3               C
     4               D            Z
</code>```

i have been provided 2 rules, which are as below:

```<code>**rule_id**   **rule_name**  **product value**  **priority**
   123              ABC             A,B               1
   456              DEF             A,B,D             2
</code>```

Requirement is to apply these rules on dataframe df in priority order, customers who have passed rule 1, should not be considered for rule 2 and in final dataframe add two more columns rule_id and rule_name, i have written below code to achieve it:

```<code>val rule_name = when(col("product").isin("A","B"), "ABC").otherwise(when(col("product").isin("A","B","D"), "DEF").otherwise(""))
val rule_id = when(col("product").isin("A","B"), "123").otherwise(when(col("product").isin("A","B","D"), "456").otherwise(""))
val df1 = df_customers.withColumn("rule_name" , rule_name).withColumn("rule_id" , rule_id)
df1.show()
</code>```

Final output looks like below:

```<code>**customers**   **product**   **Val_id**  **rule_name**  **rule_id**
     1               A            1           ABC            123
     2               B            X           ABC            123
     3               C
     4               D            Z           DEF            456
</code>```

Is there any better way to achieve it, adding both columns by just going though entire dataset once instead of going through entire dataset twice?

答:
An alternative to your solution would be to use udf functions. Its almost similar to when function as both required serialization and deserialization. Its upto you to test which is faster and efficient.

```<code>def rule_name = udf((product : String) => {
  if(Seq("A", "B").contains(product)) "ABC"
  else if(Seq("A", "B", "D").contains(product)) "DEF"
  else ""
})

def rule_id = udf((product : String) => {
  if(Seq("A", "B").contains(product)) "123"
  else if(Seq("A", "B", "D").contains(product)) "456"
  else ""
})

val df1 = df_customers.withColumn("rule_name" , rule_name(col("product"))).withColumn("rule_id" , rule_id(col("product")))
df1.show()
</code>```

Body:
I have a dataframe df, which contains below data:

**customers**   **product**   **Val_id**
     1               A            1
     2               B            X
     3               C
     4               D            Z

i have been provided 2 rules, which are as below:

**rule_id**   **rule_name**  **product value**  **priority**
   123              ABC             A,B               1
   456              DEF             A,B,D             2

Requirement is to apply these rules on dataframe df in priority order, customers who have passed rule 1, should not be considered for rule 2 and in final dataframe add two more columns rule_id and rule_name, i have written below code to achieve it:

val rule_name = when(col("product").isin("A","B"), "ABC").otherwise(when(col("product").isin("A","B","D"), "DEF").otherwise(""))
val rule_id = when(col("product").isin("A","B"), "123").otherwise(when(col("product").isin("A","B","D"), "456").otherwise(""))
val df1 = df_customers.withColumn("rule_name" , rule_name).withColumn("rule_id" , rule_id)
df1.show()

Final output looks like below:

**customers**   **product**   **Val_id**  **rule_name**  **rule_id**
     1               A            1           ABC            123
     2               B            X           ABC            123
     3               C
     4               D            Z           DEF            456

Is there any better way to achieve it, adding both columns by just going though entire dataset once instead of going through entire dataset twice?

Body:
An alternative to your solution would be to use udf functions. Its almost similar to when function as both required serialization and deserialization. Its upto you to test which is faster and efficient.

def rule_name = udf((product : String) => {
  if(Seq("A", "B").contains(product)) "ABC"
  else if(Seq("A", "B", "D").contains(product)) "DEF"
  else ""
})

def rule_id = udf((product : String) => {
  if(Seq("A", "B").contains(product)) "123"
  else if(Seq("A", "B", "D").contains(product)) "456"
  else ""
})

val df1 = df_customers.withColumn("rule_name" , rule_name(col("product"))).withColumn("rule_id" , rule_id(col("product")))
df1.show()


问:
iOS Programmatically go to Tab AND Push View Controller
My app is connected with Facebook Deep Link for Open Graph.  When the open graph story is clicked in Facebook app, it goes back to my app.  I want it to go back to my app in the 2nd tab, and subsequently present a new view controller onto the screen.

In my appDelegate, when the action is completed from Facebook, I have:

```<code> NSString *objectId = [[[call appLinkData] targetURL].path substringFromIndex:1];
 NSString *nameofhtml = [[objectId lastPathComponent] stringByDeletingPathExtension];
// now handle the deep link
// write whatever code you need to show a view controller that displays the object, etc.

      if (_webViewController == nil) {
          self.webViewController = [[PrayerGifts alloc] init];
       }
     _webViewController.fromFacebook = nameofhtml;
      [self.tabBarController setSelectedIndex:1];
      [_webViewController viewPrayer];
</code>```

This successfully sets the tab where I want it, but the method in _webViewController named viewPrayer never gets called.  That method is:

```<code>Prayer *gonow = [[Prayer alloc] init];
    gonow.currentURL = fromFacebook;
    [self.navigationController pushViewController:gonow animated:YES];
    [gonow release];
</code>```

How can I get it to come back into the app, change the tab bar, and launch the correct view from that tab

答:
Swift 3.1</p>

```<code>func goToChatViewController(){
    DispatchQueue.main.async(execute: { () -> Void in
        self.tabBarController?.selectedIndex = 3
        if let storyboard = self.storyboard {
            let helpViewController = storyboard.instantiateViewController(withIdentifier: "HelpViewController") as! HelpViewController
            let settingsRootNavigationController = self.tabBarController?.viewControllers![3] as! UINavigationController

            settingsRootNavigationController.popToRootViewController(animated: false)
            settingsRootNavigationController.pushViewController(chatController, animated: true)
        }
    })
}
</code>```

Body:
My app is connected with Facebook Deep Link for Open Graph.  When the open graph story is clicked in Facebook app, it goes back to my app.  I want it to go back to my app in the 2nd tab, and subsequently present a new view controller onto the screen.

In my appDelegate, when the action is completed from Facebook, I have:

 NSString *objectId = [[[call appLinkData] targetURL].path substringFromIndex:1];
 NSString *nameofhtml = [[objectId lastPathComponent] stringByDeletingPathExtension];
// now handle the deep link
// write whatever code you need to show a view controller that displays the object, etc.

      if (_webViewController == nil) {
          self.webViewController = [[PrayerGifts alloc] init];
       }
     _webViewController.fromFacebook = nameofhtml;
      [self.tabBarController setSelectedIndex:1];
      [_webViewController viewPrayer];

This successfully sets the tab where I want it, but the method in _webViewController named viewPrayer never gets called.  That method is:

Prayer *gonow = [[Prayer alloc] init];
    gonow.currentURL = fromFacebook;
    [self.navigationController pushViewController:gonow animated:YES];
    [gonow release];

How can I get it to come back into the app, change the tab bar, and launch the correct view from that tab

Body:
Swift 3.1

func goToChatViewController(){
    DispatchQueue.main.async(execute: { () -> Void in
        self.tabBarController?.selectedIndex = 3
        if let storyboard = self.storyboard {
            let helpViewController = storyboard.instantiateViewController(withIdentifier: "HelpViewController") as! HelpViewController
            let settingsRootNavigationController = self.tabBarController?.viewControllers![3] as! UINavigationController

            settingsRootNavigationController.popToRootViewController(animated: false)
            settingsRootNavigationController.pushViewController(chatController, animated: true)
        }
    })
}


问:
Building APK and getting 4 folders instead of the APK file
Building an APK file from a project inside the Android Studio, normally I get the output folder with .apk file inside it, but in this particular case, instead of the APK file, I'm getting 4 folders:

generated

intermediate

outputs

temp

Altogether, they hold the weight of what I'd expect the APK file to be. Is there any way to get the APK out of this project?

答: "you will find apk from this path: /app/build/outputs/apk. If the apk is not there then run your project once again." – Ronak Thakkar</p>


问:
Is it possible to autoformat / beautify SQL queries using pgAdmin4?
I would like to autoformat / beautify my SQL-queries directly in pgAdmin4. I know this feature from Java-developing in Eclipse, where I can beautify the whole code using a simple shortcut. </p>

<p>I only found a command line solution so far that makes my SQL queries pretty: pgFormatter. </p>

答:
Currently this feature is not implemented in pgadmin4 which does autoformat or beautify SQL-queries automatically but you can expect this feature in near future version as developers are working on this feature.

Developers discussion mail thread for the feature:
https://www.postgresql.org/message-id/CAPG3WN46pgzxKERPpr4TSpVFtyeMhParjvKAUzXWOuwZ4qJPhg@mail.gmail.com

Body:
I would like to autoformat / beautify my SQL-queries directly in pgAdmin4. I know this feature from Java-developing in Eclipse, where I can beautify the whole code using a simple shortcut.

I only found a command line solution so far that makes my SQL queries pretty: pgFormatter.


问:
How to fill a new dataframe column by conditional summing
I would like build a new variable by summing values considering multiple conditions (and an extra one, see below). Here you can see R Code until something like my current issue.

```<code># The raw dataframe
area <- c("A", "A", "B", "A", "C", "B", "A", "B", "A", "C")
varclass <- c("Z1", "Z1", "Z1", "Z2", "Z1", "Z1", "Z2", "Z1", "Z2", "Z2")
count <- c(45, 56, 2, 8, 345, 3, 98, 2, 6, 9)

df1 <- data.frame(area,
                  varclass,
                  count,
                  stringsAsFactors = FALSE)
df1
# See how df1 looks like...
#    area varclass count
#1     A       Z1    45
#2     A       Z1    56
#3     B       Z1     2
#4     A       Z2     8
#5     C       Z1   345
#6     B       Z1     3
#7     A       Z2    98
#8     B       Z1     2
#9     A       Z2     6
#10    C       Z2     9

# Building the final dataframe

df2 <- data.frame(unique(df1$area),
                  stringsAsFactors = FALSE)
names(df2)[1] <- "area"
# See how df2 looks like...
#   area
#1    A
#2    B
#3    C

# The new variable to build

df2$Z1_sum <- sum(df1[df1$varclass == "Z1" & df1$area == df2$area,]$count)
# doesn't work

# See what I hope
#   area  Z1_sum
#1    A     101
#2    B      7
#3    C     345
</code>```

As you can see in the last line, I would like building a new variable, Z1_sum, in the df2 database. Z1_sum is the sum of count from the df1 database where varclass = "Z1" and df1$area meet the value of df2$area current row (in MS Excel, that means using a LC1 or $A2 cell id).

Please, consider the fact that I'm not looking for solutions involving to directly build df2 from df1 by using a group by condition or the dcast function... I only want a formula wich allow me to return correct values in my new column. It's my extra condition. Why? It's because I have next to build other variables with most sophisticated formulas than just a sum. By understanding how make such conditional operations, I hope move on...

Thanks for your help.

Jeff

答:
You can get your desired result using dplyr:

```<code>library(dplyr)

df2 <- group_by(df1, area) %>%
  filter(varclass == "Z1") %>%
  summarize(Z1_sum = sum(count)) %>%
df2
#> # A tibble: 3 x 2
#>    area Z1_sum
#>   <chr>  <dbl>
#> 1     A    101
#> 2     B      7
#> 3     C    345
</code>```

The dplyr verbs should be pretty explanatory, and the %>% is the pipe operating, taking the output from one function and making it the first input to the next. group_by here groups by the column area so when we calculate the sum (in summarize) it's the sum for each area group. The filter subsets the data.

Body:
I would like build a new variable by summing values considering multiple conditions (and an extra one, see below). Here you can see R Code until something like my current issue.

# The raw dataframe
area <- c("A", "A", "B", "A", "C", "B", "A", "B", "A", "C")
varclass <- c("Z1", "Z1", "Z1", "Z2", "Z1", "Z1", "Z2", "Z1", "Z2", "Z2")
count <- c(45, 56, 2, 8, 345, 3, 98, 2, 6, 9)

df1 <- data.frame(area,
                  varclass,
                  count,
                  stringsAsFactors = FALSE)
df1
# See how df1 looks like...
#    area varclass count
#1     A       Z1    45
#2     A       Z1    56
#3     B       Z1     2
#4     A       Z2     8
#5     C       Z1   345
#6     B       Z1     3
#7     A       Z2    98
#8     B       Z1     2
#9     A       Z2     6
#10    C       Z2     9

# Building the final dataframe

df2 <- data.frame(unique(df1$area),
                  stringsAsFactors = FALSE)
names(df2)[1] <- "area"
# See how df2 looks like...
#   area
#1    A
#2    B
#3    C

# The new variable to build

df2$Z1_sum <- sum(df1[df1$varclass == "Z1" & df1$area == df2$area,]$count)
# doesn't work

# See what I hope
#   area  Z1_sum
#1    A     101
#2    B      7
#3    C     345

As you can see in the last line, I would like building a new variable, Z1_sum, in the df2 database. Z1_sum is the sum of count from the df1 database where varclass = "Z1" and df1$area meet the value of df2$area current row (in MS Excel, that means using a LC1 or $A2 cell id).

Please, consider the fact that I'm not looking for solutions involving to directly build df2 from df1 by using a group by condition or the dcast function... I only want a formula wich allow me to return correct values in my new column. It's my extra condition. Why? It's because I have next to build other variables with most sophisticated formulas than just a sum. By understanding how make such conditional operations, I hope move on...

Thanks for your help.

Jeff

Body:
You can get your desired result using dplyr:

library(dplyr)

df2 <- group_by(df1, area) %>%
  filter(varclass == "Z1") %>%
  summarize(Z1_sum = sum(count)) %>%
df2
#> # A tibble: 3 x 2
#>    area Z1_sum
#>   <chr>  <dbl>
#> 1     A    101
#> 2     B      7
#> 3     C    345

The dplyr verbs should be pretty explanatory, and the %>% is the pipe operating, taking the output from one function and making it the first input to the next. group_by here groups by the column area so when we calculate the sum (in summarize) it's the sum for each area group. The filter subsets the data.


问:
Is it possible for Eclipse to only open one JFrame?
When run the project second time, can the previous JFrame closed before open the new one ?

So I no need to close the JFrame when trying to run the project second time.

Is it possible to open only one JFrame?

答:
Eclipse has the possibility of terminating the launched program before starting the new one:
It is called Terminate and Relaunch (see the Documentation).

You can bind this to any shortcut you like (Window -> Preferences -> General -> Keys).