问:
Support 2 base URL's in Vue
Is it possible to support 2 base URL's, /test/app and /app with the Vue router? The http requests also have to use the updated path for API calls.

Maybe it's possible to do this with aliases in vue router. But this doesn't solve the API call problem for vue resource. And this would mean I have to create 2 paths for every page.

答:
First and foremost, just so that you're aware, Vue-Resource has been deprecated from official recommendation status because they don't perceive Ajax as a functionality that requires deep integration with the Vue ecosystem.

Now, to the larger question. It sounds like you're trying to use different urls based on which environment you're in (ie. local development vs. production). The easiest way to do this would be to go to the file where you define your Vue-Resource root url and add the following:

```<code>var isProduction = process.env.NODE_ENV === 'production'
var rootUrl = (isProduction) ? 'http://production.domain/api' : 'http://localhost:8080/api'
Vue.http.options.root = rootUrl;
</code>```

This code basically tests if you're in production and, if you are, assigns the production domain api to the variable, otherwise it assigns the local development domain api.

[EDIT]
I took for granted that you would be using the Vue-CLI which sets this up for you. If you are using NPM to start your Vue server, you're probably running a command like npm run dev, which references this line in your package.json:

```<code>{
// ...
     "scripts": {
         "dev": "node build/dev-server.js",
// ...
}
</code>```

You can change that "dev" line to something like this:

```<code>{
// ...
     "scripts": {
         "dev": "NODE_ENV=dev node build/dev-server.js",
// ...
}
</code>```

And that will create the NODE_ENV variable with your Node script which should allow you to use it now within the Vue context.

Title: Support 2 base URL's in Vue

Body:
First and foremost, just so that you're aware, Vue-Resource has been deprecated from official recommendation status because they don't perceive Ajax as a functionality that requires deep integration with the Vue ecosystem.

Now, to the larger question. It sounds like you're trying to use different urls based on which environment you're in (ie. local development vs. production). The easiest way to do this would be to go to the file where you define your Vue-Resource root url and add the following:

var isProduction = process.env.NODE_ENV === 'production'
var rootUrl = (isProduction) ? 'http://production.domain/api' : 'http://localhost:8080/api'
Vue.http.options.root = rootUrl;

This code basically tests if you're in production and, if you are, assigns the production domain api to the variable, otherwise it assigns the local development domain api.

[EDIT]
I took for granted that you would be using the Vue-CLI which sets this up for you. If you are using NPM to start your Vue server, you're probably running a command like npm run dev, which references this line in your package.json:

{
// ...
     "scripts": {
         "dev": "node build/dev-server.js",
// ...
}

You can change that "dev" line to something like this:

{
// ...
     "scripts": {
         "dev": "NODE_ENV=dev node build/dev-server.js",
// ...
}

And that will create the NODE_ENV variable with your Node script which should allow you to use it now within the Vue context.


来源: stackexchange

问:
How to modify USERNAME environ variable?
My tool uses the environment variable USERNAME for authentication. But on Windows you can type your username in upper and lower case characters.
Windows accept this and put this value into the environment variable. even if your username is only in lower case characters. My app does an exact match on USERNAME and the stored username. So if users change their login name accidentally or intentionally the authentication fails.
Question: How to modify (To_Lower) the env variable USERNAME?</p>

答:
I think you are referring to this:

```<code>$a=($env:username).tostring().tolower()
</code>```

In your case you have to again set it back to the same environmental variable.
This is for setting user level environmental variable

```<code>$a=($env:username).tostring().tolower()
[Environment]::SetEnvironmentVariable("username", "$a", "Username")
</code>```

OR, you can use:

```<code>$a=($env:username).tostring().tolower()
$env:UserName = "$a"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I think you are referring to this:

$a=($env:username).tostring().tolower()

In your case you have to again set it back to the same environmental variable.
This is for setting user level environmental variable

$a=($env:username).tostring().tolower()
[Environment]::SetEnvironmentVariable("username", "$a", "Username")

OR, you can use:

$a=($env:username).tostring().tolower()
$env:UserName = "$a"


问:
Using 'OR' in CakePHP find
I am using CakePHP 3.2 and following find().

```<code>if($filter_data_array['age_younger'] != '')
        {
            $conditions["icases.age <= "] = $filter_data_array['age_younger'];
        }

        if($filter_data_array['age_older'] != '')
        {
            $conditions["icases.age >= "] = $filter_data_array['age_older'];
        }

        if($filter_data_array['go_date_after'] != '')
        {
            $conditions["icases.go_date >= "] = $filter_data_array['go_date_after'];
        }

        if($filter_data_array['go_date_before'] != '')
        {
            $conditions["icases.go_date <= "] = $filter_data_array['go_date_before'];
        }

        if($filter_data_array['client'] != '')
        {
            $conditions["icases.client_id = "] = $filter_data_array['client'];
        }

        if($filter_data_array['case_name'] != '')
        {
            $conditions["icases.name = "] = $filter_data_array['case_name'];
        }

        if($filter_data_array['case_ref'] != '')
        {
            $conditions["icases.case_reference_i_d = "] = $filter_data_array['case_ref'];
        }

        if($filter_data_array['instruction_date'] != '')
        {
            $conditions["icases.date_instruction_received >= "] = $filter_data_array['instruction_date'];
        }

        $cases_data = TableRegistry::get('icases')->find('all')
                ->select(['icases.id', 'icases.state', 'icases.client_id', 'icases.name', 'icases.age', 'icases.case_reference_i_d', 'icases.go_date', 'clients.name'])
                ->innerJoin('icases_users', 'icases_users.icase_id = icases.id')
                ->where($conditions)
                ->innerJoin('clients', 'clients.id = icases.client_id')
                ->order(['clients.name' => 'ASC', 'icases.name' => 'ASC'])
                ->execute()
                ->fetchAll('assoc');
</code>```

Now there is a state column in icases table and I want to filter by

```<code>icases.state='active' OR icases.state='pending' OR icases.state='archive'
</code>```

My question is how do I integrate it into my existing $conditions array?

Thank you in advance.

答:
Here is an solution to find all matching with OR conditions

```<code>$conditions = [];     #For storing all of your conditions as an array

if($filter_data_array['age_younger'] != ''){
    $conditions[]["icases.age <= "] = $filter_data_array['age_younger'];
}

if($filter_data_array['age_older'] != ''){
    $conditions[]["icases.age >= "] = $filter_data_array['age_older'];
 }

if($filter_data_array['go_date_after'] != ''){
    $conditions[]["icases.go_date >= "] = $filter_data_array['go_date_after'];
}

if($filter_data_array['go_date_before'] != ''){
    $conditions[]["icases.go_date <= "] = $filter_data_array['go_date_before'];
}

if($filter_data_array['client'] != ''){
    $conditions[]["icases.client_id = "] = $filter_data_array['client'];
}

if($filter_data_array['case_name'] != ''){
    $conditions[]["icases.name = "] = $filter_data_array['case_name'];
}

if($filter_data_array['case_ref'] != ''){
    $conditions[]["icases.case_reference_i_d = "] = $filter_data_array['case_ref'];
}

if($filter_data_array['instruction_date'] != ''){
    $conditions[]["icases.date_instruction_received >= "] = $filter_data_array['instruction_date'];
}

$cases_data = TableRegistry::get('icases')->find('all')
        ->select(['icases.id', 'icases.state', 'icases.client_id', 'icases.name', 'icases.age', 'icases.case_reference_i_d', 'icases.go_date', 'clients.name'])
        ->innerJoin('icases_users', 'icases_users.icase_id = icases.id')
        ->where(['OR'=>$conditions])   #All of your `OR` conditions here
        ->innerJoin('clients', 'clients.id = icases.client_id')
        ->order(['clients.name' => 'ASC', 'icases.name' => 'ASC'])
        ->execute()
        ->fetchAll('assoc');
</code>```

Note : Your code has been changed like as -

```<code>$conditions[INDEX] to $conditions[][INDEX]
</code>```

AND

```<code>->where($conditions) to ->where(['OR'=>$conditions])
</code>```

Title: Using 'OR' in CakePHP find

Body:
I am using CakePHP 3.2 and following find().

if($filter_data_array['age_younger'] != '')
        {
            $conditions["icases.age <= "] = $filter_data_array['age_younger'];
        }

        if($filter_data_array['age_older'] != '')
        {
            $conditions["icases.age >= "] = $filter_data_array['age_older'];
        }

        if($filter_data_array['go_date_after'] != '')
        {
            $conditions["icases.go_date >= "] = $filter_data_array['go_date_after'];
        }

        if($filter_data_array['go_date_before'] != '')
        {
            $conditions["icases.go_date <= "] = $filter_data_array['go_date_before'];
        }

        if($filter_data_array['client'] != '')
        {
            $conditions["icases.client_id = "] = $filter_data_array['client'];
        }

        if($filter_data_array['case_name'] != '')
        {
            $conditions["icases.name = "] = $filter_data_array['case_name'];
        }

        if($filter_data_array['case_ref'] != '')
        {
            $conditions["icases.case_reference_i_d = "] = $filter_data_array['case_ref'];
        }

        if($filter_data_array['instruction_date'] != '')
        {
            $conditions["icases.date_instruction_received >= "] = $filter_data_array['instruction_date'];
        }

        $cases_data = TableRegistry::get('icases')->find('all')
                ->select(['icases.id', 'icases.state', 'icases.client_id', 'icases.name', 'icases.age', 'icases.case_reference_i_d', 'icases.go_date', 'clients.name'])
                ->innerJoin('icases_users', 'icases_users.icase_id = icases.id')
                ->where($conditions)
                ->innerJoin('clients', 'clients.id = icases.client_id')
                ->order(['clients.name' => 'ASC', 'icases.name' => 'ASC'])
                ->execute()
                ->fetchAll('assoc');

Now there is a state column in icases table and I want to filter by

icases.state='active' OR icases.state='pending' OR icases.state='archive'

My question is how do I integrate it into my existing $conditions array?

Thank you in advance.

Body:
Here is an solution to find all matching with OR conditions

$conditions = [];     #For storing all of your conditions as an array

if($filter_data_array['age_younger'] != ''){
    $conditions[]["icases.age <= "] = $filter_data_array['age_younger'];
}

if($filter_data_array['age_older'] != ''){
    $conditions[]["icases.age >= "] = $filter_data_array['age_older'];
 }

if($filter_data_array['go_date_after'] != ''){
    $conditions[]["icases.go_date >= "] = $filter_data_array['go_date_after'];
}

if($filter_data_array['go_date_before'] != ''){
    $conditions[]["icases.go_date <= "] = $filter_data_array['go_date_before'];
}

if($filter_data_array['client'] != ''){
    $conditions[]["icases.client_id = "] = $filter_data_array['client'];
}

if($filter_data_array['case_name'] != ''){
    $conditions[]["icases.name = "] = $filter_data_array['case_name'];
}

if($filter_data_array['case_ref'] != ''){
    $conditions[]["icases.case_reference_i_d = "] = $filter_data_array['case_ref'];
}

if($filter_data_array['instruction_date'] != ''){
    $conditions[]["icases.date_instruction_received >= "] = $filter_data_array['instruction_date'];
}

$cases_data = TableRegistry::get('icases')->find('all')
        ->select(['icases.id', 'icases.state', 'icases.client_id', 'icases.name', 'icases.age', 'icases.case_reference_i_d', 'icases.go_date', 'clients.name'])
        ->innerJoin('icases_users', 'icases_users.icase_id = icases.id')
        ->where(['OR'=>$conditions])   #All of your `OR` conditions here
        ->innerJoin('clients', 'clients.id = icases.client_id')
        ->order(['clients.name' => 'ASC', 'icases.name' => 'ASC'])
        ->execute()
        ->fetchAll('assoc');

Note : Your code has been changed like as -

$conditions[INDEX] to $conditions[][INDEX]

AND

->where($conditions) to ->where(['OR'=>$conditions])


问:
Loading multiple maps libraries with javascript
I am trying to load both the maps library and the places library with javascript so I can embed a map into my page, use google.maps.geometry.spherical functions and make places search requests but I'm having trouble loading all 3 libraries.
At the moment I am importing:

```<code><script type="text/javascript"src="http://maps.google.com/maps?key=mykey"></script>
<script type="text/javascript"src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
</code>```

But I get the errors:

```<code>syntax error
[Break On This Error]

...gs4d .gbmac,.gbes#gbg4 #gbgs4d .gbmac{margin:34px 0 0}.gbemi#gb #gbgs4d .gbmac,....

maps?k...hrkDAmw (line 1)

GClientGeocoder is not defined
[Break On This Error]

var geocoder = new GClientGeocoder();
</code>```

Where am I going wrong?

Thanks a lot.

答:
You can use it in this way     </p>

```<code><script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places"></script>
</code>```

Body:
I am trying to load both the maps library and the places library with javascript so I can embed a map into my page, use google.maps.geometry.spherical functions and make places search requests but I'm having trouble loading all 3 libraries.
At the moment I am importing:

But I get the errors:

syntax error
[Break On This Error]

...gs4d .gbmac,.gbes#gbg4 #gbgs4d .gbmac{margin:34px 0 0}.gbemi#gb #gbgs4d .gbmac,....

maps?k...hrkDAmw (line 1)

GClientGeocoder is not defined
[Break On This Error]

var geocoder = new GClientGeocoder();

Where am I going wrong?

Thanks a lot.

Body:
You can use it in this way

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places"></script>


问:
Android: Firebase token is null at first run
I am using FCM to provide notifications in my app. Everything worked well, but now I realised that, when I install my application using Android Studio (not from GooglePlay) the token is null at first run. When I close my app and restart it, the token is not null anymore. What cause this problem and how can I avoid it?

InstanceIDService:

```<code>public class InstanceIDService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {

        String token = FirebaseInstanceId.getInstance().getToken();
        registerToken(token);
    }

    private void registerToken(String token) {

        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("Token",token)
                .build();

        Request request = new Request.Builder()
                .url("url_to_registration_script")
                .post(body)
                .build();

        try {
            client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

In MainActivity:

```<code>FirebaseMessaging.getInstance().subscribeToTopic("topic");
String token = FirebaseInstanceId.getInstance().getToken();
Log.d("TOKEN", token);
</code>```

Last log returns null when app is installed and started for the first time

Registration script:

```<code> <?php
 if (isset($_POST["Token"])) {

       $_uv_Token=$_POST["Token"];
       $conn = mysqli_connect("localhost","user","pass","db") or die("Error connecting");
       $q="INSERT INTO users (Token) VALUES ( '$_uv_Token') "
          ." ON DUPLICATE KEY UPDATE Token = '$_uv_Token';";

  mysqli_query($conn,$q) or die(mysqli_error($conn));
  mysqli_close($conn);
}
?>
</code>```

答:
I just fell in same issue and this is the way I fixed it. Call the block somewhere in onCreate() method of your activity. I want to sent the Token to my Parse server so you must change it based on your needs.

This is the sample I followed.

```<code>private void subscribeUserToParse() {
        String deviceToken = FirebaseInstanceId.getInstance().getToken();
        if (TextUtils.isEmpty(deviceToken)) {
            Intent intent = new Intent(this, MyFirebaseInstanceIDService.class);
            startService(intent);
            return;
        }

        User user = UserUtil.retrieveUserFromDB(mRealm);
        String objectId = user.getParseObjectId();
        if (!TextUtils.isEmpty(objectId)) {
            ParseUtils.subscribeWithUsersObjectId(objectId, deviceToken);
        }
    }
</code>```

Body:
I am using FCM to provide notifications in my app. Everything worked well, but now I realised that, when I install my application using Android Studio (not from GooglePlay) the token is null at first run. When I close my app and restart it, the token is not null anymore. What cause this problem and how can I avoid it?

InstanceIDService:

public class InstanceIDService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {

        String token = FirebaseInstanceId.getInstance().getToken();
        registerToken(token);
    }

    private void registerToken(String token) {

        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("Token",token)
                .build();

        Request request = new Request.Builder()
                .url("url_to_registration_script")
                .post(body)
                .build();

        try {
            client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In MainActivity:

FirebaseMessaging.getInstance().subscribeToTopic("topic");
String token = FirebaseInstanceId.getInstance().getToken();
Log.d("TOKEN", token);

Last log returns null when app is installed and started for the first time

Registration script:

 <?php
 if (isset($_POST["Token"])) {

       $_uv_Token=$_POST["Token"];
       $conn = mysqli_connect("localhost","user","pass","db") or die("Error connecting");
       $q="INSERT INTO users (Token) VALUES ( '$_uv_Token') "
          ." ON DUPLICATE KEY UPDATE Token = '$_uv_Token';";

  mysqli_query($conn,$q) or die(mysqli_error($conn));
  mysqli_close($conn);
}
?>

Body:
I just fell in same issue and this is the way I fixed it. Call the block somewhere in onCreate() method of your activity. I want to sent the Token to my Parse server so you must change it based on your needs.

This is the sample I followed.

private void subscribeUserToParse() {
        String deviceToken = FirebaseInstanceId.getInstance().getToken();
        if (TextUtils.isEmpty(deviceToken)) {
            Intent intent = new Intent(this, MyFirebaseInstanceIDService.class);
            startService(intent);
            return;
        }

        User user = UserUtil.retrieveUserFromDB(mRealm);
        String objectId = user.getParseObjectId();
        if (!TextUtils.isEmpty(objectId)) {
            ParseUtils.subscribeWithUsersObjectId(objectId, deviceToken);
        }
    }


问:
Hibernate 3 not auto creating tables
Here is my code:

hiberntae.cfg.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">create</property>
  </session-factory>
</hibernate-configuration>
</code>```

pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>edu.bc.eagleapps</groupId>
    <artifactId>mavenproject1</artifactId>
    <version>1.2-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>mavenproject1</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <springframework.version>4.0.6.RELEASE</springframework.version>
        <hibernate.version>3.6.9.Final</hibernate.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.18.2-GA</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-base</artifactId>
            <version>2.6.3</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1.1</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.1</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>6.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Model

```<code>package app.model;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="USER_MASTER")
public class UserMaster {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
        @Column
private String id;

  @Column(length = 50, nullable = false, unique = true)
private String userid;

  @Column(length = 50, nullable = false, unique = true)
private String password;

public UserMaster() {}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getUserid() {
            return userid;
        }

        public void setUserid(String userid) {
            this.userid = userid;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }
</code>```

When I try to save user via controller, I get the following error:

```<code>org.hibernate.exception.SQLGrammarException: could not insert: [app.model.UserMaster]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2345)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2852)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697)
at coolcook.dao.UserMasterDao.saveUser(UserMasterDao.java:23)
at coolcook.service.UserMasterServiceImpl.saveUser(UserMasterServiceImpl.java:16)
at coolcook.controller.UserController.registerUser(UserController.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
a

t java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'app.USER_MASTER' doesn't exist
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
</code>```

the database "app" exists, but whenever I try to save user through controller, it gives me above error.

I search through several answers on SO and other sites but not successful. Any help will be appreciated!

Dao

```<code>   package coolcook.dao;

import coolcook.model.UserMaster;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class UserMasterDao {

    @Autowired
    private SessionFactory sessionFactory;

    public UserMaster saveUser(UserMaster user) {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        Integer employeeID = null;
        try {
            tx = session.beginTransaction();
            session.save(user);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
            }
            return user;
        }

    }
</code>```

springmvc-servlet.xml

```<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:p="http://www.springframework.org/schema/p"
       xmlns:mvc="http://www.springframework.org/schema/mvc" 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-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd
                http://www.springframework.org/schema/tx
                http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
                http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

    <mvc:annotation-driven />
    <context:component-scan base-package="app" />
    <!--<mvc:resources mapping="/views/**" location="/views/" />-->
    <mvc:default-servlet-handler />

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver"
          p:url="jdbc:mysql://localhost:3306/app" p:username="root"
          p:password="root" />

    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan">
            <list>
                <value>app.model</value>
            </list>
        </property>

        <property name="configLocation">
            <value>WEB-INF/hibernate.cfg.xml</value>
        </property>

    </bean>

    <bean id="transactionManager"
          class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />
    <context:annotation-config />

       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name = "prefix" value = "/WEB-INF/views/" />
        <property name = "suffix" value = ".jsp" />
    </bean>

</beans>
</code>```

答:
You have defined hibernate.hbm2ddl.auto as create. This sometimes gives this error because each time your application runs, your table is deleted.

Try changing this to validate.

validate: validate that the schema matches, make no changes to the
  schema of the database.

```<code><property name="hibernate.hbm2ddl.auto">validate</property>
</code>```

Title: Hibernate 3 not auto creating tables

Body:
Here is my code:

hiberntae.cfg.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">create</property>
  </session-factory>
</hibernate-configuration>

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>edu.bc.eagleapps</groupId>
    <artifactId>mavenproject1</artifactId>
    <version>1.2-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>mavenproject1</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <springframework.version>4.0.6.RELEASE</springframework.version>
        <hibernate.version>3.6.9.Final</hibernate.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.18.2-GA</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-base</artifactId>
            <version>2.6.3</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1.1</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.1</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>6.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

Model

package app.model;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="USER_MASTER")
public class UserMaster {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
        @Column
private String id;

  @Column(length = 50, nullable = false, unique = true)
private String userid;

  @Column(length = 50, nullable = false, unique = true)
private String password;

public UserMaster() {}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getUserid() {
            return userid;
        }

        public void setUserid(String userid) {
            this.userid = userid;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }

When I try to save user via controller, I get the following error:

org.hibernate.exception.SQLGrammarException: could not insert: [app.model.UserMaster]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2345)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2852)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697)
at coolcook.dao.UserMasterDao.saveUser(UserMasterDao.java:23)
at coolcook.service.UserMasterServiceImpl.saveUser(UserMasterServiceImpl.java:16)
at coolcook.controller.UserController.registerUser(UserController.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
a

t java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'app.USER_MASTER' doesn't exist
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)

the database "app" exists, but whenever I try to save user through controller, it gives me above error.

I search through several answers on SO and other sites but not successful. Any help will be appreciated!

Dao

   package coolcook.dao;

import coolcook.model.UserMaster;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class UserMasterDao {

    @Autowired
    private SessionFactory sessionFactory;

    public UserMaster saveUser(UserMaster user) {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        Integer employeeID = null;
        try {
            tx = session.beginTransaction();
            session.save(user);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
            }
            return user;
        }

    }

springmvc-servlet.xml

<?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:p="http://www.springframework.org/schema/p"
       xmlns:mvc="http://www.springframework.org/schema/mvc" 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-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd
                http://www.springframework.org/schema/tx
                http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
                http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

    <mvc:annotation-driven />
    <context:component-scan base-package="app" />

    <mvc:default-servlet-handler />

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver"
          p:url="jdbc:mysql://localhost:3306/app" p:username="root"
          p:password="root" />

    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan">
            <list>
                <value>app.model</value>
            </list>
        </property>

        <property name="configLocation">
            <value>WEB-INF/hibernate.cfg.xml</value>
        </property>

    </bean>

    <bean id="transactionManager"
          class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />
    <context:annotation-config />

       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name = "prefix" value = "/WEB-INF/views/" />
        <property name = "suffix" value = ".jsp" />
    </bean>

</beans>

Body:
You have defined hibernate.hbm2ddl.auto as create. This sometimes gives this error because each time your application runs, your table is deleted.

Try changing this to validate.

validate: validate that the schema matches, make no changes to the
  schema of the database.

<property name="hibernate.hbm2ddl.auto">validate</property>


问:
Video not Autoplaying in Html
I have a video which is not autoplaying:

```<code>  <video preload="auto" autoplay="autoplay" loop="loop" muted="muted" className="myVideo" id="vidAd">
        <source src={video} type="video/mp4"/>
        <source src={video} type="video/ogg"/>
        <source src={video} type="video/webm"/>
      Your browser does not support the video tag.
    </video>
</code>```

Currently the video shows up but does not autoplay.

I tried to tackle this with javascript but I'm not sure what the correct syntax is

```<code><script type="text/javascript">
$(document).ready(function() {
   var vid = document.getElementById("vidAd");
   vid.autoplay = true;
   vid.load();
});
</script>
</code>```

答:
What browser are you using? The autoplay attribute doesn't work for browser below IE9 I believe.

Also you don't need to provide a value to the attribute 'autoplay'

```<code><video preload="auto" className="myVideo" id="vidAd" loop muted autoplay>
    <source src={video} type="video/mp4"/>
    <source src={video} type="video/ogg"/>
    <source src={video} type="video/webm"/>
  Your browser does not support the video tag.
</video>
</code>```

Have you tried removing all the attributes on the video element except the autoplay? Maybe there's an error in one of these attributes (Loop and muted also don't require a 'value').

Title: Video not Autoplaying in Html

Body:
I have a video which is not autoplaying:

  <video preload="auto" autoplay="autoplay" loop="loop" muted="muted" className="myVideo" id="vidAd">
        <source src={video} type="video/mp4"/>
        <source src={video} type="video/ogg"/>
        <source src={video} type="video/webm"/>
      Your browser does not support the video tag.
    </video>

Currently the video shows up but does not autoplay.

I tried to tackle this with javascript but I'm not sure what the correct syntax is

Body:
What browser are you using? The autoplay attribute doesn't work for browser below IE9 I believe.

Also you don't need to provide a value to the attribute 'autoplay'

<video preload="auto" className="myVideo" id="vidAd" loop muted autoplay>
    <source src={video} type="video/mp4"/>
    <source src={video} type="video/ogg"/>
    <source src={video} type="video/webm"/>
  Your browser does not support the video tag.
</video>

Have you tried removing all the attributes on the video element except the autoplay? Maybe there's an error in one of these attributes (Loop and muted also don't require a 'value').


问:
Difference between these implementations in linux kernel
In Linux kernel code, I can see the macro which expands to

```<code>(1<<0)
</code>```

What does it imply? We can directly use 1 in that place why (1<<0)?

Basically what is the difference between

```<code>(AVIVO_D1CRTC_CONTROL & (1<<0))
</code>```

and

```<code>(AVIVO_D1CRTC_CONTROL & (1))
</code>```

答:
It's a style thing.

```<code>(X & (1<<0)) // And X with a value that has the 0th bit set.
</code>```

which expands much nicer for

```<code>(X & (1<<7)) // And X with a value that has the 7th bit set.
</code>```

vice

```<code>(X & (1)) // And X with 1.

(X & (128)) // And X with 128. (or 0x80)
</code>```

Edit: Because I screwed up the manual bit shifts... Second edit I had it right the first time.

Body:
In Linux kernel code, I can see the macro which expands to

(1<<0)

What does it imply? We can directly use 1 in that place why (1<<0)?

Basically what is the difference between

(AVIVO_D1CRTC_CONTROL & (1<<0))

and

(AVIVO_D1CRTC_CONTROL & (1))

Body:
It's a style thing.

(X & (1<<0)) // And X with a value that has the 0th bit set.

which expands much nicer for

(X & (1<<7)) // And X with a value that has the 7th bit set.

vice

(X & (1)) // And X with 1.

(X & (128)) // And X with 128. (or 0x80)

Edit: Because I screwed up the manual bit shifts... Second edit I had it right the first time.


问:
How do we create nested Vue Components passing other elements as their children
In React I would do something like this:

```<code>//ParentComponent.js
(<div>
  {this.props.children}
</div>)

//ChildComponent.js
(<div>
  I'm the child!
</div>)

//App.js
import ParentComponent
import ChildComponent

<ParentComponent>
  <ChildComponent />
  <span>Other element</span>
</ParentComponent>
</code>```

I understand they are different things, but how could I do something like this in Vue? I want to pass ChildElement in ParentComponent's content, and in ParentComponent I must be able to put its content somewhere.

What is the closest to this idea?

答:
You would do that using slots.

```<code>Vue.component("parent",{
  template:"<div><h1>I'm the parent component</h1><slot></slot></div>",
})

Vue.component("child", {
  template: "<div><h2>I'm the child component</h2></div>"
})

new Vue({
  el:"#app"
})

<div id="app">
  <parent>
    <child></child>
  </parent>
</div>
</code>```

Example.

Body:
In React I would do something like this:

//ParentComponent.js
(

  {this.props.children}

)

//ChildComponent.js
(

  I'm the child!

)

//App.js
import ParentComponent
import ChildComponent

<ParentComponent>
  <ChildComponent />
  Other element
</ParentComponent>

I understand they are different things, but how could I do something like this in Vue? I want to pass ChildElement in ParentComponent's content, and in ParentComponent I must be able to put its content somewhere.

What is the closest to this idea?

Body:
You would do that using slots.

Vue.component("parent",{
  template:"<div><h1>I'm the parent component</h1><slot></slot></div>",
})

Vue.component("child", {
  template: "<div><h2>I'm the child component</h2></div>"
})

new Vue({
  el:"#app"
})

<div id="app">
  <parent>
    <child></child>
  </parent>
</div>

Example.

ContentLicense: CC BY-SA 4.0


问:
Error while trying to connect to Octobercms database: Connection failed: SQLSTATE[HY000] [2002] No such file or directory
I keep getting this error on my server:

```<code>Connection failed: SQLSTATE[HY000] [2002] No such file or directory
</code>```

There is a problem with the specified Database configuration. My host is TSDhost.

How can I fix this?

答: One possible solution would be to set the database host from localhost to 127.0.0.1

Body:
I keep getting this error on my server:

Connection failed: SQLSTATE[HY000] [2002] No such file or directory

There is a problem with the specified Database configuration. My host is TSDhost.

How can I fix this?


问:
Java - is there a way to open a text file if it does not exist already, and append to it if it does exist?
I am pretty new to Java and I came across this problem. I want the java code to make a txt file if it does not exist already, but if it does, I want PrintWriter to append to it using FileWriter. Here is my code:

Edit: I attempted to fix my code but now I am getting the IOException error. What am I doing wrong here?
Edit 2: I think my code is unique since I am trying to make it create a new file if the file does not exist, and make it append to the existing file if it already exists.

```<code>import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

/**
 * Created by FakeOwl96 on 3/28/2017.
 */
public class AreaOfCircle {
    private static double PI = Math.PI;
    private double radius;
    private static double area;
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        AreaOfCircle a = new AreaOfCircle();
        System.out.print("Type in the radius of circle: ");
        a.radius = keyboard.nextDouble();
        getArea(a.radius);
        System.out.print("Name of the txt file you want to create:");
        String fileName = keyboard.nextLine();
        keyboard.nextLine();
        try {
            File myFile = new File(fileName);
            if (!myFile.exists()) {
                myFile.createNewFile();
            }
            FileWriter fw = new FileWriter(myFile, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("The area of the circle is " + area + ".\n");
            bw.close();
        }
        catch (IOException e) {
            System.out.println("IOException Occured");
            e.printStackTrace();
        }
    }

    public static void getArea(double n) {
        area = n * PI;
    }
}
</code>```

答:
```<code>import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class AreaOfCircle {
    private static double PI = Math.PI;
    private double radius;
    private static double area;
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        AreaOfCircle a = new AreaOfCircle();
        System.out.print("Type in the radius of circle: ");
        a.radius = keyboard.nextDouble();
        getArea(a.radius);
        System.out.print("Name of the txt file you want to create:");
        String fileName = keyboard.next();
        keyboard.nextLine();
        try {
            File myFile = new File(fileName);
            if (!myFile.exists()) {
                myFile.createNewFile();
            }
            FileWriter fw = new FileWriter(myFile, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("The area of the circle is " + area + ".\n");
            bw.close();
        }
        catch (IOException e) {
            System.out.println("IOException Occured");
            e.printStackTrace();
        }
    }

    public static void getArea(double n) {
        area = n * PI;
    }
}
</code>```

The only change I made is
String fileName = keyboard.next(); from //keyboard.nextLine()
The above code worked for me . Hope this helps.

Body:
I am pretty new to Java and I came across this problem. I want the java code to make a txt file if it does not exist already, but if it does, I want PrintWriter to append to it using FileWriter. Here is my code:

Edit: I attempted to fix my code but now I am getting the IOException error. What am I doing wrong here?
Edit 2: I think my code is unique since I am trying to make it create a new file if the file does not exist, and make it append to the existing file if it already exists.

import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

/**
 * Created by FakeOwl96 on 3/28/2017.
 */
public class AreaOfCircle {
    private static double PI = Math.PI;
    private double radius;
    private static double area;
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        AreaOfCircle a = new AreaOfCircle();
        System.out.print("Type in the radius of circle: ");
        a.radius = keyboard.nextDouble();
        getArea(a.radius);
        System.out.print("Name of the txt file you want to create:");
        String fileName = keyboard.nextLine();
        keyboard.nextLine();
        try {
            File myFile = new File(fileName);
            if (!myFile.exists()) {
                myFile.createNewFile();
            }
            FileWriter fw = new FileWriter(myFile, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("The area of the circle is " + area + ".\n");
            bw.close();
        }
        catch (IOException e) {
            System.out.println("IOException Occured");
            e.printStackTrace();
        }
    }

    public static void getArea(double n) {
        area = n * PI;
    }
}

Body:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class AreaOfCircle {
    private static double PI = Math.PI;
    private double radius;
    private static double area;
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        AreaOfCircle a = new AreaOfCircle();
        System.out.print("Type in the radius of circle: ");
        a.radius = keyboard.nextDouble();
        getArea(a.radius);
        System.out.print("Name of the txt file you want to create:");
        String fileName = keyboard.next();
        keyboard.nextLine();
        try {
            File myFile = new File(fileName);
            if (!myFile.exists()) {
                myFile.createNewFile();
            }
            FileWriter fw = new FileWriter(myFile, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("The area of the circle is " + area + ".\n");
            bw.close();
        }
        catch (IOException e) {
            System.out.println("IOException Occured");
            e.printStackTrace();
        }
    }

    public static void getArea(double n) {
        area = n * PI;
    }
}

The only change I made is
String fileName = keyboard.next(); from //keyboard.nextLine()
The above code worked for me . Hope this helps.


问:
Statistics, machine learning and data mining
I am currently learning data mining and I have the following questions.

what is the relationship between machine learning and data mining?

I found many data mining techniques are associated with statistics, while I "hear" data mining has many thing to do with machine learning. So my question is: is machine learning closely related with statistics?

If they are not closely related, is there such divisions that separate data mining focusing on statistical techniques and data mining focusing on machine learning skills? Because I found department of statistics of some graduate schools open data mining courses.

答:
A comprehensive answer was already given by @SpeedBirdNine. As a side note:

Data-mining and Machine-learning are mainly based on the old but ingenious ideas of statisticians. (Inferential statistics, decision theories, etc.)

Classic Statistics + today's powerful computers = DM & ML

Since we are living in the era of big data, the barrier statisticians used to be faced with, in terms of the absence of enough data, is no longer an issue. Therefore, in many cases (but not all of course), it is safe to say that Data-mining/Machine-learning is the new Statistics! (The infinity symbol ∞ they used to have in their equations that if n (the sample size) goes to infinity, then everything's behavior is predictable (!), is not a compromised reality anymore!).

Regarding your last question, in my opinion, in any meaningful research, you either need to apply some statistical methods on big data and this is when DM/ML comes in handy, or you need to apply a DM/ML method which is already designed based on classical statistics. These are the two sections that every DM/ML research is involved, and statistics is not excluded, let alone when the goal is to come up with a noble DM/ML algorithm to analyze/cluster/classify big data.


问:
Unable to use Facebook Places after manually setting Geolocation in Firefox
I am having a play with Facebook Places but don't want to publish my current location for privacy reasons. I therefore changed the geo.wifi.uri in the about:config in Firefox to point to a file containing JSON of my location with the lat and long. This works great and if I test by using Google Maps or the Mozilla Geolocation test I get the location I have specified. However, if I 'Check in' via Facebook (touch.facebook.com) in Firefox I can see the location on the little Bing map but get the following error

We couldn't determine the coordinates of this location. Check if your latitude and longitude are in range, and verify the format of the location.\n

Any ideas?

Thanks

答:
I have wired up Google Latitude to Firefox geolocation. This lets you manually update your location in Google Latitude with a single mouse click, instead of looking up your latitude and longitude yourself and typing it into a local file or URI. My article on the subject is Make Firefox Take Geolocation From Google Latitude.

I am not normally a Facebook Places user, but I browsed over to touch.facebook.com and clicked Places, and was presented with the usual permission prompt and then a list of nearby places. So the problem does not seem to be in Facebook or in Firefox. Without looking at your JSON I could not guess why it's not working.

Cheers, MetaEd

ContentLicense: CC BY-SA 2.5


问:
Lua string.find() error
So I'm writing a Lua script and I tested it but I got an error that I don't know how to fix:

.\search.lua:10: malformed pattern (missing ']')

Below is my code. If you know what I did wrong, it would be very helpful if you could tell me.

```<code>weird = "--[[".."\n"
function readAll(file)
    local c = io.open(file, "rb")
    local j = c:read("*all")
    c:close()
    return(j)
end
function blockActive()
    local fc = readAll("functions.lua")
    if string.find(fc,weird) ~= nil then
        require("blockDeactivated")
        return("false")
    else
        return("true")
    end
end
print(blockActive())
</code>```

Edit: first comment had the answer. I changed
weird = "--[[".."\n" to weird = "%-%-%[%[".."\r" The \n to \r change was because it was actually supposed to be that way in the first place.

答:
This errors because string.find uses Lua Patterns.

Most non-alpha-numeric characters, such as "[", ".", "-" etc. convey special meaning.

string.find(fc,weird), or better, fc:find(weird) is trying to parse these special characters, and erroring.

You can use these patterns to cancel out your other patterns, however.

weird = ("--[["):gsub("%W","%%%0") .. "\r?\n"
```

<p>This is a little daunting, but it will hopefully make sense.</p>

<p>the <code>("--[[")</code> is the orignal first part of your weird string, working as expected.</p>

<p><code>:gsub()</code> is a function that replaces a pattern with another one. Once again, see Patterns.</p>

<p><code>"%W"</code> is a pattern that matches every string that isn't a letter, a number, or an underscore.</p>

<p><code>%%%0</code> replaces everything that matches with itself (<code>%0</code> is a string that represents everything in this match), following a <code>%</code>, which is escaped.</p>

<p>So this means that <code>[[</code> will be turned into <code>%[%[</code>, which is how find, and similar patterns 'escape' special characters.</p>

<p>The reason <code>\n</code> is now <code>\r?\n</code> refers back to these patterns. This matches it if it ends with a <code>\n</code>, like it did before. However, if this is running on windows, a newline might look like <code>\r\n</code>. (You can read up on this HERE). A <code>?</code> following a character, <code>\r</code> in this case, means it can <em>optionally</em> match it. So this matches both <code>--[[\n</code> <em>and</em> <code>--[[\r\n</code>, supporting both windows and linux.</p>

<p>Now, when you run your <code>fc:find(weird)</code>, it's running <code>fc:find("%-%-%[%[\r?\n")</code>, which should be exactly what you want.</p>

<p>Hope this has helped!</p>

<p><em>Finished code if you're a bit lazy</em></p>

<pre class="lang-lua prettyprint-override"><code>weird = ("--[["):gsub("%W","%%%0") .. "\r?\n" // Escape "--[[", add a newline. Used in our find.

// readAll(file)
// Takes a string as input representing a filename, returns the entire contents as a string.
function readAll(file)
    local c = io.open(file, "rb")   // Open the file specified by the argument. Read-only, binary (Doesn't autoformat things like \r\n)
    local j = c:read("*all")        // Dump the contents of the file into a string.
    c:close()                       // Close the file, free up memory.
    return j                        // Return the contents of the string.
end

// blockActive()
// returns whether or not the weird string was matched in 'functions.lua', executes 'blockDeactivated.lua' if it wasn't.
function blockActive()
    local fc = readAll("functions.lua") // Dump the contents of 'functions.lua' into a string.
    if fc:find(weird) then              // If it functions.lua has the block-er.
        require("blockDeactivated")     // Require (Thus, execute, consider loadfile instead) 'blockDeactived.lua'
        return false                    // Return false.
    else
        return true                     // Return true.
    end
end
print(blockActive()) // Test? the blockActve code.
</code>```

Title: Lua string.find() error

Body:
So I'm writing a Lua script and I tested it but I got an error that I don't know how to fix:

.\search.lua:10: malformed pattern (missing ']')

Below is my code. If you know what I did wrong, it would be very helpful if you could tell me.

weird = "--[[".."\n"
function readAll(file)
    local c = io.open(file, "rb")
    local j = c:read("*all")
    c:close()
    return(j)
end
function blockActive()
    local fc = readAll("functions.lua")
    if string.find(fc,weird) ~= nil then
        require("blockDeactivated")
        return("false")
    else
        return("true")
    end
end
print(blockActive())

Edit: first comment had the answer. I changed
weird = "--[[".."\n" to weird = "%-%-%[%[".."\r" The \n to \r change was because it was actually supposed to be that way in the first place.

Body:
This errors because string.find uses Lua Patterns.

Most non-alpha-numeric characters, such as "[", ".", "-" etc. convey special meaning.

string.find(fc,weird), or better, fc:find(weird) is trying to parse these special characters, and erroring.

You can use these patterns to cancel out your other patterns, however.

weird = ("--[["):gsub("%W","%%%0") .. "\r?\n"

This is a little daunting, but it will hopefully make sense.

the ("--[[") is the orignal first part of your weird string, working as expected.

:gsub() is a function that replaces a pattern with another one. Once again, see Patterns.

"%W" is a pattern that matches every string that isn't a letter, a number, or an underscore.

%%%0 replaces everything that matches with itself (%0 is a string that represents everything in this match), following a %, which is escaped.

So this means that [[ will be turned into %[%[, which is how find, and similar patterns 'escape' special characters.

The reason \n is now \r?\n refers back to these patterns. This matches it if it ends with a \n, like it did before. However, if this is running on windows, a newline might look like \r\n. (You can read up on this HERE). A ? following a character, \r in this case, means it can optionally match it. So this matches both --[[\n and --[[\r\n, supporting both windows and linux.

Now, when you run your fc:find(weird), it's running fc:find("%-%-%[%[\r?\n"), which should be exactly what you want.

Hope this has helped!

Finished code if you're a bit lazy

weird = ("--[["):gsub("%W","%%%0") .. "\r?\n" // Escape "--[[", add a newline. Used in our find.

// readAll(file)
// Takes a string as input representing a filename, returns the entire contents as a string.
function readAll(file)
    local c = io.open(file, "rb")   // Open the file specified by the argument. Read-only, binary (Doesn't autoformat things like \r\n)
    local j = c:read("*all")        // Dump the contents of the file into a string.
    c:close()                       // Close the file, free up memory.
    return j                        // Return the contents of the string.
end

// blockActive()
// returns whether or not the weird string was matched in 'functions.lua', executes 'blockDeactivated.lua' if it wasn't.
function blockActive()
    local fc = readAll("functions.lua") // Dump the contents of 'functions.lua' into a string.
    if fc:find(weird) then              // If it functions.lua has the block-er.
        require("blockDeactivated")     // Require (Thus, execute, consider loadfile instead) 'blockDeactived.lua'
        return false                    // Return false.
    else
        return true                     // Return true.
    end
end
print(blockActive()) // Test? the blockActve code.


问:
Count number of POS in (word,pos) tuples of NLTK tagged sentences
I have a list of tuples and I'm trying to count number of keys of tuples. The following is my code:

```<code>import nltk
from nltk.corpus import treebank
from collections import Counter

# print treebank.fileids()
treebank_raw = list(treebank.tagged_sents()) ##treebank_raw is a list of list (of tuples)

treebank_flipped = []
treebank_flipped_counter = Counter()
for sent in treebank_raw:
    flipped = {b : a.lower() for a, b in sent}
    treebank_flipped_counter.update(flipped.items())
</code>```

If I were to count number of u'VBD', print treebank_flipped_count reveals the following to be all independent cases when in fact I want to count them together.

```<code>(u'VBD', u'said'): 405
(u'VBD', u'was'): 264
(u'VBD', u'were'): 138
</code>```

So that u'VBD' : (405 + 264 + 138). How do I dissolve keys of tuples and count them altogether?

答:
@lenz answer on using the Counter and list comprehension is good.

But if you need something a little more complicated, esp. when you need to also retrieve the word+pos counts other than the the pos / word counts, maybe this would help:

```<code>from collections import Counter, defaultdict
corpus_counts = defaultdict(Counter)
for word, pos in treebank.tagged_sents():
    corpus_counts[pos][word] +=1
</code>```

[out]:

```<code>>>> corpus_counts['NNPS']
Counter({u'Securities': 16, u'Containers': 16, u'Industries': 12, u'Materials': 10, u'Soviets': 8, u'Americans': 6, u'Associates': 5, u'Airlines': 5, u'Savings': 5, u'Motors': 5, u'States': 5, u'Democrats': 5, u'Systems': 4, u'Markets': 4, u'Resources': 4, u'Services': 4, u'Travelers': 4, u'Communications': 4, u'Stores': 3, u'Investors': 3, u'Partners': 3, u'Giants': 3, u'Machines': 3, u'Brothers': 3, u'Philippines': 3, u'Issues': 3, u'Friends': 3, u'Messrs.': 2, u'Laboratories': 2, u'Engineers': 2, u'Futures': 2, u'Burgundies': 2, u'Islands': 2, u'Options': 2, u'Cabernets': 2, u'Nations': 2, u'Instruments': 2, u'Writers': 2, u'Dealers': 2, u'Institutes': 2, u'ADRs': 2, u'Contras': 2, u'Lakes': 1, u'Tots': 1, u'BILLS': 1, u'Manufacturers': 1, u'Republicans': 1, u'Journals': 1, u'Netherlands': 1, u'Notes': 1, u'Products': 1, u'Underwoods': 1, u'Operations': 1, u'ASSETS': 1, u'Facilities': 1, u'Foods': 1, u'Preferences': 1, u'Holdings': 1, u'BRIEFS': 1, u'Dakotas': 1, u'Plains': 1, u'Toys': 1, u'Lawyers': 1, u'Utilities': 1, u'Monopolies': 1, u'Chardonnays': 1, u'Inns': 1, u'Charities': 1, u'Parkinson': 1, u'Fundamentalists': 1, u'Centers': 1, u'Bridges': 1, u'Yorkers': 1, u'SOYBEANS': 1, u'Pictures': 1, u'Rieslings': 1, u'F-series': 1, u'ASSOCIATES': 1, u'RATES': 1, u'Lawmakers': 1, u'Contracts': 1, u'Investments': 1, u'Dolphins': 1, u'Appropriations': 1, u'Mergers': 1, u'Productions': 1, u'Virginians': 1, u'Works': 1, u'Donuts': 1, u'Angels': 1, u'Asians': 1, u'GRAINS': 1, u'Airways': 1, u'Elders': 1, u'Delegates': 1, u'Germans': 1, u'Articles': 1, u'Lines': 1, u'METALS': 1, u'Publications': 1, u'Mercedes': 1, u'Craftsmen': 1, u'Builders': 1, u'Appeals': 1, u'Bricklayers': 1, u'FUNDS': 1, u'Springs': 1})

# Count of `Securities|NNPS`:
>>> corpus_counts['NNPS']['Securities']
16

# Count of all `NNPS`:
>>> sum(corpus_counts['NNPS'].values())
</code>```

Body:
I have a list of tuples and I'm trying to count number of keys of tuples. The following is my code:

import nltk
from nltk.corpus import treebank
from collections import Counter

# print treebank.fileids()
treebank_raw = list(treebank.tagged_sents()) ##treebank_raw is a list of list (of tuples)

treebank_flipped = []
treebank_flipped_counter = Counter()
for sent in treebank_raw:
    flipped = {b : a.lower() for a, b in sent}
    treebank_flipped_counter.update(flipped.items())

If I were to count number of u'VBD', print treebank_flipped_count reveals the following to be all independent cases when in fact I want to count them together.

(u'VBD', u'said'): 405
(u'VBD', u'was'): 264
(u'VBD', u'were'): 138

So that u'VBD' : (405 + 264 + 138). How do I dissolve keys of tuples and count them altogether?

Body:
@lenz answer on using the Counter and list comprehension is good.

But if you need something a little more complicated, esp. when you need to also retrieve the word+pos counts other than the the pos / word counts, maybe this would help:

from collections import Counter, defaultdict
corpus_counts = defaultdict(Counter)
for word, pos in treebank.tagged_sents():
    corpus_counts[pos][word] +=1

[out]:

>>> corpus_counts['NNPS']
Counter({u'Securities': 16, u'Containers': 16, u'Industries': 12, u'Materials': 10, u'Soviets': 8, u'Americans': 6, u'Associates': 5, u'Airlines': 5, u'Savings': 5, u'Motors': 5, u'States': 5, u'Democrats': 5, u'Systems': 4, u'Markets': 4, u'Resources': 4, u'Services': 4, u'Travelers': 4, u'Communications': 4, u'Stores': 3, u'Investors': 3, u'Partners': 3, u'Giants': 3, u'Machines': 3, u'Brothers': 3, u'Philippines': 3, u'Issues': 3, u'Friends': 3, u'Messrs.': 2, u'Laboratories': 2, u'Engineers': 2, u'Futures': 2, u'Burgundies': 2, u'Islands': 2, u'Options': 2, u'Cabernets': 2, u'Nations': 2, u'Instruments': 2, u'Writers': 2, u'Dealers': 2, u'Institutes': 2, u'ADRs': 2, u'Contras': 2, u'Lakes': 1, u'Tots': 1, u'BILLS': 1, u'Manufacturers': 1, u'Republicans': 1, u'Journals': 1, u'Netherlands': 1, u'Notes': 1, u'Products': 1, u'Underwoods': 1, u'Operations': 1, u'ASSETS': 1, u'Facilities': 1, u'Foods': 1, u'Preferences': 1, u'Holdings': 1, u'BRIEFS': 1, u'Dakotas': 1, u'Plains': 1, u'Toys': 1, u'Lawyers': 1, u'Utilities': 1, u'Monopolies': 1, u'Chardonnays': 1, u'Inns': 1, u'Charities': 1, u'Parkinson': 1, u'Fundamentalists': 1, u'Centers': 1, u'Bridges': 1, u'Yorkers': 1, u'SOYBEANS': 1, u'Pictures': 1, u'Rieslings': 1, u'F-series': 1, u'ASSOCIATES': 1, u'RATES': 1, u'Lawmakers': 1, u'Contracts': 1, u'Investments': 1, u'Dolphins': 1, u'Appropriations': 1, u'Mergers': 1, u'Productions': 1, u'Virginians': 1, u'Works': 1, u'Donuts': 1, u'Angels': 1, u'Asians': 1, u'GRAINS': 1, u'Airways': 1, u'Elders': 1, u'Delegates': 1, u'Germans': 1, u'Articles': 1, u'Lines': 1, u'METALS': 1, u'Publications': 1, u'Mercedes': 1, u'Craftsmen': 1, u'Builders': 1, u'Appeals': 1, u'Bricklayers': 1, u'FUNDS': 1, u'Springs': 1})

# Count of `Securities|NNPS`:
>>> corpus_counts['NNPS']['Securities']
16

# Count of all `NNPS`:
>>> sum(corpus_counts['NNPS'].values())


问:
jQuery .ajax() - add query parameters to POST request?
To add query parameters to a url using jQuery AJAX, you do this:

```<code>$.ajax({
  url: 'www.some.url',
  method: 'GET',
  data: {
      param1: 'val1'
  }
)}
</code>```

Which results in a url like www.some.url?param1=val1

How do I do the same when the method is POST? When that is the case, data no longer gets appended as query parameters - it instead makes up the body of the request.

I know that I could manually append the params to the url manually before the ajax request, but I just have this nagging feeling that I'm missing some obvious way to do this that is shorter than the ~5 lines I'll need to execute before the ajax call.

答:
jQuery.param() allows you to serialize the properties of an object as a query string, which you could append to the URL yourself:</p>

```<code>$.ajax({
  url: 'http://www.example.com?' + $.param({ paramInQuery: 1 }),
  method: 'POST',
  data: {
    paramInBody: 2
  }
});
</code>```

Body:
To add query parameters to a url using jQuery AJAX, you do this:

$.ajax({
  url: 'www.some.url',
  method: 'GET',
  data: {
      param1: 'val1'
  }
)}

Which results in a url like www.some.url?param1=val1

How do I do the same when the method is POST? When that is the case, data no longer gets appended as query parameters - it instead makes up the body of the request.

I know that I could manually append the params to the url manually before the ajax request, but I just have this nagging feeling that I'm missing some obvious way to do this that is shorter than the ~5 lines I'll need to execute before the ajax call.

Body:
jQuery.param() allows you to serialize the properties of an object as a query string, which you could append to the URL yourself:

$.ajax({
  url: 'http://www.example.com?' + $.param({ paramInQuery: 1 }),
  method: 'POST',
  data: {
    paramInBody: 2
  }
});


问:
How to require many Lua strcip in Xcode
I have a problem when i require lua in xcode

there are two strcips:

in bar.lua:

```<code>bar =function()
    print("bar")
end
</code>```

in foo.lua:

```<code>require "bar"
bar()
</code>```

in xcode i write this code:

```<code>NSString * tagsString = @"bar,foo";
NSArray * tagsArray = [tagsString componentsSeparatedByString:@","];
for (NSString* luaFileName in tagsArray) {
    NSString *path = [[NSBundle mainBundle] pathForResource:luaFileName ofType:@"lua"];
    if (luaL_loadfile(_L, [path UTF8String])!=0){
        NSLog(@"luaL_loadfile error:%s",lua_tostring(_L, -1));
    }
    if (lua_pcall(_L, 0, 0, 0)!=0){
        NSLog(@"lua_pcall error？:%s",lua_tostring(_L, -1));
    }
}
</code>```

but it doesnot work:

```<code>lua_pcall error？:...on/2DD58CF6-044C-405C-885F-46B98BF6F355/0317.app/foo.lua:6: module 'bar' not found:
no field package.preload['bar']
no file '/usr/local/share/lua/5.3/bar.lua'
no file '/usr/local/share/lua/5.3/bar/init.lua'
no file '/usr/local/lib/lua/5.3/bar.lua'
no file '/usr/local/lib/lua/5.3/bar/init.lua'
no file './bar.lua'
no file './bar/init.lua'
no file '/usr/local/lib/lua/5.3/bar.so'
no file '/usr/local/lib/lua/5.3/loadall.so'
no file './bar.so'
</code>```

I'm pretty sure that ./bar.lua is exist

答:
i sloved this problem by this code:
NSString *appPath = [[NSBundle mainBundle] resourcePath]; [self runLuaCode:[NSString stringWithFormat:@"appPath = '%@/?.lua'",appPath]];</p>

Title: How to require many Lua strcip in Xcode

Body:
I have a problem when i require lua in xcode

there are two strcips:

in bar.lua:

bar =function()
    print("bar")
end

in foo.lua:

require "bar"
bar()

in xcode i write this code:

NSString * tagsString = @"bar,foo";
NSArray * tagsArray = [tagsString componentsSeparatedByString:@","];
for (NSString* luaFileName in tagsArray) {
    NSString *path = [[NSBundle mainBundle] pathForResource:luaFileName ofType:@"lua"];
    if (luaL_loadfile(_L, [path UTF8String])!=0){
        NSLog(@"luaL_loadfile error:%s",lua_tostring(_L, -1));
    }
    if (lua_pcall(_L, 0, 0, 0)!=0){
        NSLog(@"lua_pcall error？:%s",lua_tostring(_L, -1));
    }
}

but it doesnot work:

lua_pcall error？:...on/2DD58CF6-044C-405C-885F-46B98BF6F355/0317.app/foo.lua:6: module 'bar' not found:
no field package.preload['bar']
no file '/usr/local/share/lua/5.3/bar.lua'
no file '/usr/local/share/lua/5.3/bar/init.lua'
no file '/usr/local/lib/lua/5.3/bar.lua'
no file '/usr/local/lib/lua/5.3/bar/init.lua'
no file './bar.lua'
no file './bar/init.lua'
no file '/usr/local/lib/lua/5.3/bar.so'
no file '/usr/local/lib/lua/5.3/loadall.so'
no file './bar.so'

I'm pretty sure that ./bar.lua is exist


问:
Javascript: Nested Callbacks/MySQL Results
I am sure this is a basic question, but I have been searching google for awhile and can't find a satisfactory answer..

I am used to programming MySQL select queries in PHP and simply grabbing a result, looping through each row, and within the loop doing further queries based on the column values of each individual row.

However, I'm working with javascript server side code now that relies on a SQL object where you pass the query and then a callback function that will be invoked after the query is run.

I'm confused with some of the scoping issues and how to best cleanly do this. For example, I don't want to do something like:

```<code>SQL.query("select * from blah", function(result) {
  for(var i = 0; i < result.length; i++) {
    SQL.query("select * from blah2 where i =" + result[i].property, function(result2) {
      //now how do I access result from here? I know this isn't scoped correctly
    });
  }
});
</code>```

What is the standard way to write this style of nested SQL query and not have scoping issues/messy code? Thanks!

答:
result will be available in the second callback, that's how closures in JavaScript work, the functions has access to all variables in the outer scopes it was defined in.

```<code>function outer() {
    var foo = 1;
    function inner() { // inherits the scope of outer
        var bla = 2;
        console.log(foo); // works!

        // another function in here well inherit both the scope of inner AND outer, and so on
    }
    inner();
    console.log(bla); // doesn't work, raises "ReferenceError: bla is not defined"
}
outer();
</code>```

Now, on to the problem, i will not point to the correct value, it too will be inherited to the second callback but it`s a reference and will therefore has the wrong value.

Fix is to create another closure:

```<code>SQL.query("select * from blah", function(result) {
  for(var i = 0; i < result.length; i++) {
    (function(innerResult) { // anonymous function to provide yet another scope
        SQL.query("select * from blah2 where i =" + innerResult.property, function(result2) {
          // innerResult has the correct value
        });
    })(result[i]); // pass the current result into the function
  }
});
</code>```

Or an extra function:

```<code>function resultThingy(result) {
   SQL.query("select * from blah2 where i =" + result.property, function(result2) {
       // result has the correct value
   });
}

SQL.query("select * from blah", function(result) {
  for(var i = 0; i < result.length; i++) {
    resultThingy(result[i]);
  }
});
</code>```

Body:
I am sure this is a basic question, but I have been searching google for awhile and can't find a satisfactory answer..

I am used to programming MySQL select queries in PHP and simply grabbing a result, looping through each row, and within the loop doing further queries based on the column values of each individual row.

However, I'm working with javascript server side code now that relies on a SQL object where you pass the query and then a callback function that will be invoked after the query is run.

I'm confused with some of the scoping issues and how to best cleanly do this. For example, I don't want to do something like:

SQL.query("select * from blah", function(result) {
  for(var i = 0; i < result.length; i++) {
    SQL.query("select * from blah2 where i =" + result[i].property, function(result2) {
      //now how do I access result from here? I know this isn't scoped correctly
    });
  }
});

What is the standard way to write this style of nested SQL query and not have scoping issues/messy code? Thanks!

Body:
result will be available in the second callback, that's how closures in JavaScript work, the functions has access to all variables in the outer scopes it was defined in.

function outer() {
    var foo = 1;
    function inner() { // inherits the scope of outer
        var bla = 2;
        console.log(foo); // works!

        // another function in here well inherit both the scope of inner AND outer, and so on
    }
    inner();
    console.log(bla); // doesn't work, raises "ReferenceError: bla is not defined"
}
outer();

Now, on to the problem, i will not point to the correct value, it too will be inherited to the second callback but it`s a reference and will therefore has the wrong value.

Fix is to create another closure:

SQL.query("select * from blah", function(result) {
  for(var i = 0; i < result.length; i++) {
    (function(innerResult) { // anonymous function to provide yet another scope
        SQL.query("select * from blah2 where i =" + innerResult.property, function(result2) {
          // innerResult has the correct value
        });
    })(result[i]); // pass the current result into the function
  }
});

Or an extra function:

function resultThingy(result) {
   SQL.query("select * from blah2 where i =" + result.property, function(result2) {
       // result has the correct value
   });
}

SQL.query("select * from blah", function(result) {
  for(var i = 0; i < result.length; i++) {
    resultThingy(result[i]);
  }
});


问:
my iPhone app crashes and unable to restart on disabling camera access in Settings
It happens no matter I run it under release mode or debug mode. If it is due to the automatic shutdown by iOS, there should be a re-start. But my app is unable to do that.
the output on the console:
Message from debugger: Terminated due to signal 9

But I don't think disabling camera will cause a memory issue.
My Root.plist is like this:
screenshot of plist

However, if I choose "don't allow" at the popup when first launching, the app is running normally.

答:
Do you have code snippet? Or full error message?

Let me take a guess. In your code where you access the camera, you should check the camera permission before you just use it. I think that's where the problem would be. For how to do that, check [question]: Detect permission of camera in iOS But I might be wrong. need more info. And I also think you didn't correctly set your plist, you need to add following attributes in you plist.

Photo :

```<code>Key: Privacy - Photo Library Usage Description
Value: $(PRODUCT_NAME) photo use
</code>```

Microphone :

```<code>Key: Privacy - Microphone Usage Description
Value: $(PRODUCT_NAME) microphone use
</code>```

Camera :

```<code>Key: Privacy - Camera Usage Description
Value: $(PRODUCT_NAME) camera use
</code>```

And one more thing, when you encounter a crash or any weird behavior, look for its reason, look into its log, look deeply into its err message. search for the error code, put exception breakpoints to find exactly where the crash happens, etc. And then, post questions related to how you cannot solve those materials/experiments you went through. That is more effective than just agonize yourself over the app behavior.

Body:
Do you have code snippet? Or full error message?

Let me take a guess. In your code where you access the camera, you should check the camera permission before you just use it. I think that's where the problem would be. For how to do that, check [question]: Detect permission of camera in iOS But I might be wrong. need more info. And I also think you didn't correctly set your plist, you need to add following attributes in you plist.

Photo :

Key: Privacy - Photo Library Usage Description
Value: $(PRODUCT_NAME) photo use

Microphone :

Key: Privacy - Microphone Usage Description
Value: $(PRODUCT_NAME) microphone use

Camera :

Key: Privacy - Camera Usage Description
Value: $(PRODUCT_NAME) camera use

And one more thing, when you encounter a crash or any weird behavior, look for its reason, look into its log, look deeply into its err message. search for the error code, put exception breakpoints to find exactly where the crash happens, etc. And then, post questions related to how you cannot solve those materials/experiments you went through. That is more effective than just agonize yourself over the app behavior.