问:
Failed to install zbar with pip on Windows
I'm trying to install zbar on my Windows x64 machine:

```<code>pip install zbar
</code>```

And this is what I got:

```<code>Collecting zbar
Using cached zbar-0.10.tar.bz2
Installing collected packages: zbar
Running setup.py install for zbar ... error
Complete output from command c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\ruiyang\\appdata\\local\\temp\\pip-build-t2okcg\\zbar\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record c:\users\ruiyang\appdata\local\temp\pip-4pohzw-record\install-record.txt --single-version-externally-managed --compile:
running install
running build
running build_ext
building 'zbar' extension
creating build
creating build\temp.win-amd64-2.7
creating build\temp.win-amd64-2.7\Release
C:\Users\Ruiyang\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Python27\include -IC:\Python27\PC /Tczbarmodule.c /Fobuild\temp.win-amd64-2.7\Release\zbarmodule.obj
zbarmodule.c
c:\users\ruiyang\appdata\local\temp\pip-build-t2okcg\zbar\zbarmodule.h(26) : fatal error C1083: Cannot open include file: 'zbar.h': No such file or directory
error: command 'C:\\Users\\Ruiyang\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2

----------------------------------------
Command "c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\ruiyang\\appdata\\local\\temp\\pip-build-t2okcg\\zbar\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record c:\users\ruiyang\appdata\local\temp\pip-4pohzw-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\users\ruiyang\appdata\local\temp\pip-build-t2okcg\zbar\
</code>```

Anyone knows how to fix this problem?

答:
You are trying to install zbar package with pip. When doing so, pip downloads the source and tries to compile the C/C++ source code of this project.

To do such a thing, you need a C/C++ compiler and having all dependencies. It may be complicated to have pip compiles this package.

The other solution is to download a binary wheel that embeds all binaries. zbar developers propose to download a binary wheel from their GitHub webpage

You can download this binary wheel, that targets a Windows Python 2.7 64 bit installation.

All you have to do is:

open a Windows cli with Windows+R and by running inside cmd

go to the directory where you have downloaded the whl file, with cd instructions

run pip install zbar-0.10-cp27-none-win_amd64.whl

For example, the command can be

```<code>pip install zbar-0.10-cp27-none-win_amd64.whl
</code>```

If you have several Python installations, make sure to use the correct pip program.

You can do it for any package with some code that has to be compiled

Body:
I'm trying to install zbar on my Windows x64 machine:

pip install zbar

And this is what I got:

Collecting zbar
Using cached zbar-0.10.tar.bz2
Installing collected packages: zbar
Running setup.py install for zbar ... error
Complete output from command c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\ruiyang\\appdata\\local\\temp\\pip-build-t2okcg\\zbar\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record c:\users\ruiyang\appdata\local\temp\pip-4pohzw-record\install-record.txt --single-version-externally-managed --compile:
running install
running build
running build_ext
building 'zbar' extension
creating build
creating build\temp.win-amd64-2.7
creating build\temp.win-amd64-2.7\Release
C:\Users\Ruiyang\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Python27\include -IC:\Python27\PC /Tczbarmodule.c /Fobuild\temp.win-amd64-2.7\Release\zbarmodule.obj
zbarmodule.c
c:\users\ruiyang\appdata\local\temp\pip-build-t2okcg\zbar\zbarmodule.h(26) : fatal error C1083: Cannot open include file: 'zbar.h': No such file or directory
error: command 'C:\\Users\\Ruiyang\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2

----------------------------------------
Command "c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\ruiyang\\appdata\\local\\temp\\pip-build-t2okcg\\zbar\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record c:\users\ruiyang\appdata\local\temp\pip-4pohzw-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\users\ruiyang\appdata\local\temp\pip-build-t2okcg\zbar\

Anyone knows how to fix this problem?

Body:
You are trying to install zbar package with pip. When doing so, pip downloads the source and tries to compile the C/C++ source code of this project.

To do such a thing, you need a C/C++ compiler and having all dependencies. It may be complicated to have pip compiles this package.

The other solution is to download a binary wheel that embeds all binaries. zbar developers propose to download a binary wheel from their GitHub webpage

You can download this binary wheel, that targets a Windows Python 2.7 64 bit installation.

All you have to do is:

open a Windows cli with Windows+R and by running inside cmd

go to the directory where you have downloaded the whl file, with cd instructions

run pip install zbar-0.10-cp27-none-win_amd64.whl

For example, the command can be

pip install zbar-0.10-cp27-none-win_amd64.whl

If you have several Python installations, make sure to use the correct pip program.

You can do it for any package with some code that has to be compiled


来源: stackexchange

问:
Remove a package from laravel
I installed this Cartalyst Stripe package for laravel which was nothing but trouble for me.. I just couldn't get it working and now I decided to remove it completely.
So, I remove the line that requires this package in composer.json.
I removed the line from confing/app.php from the providers & aliases array. I also removed all references of that Cartalyst package from my code..
Somehow, after I run composer update I still get this error..

```<code>  [Symfony\Component\Debug\Exception\FatalThrowableError]
  Class 'Cartalyst\Stripe\Laravel\StripeServiceProvider' not found

Script php artisan optimize handling the post-update-cmd event returned with error code 1
</code>```

What am I missing here?

答:
You need to clear config cache. Run php artisan config:clear command to fix this.

If you still see the error message when you run the artisan commands, clear the bootstrap/cache directory manually.

ContentLicense: CC BY-SA 3.0

Title: Remove a package from laravel

Body:
I installed this Cartalyst Stripe package for laravel which was nothing but trouble for me.. I just couldn't get it working and now I decided to remove it completely.
So, I remove the line that requires this package in composer.json.
I removed the line from confing/app.php from the providers & aliases array. I also removed all references of that Cartalyst package from my code..
Somehow, after I run composer update I still get this error..

  [Symfony\Component\Debug\Exception\FatalThrowableError]
  Class 'Cartalyst\Stripe\Laravel\StripeServiceProvider' not found

Script php artisan optimize handling the post-update-cmd event returned with error code 1

What am I missing here?


问:
mongodb 3.4.3 Permission denied wiredtiger_kv_engine.cpp 267 error with ubuntu 16
I'm having problems lauching mongod as a service:
How is it possible that it works when I do sudo mongod -f /etc/mongod.conf but when launching it with sudo service mongod start I get an error in the log

Assertion: 28595:13: Permission denied src/mongo/db/storage/wiredtiger/wiredtiger_kv_engine.cpp 267

I'm running mongodb on ubuntu 16

I followed exactly the instructions in the mongodb documentation for installation of that version, so is this a bug? Any suggestions how to solve this are appreciated.

Additional information:

The mongodb service startup script looks like this and runs it as user mongodb, could this be connected to the error?
lib/systemd/system/mongodb.service:

```<code>[Unit]
Description=MongoDB Database Service
Wants=network.target
After=network.target

[Service]
ExecStart=/usr/bin/mongod --config /etc/mongod.conf
ExecReload=/bin/kill -HUP $MAINPID
Restart=always
User=mongodb
Group=mongodb
StandardOutput=syslog
StandardError=syslog

[Install]
WantedBy=multi-user.target
</code>```

答:
I'm having problems lauching mongod as a service: How is it possible that it works when I do sudo mongod -f /etc/mongod.conf but when launching it with sudo service mongod start I get an error in the log

The sudo command starts mongod with root permissions (aka superuser access). If you run mongod as a service the user and group are configured in the service definition (mongodb for both in your example).

There is no need to run the mongod process as the root user, and this is strongly discouraged as per the common security practice of Principle of least privilege.

If you want to test a configuration from the command-line, you could use sudo to run with a specified user instead of the default (root) user.

For example:

```<code>sudo -u mongodb mongod -f /etc/mongod.conf
</code>```

In general, it's best to use a service configuration rather than running mongod manually. With manual invocation you will also have to remember to include parameters like the config file path (as there is no default config path). Without a configuration file, mongod also uses default options such as a dbPath of /data/db.

Assertion: 28595:13: Permission denied src/mongo/db/storage/wiredtiger/wiredtiger_kv_engine.cpp 267

The likely cause of your permission errors is having previously started mongod as the root user. Some directories and files may now be owned by the root user, so the  mongodb user cannot access those. Your specific error relates to accessing files in the data directory (i.e. the configured storage.dbPath in mongod.conf).

Assuming you haven't changed the default paths in your mongod.conf file, you should be able to recursively adjust permissions to match what the mongod.service definition expects.

First, ensure you have stopped your mongod instance if it is currently running.

Then, recursively adjust permissions to the expected user and group:

```<code># storage.dbPath
sudo chown -R mongodb:mongodb /var/lib/mongodb

# systemLog.path
sudo chown -R mongodb:mongodb /var/log/mongodb
</code>```

Now you should be able to start mongod as a service. If the service fails to start, there should be further detail in the mongod log file (assuming the log file is writable by the mongodb service user).

Body:
I'm having problems lauching mongod as a service:
How is it possible that it works when I do sudo mongod -f /etc/mongod.conf but when launching it with sudo service mongod start I get an error in the log

Assertion: 28595:13: Permission denied src/mongo/db/storage/wiredtiger/wiredtiger_kv_engine.cpp 267

I'm running mongodb on ubuntu 16

I followed exactly the instructions in the mongodb documentation for installation of that version, so is this a bug? Any suggestions how to solve this are appreciated.

Additional information:

The mongodb service startup script looks like this and runs it as user mongodb, could this be connected to the error?
lib/systemd/system/mongodb.service:

[Unit]
Description=MongoDB Database Service
Wants=network.target
After=network.target

[Service]
ExecStart=/usr/bin/mongod --config /etc/mongod.conf
ExecReload=/bin/kill -HUP $MAINPID
Restart=always
User=mongodb
Group=mongodb
StandardOutput=syslog
StandardError=syslog

[Install]
WantedBy=multi-user.target

Body:
I'm having problems lauching mongod as a service: How is it possible that it works when I do sudo mongod -f /etc/mongod.conf but when launching it with sudo service mongod start I get an error in the log

The sudo command starts mongod with root permissions (aka superuser access). If you run mongod as a service the user and group are configured in the service definition (mongodb for both in your example).

There is no need to run the mongod process as the root user, and this is strongly discouraged as per the common security practice of Principle of least privilege.

If you want to test a configuration from the command-line, you could use sudo to run with a specified user instead of the default (root) user.

For example:

sudo -u mongodb mongod -f /etc/mongod.conf

In general, it's best to use a service configuration rather than running mongod manually. With manual invocation you will also have to remember to include parameters like the config file path (as there is no default config path). Without a configuration file, mongod also uses default options such as a dbPath of /data/db.

Assertion: 28595:13: Permission denied src/mongo/db/storage/wiredtiger/wiredtiger_kv_engine.cpp 267

The likely cause of your permission errors is having previously started mongod as the root user. Some directories and files may now be owned by the root user, so the  mongodb user cannot access those. Your specific error relates to accessing files in the data directory (i.e. the configured storage.dbPath in mongod.conf).

Assuming you haven't changed the default paths in your mongod.conf file, you should be able to recursively adjust permissions to match what the mongod.service definition expects.

First, ensure you have stopped your mongod instance if it is currently running.

Then, recursively adjust permissions to the expected user and group:

# storage.dbPath
sudo chown -R mongodb:mongodb /var/lib/mongodb

# systemLog.path
sudo chown -R mongodb:mongodb /var/log/mongodb

Now you should be able to start mongod as a service. If the service fails to start, there should be further detail in the mongod log file (assuming the log file is writable by the mongodb service user).


问:
How to initialize secondary/other datasources programatically without reading application.properties
I have a developed a multi-tenancy spring boot application where in the datasources are initialized via database credentials stored in application.properties as shown below :

application.properties

```<code>spring.multitenancy.datasource1.url=jdbc:mysql://localhost:3306/db1
spring.multitenancy.datasource1.username=root
spring.multitenancy.datasource1.password=****
spring.multitenancy.datasource1.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update

spring.multitenancy.datasource2.url=jdbc:mysql://localhost:3306/db2
spring.multitenancy.datasource2.username=root
spring.multitenancy.datasource2.password=****
spring.multitenancy.datasource2.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update

spring.multitenancy.datasource3.url=jdbc:mysql://localhost:3306/db3
spring.multitenancy.datasource3.username=root
spring.multitenancy.datasource3.password=****
spring.multitenancy.datasource3.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
</code>```

DataSourceConfig.java

```<code>@Configuration
public class DataSourceConfig {

    @Autowired
    private MultitenancyProperties multitenancyProperties;

    @Bean(name = { "dataSource", "dataSource1" })
    @ConfigurationProperties(prefix = "spring.multitenancy.datasource1")
    public DataSource dataSource1() {
        DataSourceBuilder factory = DataSourceBuilder
                .create(this.multitenancyProperties.getDatasource1().getClassLoader())
                .driverClassName(this.multitenancyProperties.getDatasource1().getDriverClassName())
                .username(this.multitenancyProperties.getDatasource1().getUsername())
                .password(this.multitenancyProperties.getDatasource1().getPassword())
                .url(this.multitenancyProperties.getDatasource1().getUrl());
        return factory.build();
    }

    @Bean(name = "dataSource2")
    @ConfigurationProperties(prefix = "spring.multitenancy.datasource2")
    public DataSource dataSource2() {
        DataSourceBuilder factory = DataSourceBuilder
                .create(this.multitenancyProperties.getDatasource2().getClassLoader())
                .driverClassName(this.multitenancyProperties.getDatasource2().getDriverClassName())
                .username(this.multitenancyProperties.getDatasource2().getUsername())
                .password(this.multitenancyProperties.getDatasource2().getPassword())
                .url(this.multitenancyProperties.getDatasource2().getUrl());
        return factory.build();
    }

    @Bean(name = "dataSource3")
    @ConfigurationProperties(prefix = "spring.multitenancy.datasource3")
    public DataSource dataSource3() {
        DataSourceBuilder factory = DataSourceBuilder
                .create(this.multitenancyProperties.getDatasource3().getClassLoader())
                .driverClassName(this.multitenancyProperties.getDatasource3().getDriverClassName())
                .username(this.multitenancyProperties.getDatasource3().getUsername())
                .password(this.multitenancyProperties.getDatasource3().getPassword())
                .url(this.multitenancyProperties.getDatasource3().getUrl());
        return factory.build();
    }
}
</code>```

Here, data sources are initialized via values stored in application properties.

MultitenancyProperties.java

```<code>@ConfigurationProperties("spring.multitenancy")
public class MultitenancyProperties {

    @NestedConfigurationProperty
    private DataSourceProperties datasource1;

    @NestedConfigurationProperty
    private DataSourceProperties datasource2;

    @NestedConfigurationProperty
    private DataSourceProperties datasource3;

    public DataSourceProperties getDatasource1() {
        return datasource1;
    }

    public void setDatasource1(DataSourceProperties datasource1) {
        this.datasource1 = datasource1;
    }

    public DataSourceProperties getDatasource2() {
        return datasource2;
    }

    public void setDatasource2(DataSourceProperties datasource2) {
        this.datasource2 = datasource2;
    }

    public DataSourceProperties getDatasource3() {
        return datasource3;
    }

    public void setDatasource3(DataSourceProperties datasource3) {
        this.datasource3 = datasource3;
    }
}
</code>```

Spring boot application launcher

```<code>@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableConfigurationProperties(MultitenancyProperties.class)
public class Application {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
    }
}
</code>```

How to initialize only primary datasource by reading the application.properties and other datasources(dataSource2,dataSource3) programatically by reading the database credentials stored in a table of primary datasource.

答:
First you could import commons-dbcp2.jar,then you could create a org.apache.commons.dbcp.BasicDataSource,eg,

```<code> BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUrl("jdbc:mysql://localhost:3306/housesearch");
    ds.setUsername("root");
    ds.setPassword("");
    ds.setInitialSize(50);
    ds.setMaxIdle(30);
    Connection connection = ds.getConnection();
    Statement statement = connection.createStatement();
    ResultSet resultSet = statement.executeQuery("select * from pay_info");
    if(resultSet.next()){
        System.out.println(resultSet.getInt(5));
    }
    connection.close();
    ds.close();
</code>```

The driverClassName, url, password and other properties can be stored in a table.

I wish my answer could help you.

Body:
I have a developed a multi-tenancy spring boot application where in the datasources are initialized via database credentials stored in application.properties as shown below :

application.properties

spring.multitenancy.datasource1.url=jdbc:mysql://localhost:3306/db1
spring.multitenancy.datasource1.username=root
spring.multitenancy.datasource1.password=****
spring.multitenancy.datasource1.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update

spring.multitenancy.datasource2.url=jdbc:mysql://localhost:3306/db2
spring.multitenancy.datasource2.username=root
spring.multitenancy.datasource2.password=****
spring.multitenancy.datasource2.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update

spring.multitenancy.datasource3.url=jdbc:mysql://localhost:3306/db3
spring.multitenancy.datasource3.username=root
spring.multitenancy.datasource3.password=****
spring.multitenancy.datasource3.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update

DataSourceConfig.java

@Configuration
public class DataSourceConfig {

    @Autowired
    private MultitenancyProperties multitenancyProperties;

    @Bean(name = { "dataSource", "dataSource1" })
    @ConfigurationProperties(prefix = "spring.multitenancy.datasource1")
    public DataSource dataSource1() {
        DataSourceBuilder factory = DataSourceBuilder
                .create(this.multitenancyProperties.getDatasource1().getClassLoader())
                .driverClassName(this.multitenancyProperties.getDatasource1().getDriverClassName())
                .username(this.multitenancyProperties.getDatasource1().getUsername())
                .password(this.multitenancyProperties.getDatasource1().getPassword())
                .url(this.multitenancyProperties.getDatasource1().getUrl());
        return factory.build();
    }

    @Bean(name = "dataSource2")
    @ConfigurationProperties(prefix = "spring.multitenancy.datasource2")
    public DataSource dataSource2() {
        DataSourceBuilder factory = DataSourceBuilder
                .create(this.multitenancyProperties.getDatasource2().getClassLoader())
                .driverClassName(this.multitenancyProperties.getDatasource2().getDriverClassName())
                .username(this.multitenancyProperties.getDatasource2().getUsername())
                .password(this.multitenancyProperties.getDatasource2().getPassword())
                .url(this.multitenancyProperties.getDatasource2().getUrl());
        return factory.build();
    }

    @Bean(name = "dataSource3")
    @ConfigurationProperties(prefix = "spring.multitenancy.datasource3")
    public DataSource dataSource3() {
        DataSourceBuilder factory = DataSourceBuilder
                .create(this.multitenancyProperties.getDatasource3().getClassLoader())
                .driverClassName(this.multitenancyProperties.getDatasource3().getDriverClassName())
                .username(this.multitenancyProperties.getDatasource3().getUsername())
                .password(this.multitenancyProperties.getDatasource3().getPassword())
                .url(this.multitenancyProperties.getDatasource3().getUrl());
        return factory.build();
    }
}

Here, data sources are initialized via values stored in application properties.

MultitenancyProperties.java

@ConfigurationProperties("spring.multitenancy")
public class MultitenancyProperties {

    @NestedConfigurationProperty
    private DataSourceProperties datasource1;

    @NestedConfigurationProperty
    private DataSourceProperties datasource2;

    @NestedConfigurationProperty
    private DataSourceProperties datasource3;

    public DataSourceProperties getDatasource1() {
        return datasource1;
    }

    public void setDatasource1(DataSourceProperties datasource1) {
        this.datasource1 = datasource1;
    }

    public DataSourceProperties getDatasource2() {
        return datasource2;
    }

    public void setDatasource2(DataSourceProperties datasource2) {
        this.datasource2 = datasource2;
    }

    public DataSourceProperties getDatasource3() {
        return datasource3;
    }

    public void setDatasource3(DataSourceProperties datasource3) {
        this.datasource3 = datasource3;
    }
}

Spring boot application launcher

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableConfigurationProperties(MultitenancyProperties.class)
public class Application {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
    }
}

How to initialize only primary datasource by reading the application.properties and other datasources(dataSource2,dataSource3) programatically by reading the database credentials stored in a table of primary datasource.

Body:
First you could import commons-dbcp2.jar,then you could create a org.apache.commons.dbcp.BasicDataSource,eg,

 BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUrl("jdbc:mysql://localhost:3306/housesearch");
    ds.setUsername("root");
    ds.setPassword("");
    ds.setInitialSize(50);
    ds.setMaxIdle(30);
    Connection connection = ds.getConnection();
    Statement statement = connection.createStatement();
    ResultSet resultSet = statement.executeQuery("select * from pay_info");
    if(resultSet.next()){
        System.out.println(resultSet.getInt(5));
    }
    connection.close();
    ds.close();

The driverClassName, url, password and other properties can be stored in a table.

I wish my answer could help you.


问:
htmlunit : checkbox not getting checked
I am using HtmlUnit for setting a checkbox in a page. Html code for checkbox is :

```<code><input id="Checkbox" type="checkbox"  name="Checkbox" style="color:Black;"/>
</code>```

My java code to set checkbox is :

```<code>HtmlCheckBoxInput checkBox = page.getHtmlElementById("Checkbox");
checkBox.setChecked(true);

FileUtils.writeStringToFile(new File("src/test/page-dumps/page-3.html"),page.asXml(),"UTF-8");
</code>```

When I open page-3.html in my browse, ckeckbox is unchecked. Why is it not checked?

答:
Well, it is not checked because real browsers don't add an attribute.

Test the below with real browser:

  <input type=checkbox id=myid>

```

<p>There is an alert of</p>

<pre class="lang-html prettyprint-override"><code><input type="checkbox" id="myid">
</code>```

without any checked attribute.

You should instead use:

```<code>checkBox.setAttribute("checked", "checked");
</code>```

ContentLicense: CC BY-SA 4.0

Title: htmlunit : checkbox not getting checked

Body:
I am using HtmlUnit for setting a checkbox in a page. Html code for checkbox is :

<input id="Checkbox" type="checkbox"  name="Checkbox" style="color:Black;"/>

My java code to set checkbox is :

HtmlCheckBoxInput checkBox = page.getHtmlElementById("Checkbox");
checkBox.setChecked(true);

FileUtils.writeStringToFile(new File("src/test/page-dumps/page-3.html"),page.asXml(),"UTF-8");

When I open page-3.html in my browse, ckeckbox is unchecked. Why is it not checked?

Body:
Well, it is not checked because real browsers don't add an attribute.

Test the below with real browser:

<html><head>
<script>
  function test() {
    var e = document.getElementById('myid');
    e.checked = true;
    alert(e.outerHTML);
  }
</script>
</head><body onload="test()">
  <input type=checkbox id=myid>
</body></html>

There is an alert of

<input type="checkbox" id="myid">

without any checked attribute.

You should instead use:

checkBox.setAttribute("checked", "checked");


问:
type checking in javascript
How can I check if a variable is currently an integer type?  I've looked for some sort of resource for this and I think the === operator is important, but I'm not sure how to check if a variable is an Integer (or an Array for that matter)</p>

答:
You may also have a look on Runtyper - a tool that performs type checking of operands in === (and other operations).

For your example, if you have strict comparison x === y and x = 123, y = "123", it will automatically check typeof x, typeof y and show warning in console:

Strict compare of different types: 123 (number) === "123" (string)

ContentLicense: CC BY-SA 2.5

Title: type checking in javascript


问:
Creating a list of lists from round robin not using a recipe
I am new to python and trying to learn how to round robin of a list into a list of lists. I saw posts with answers pointing to a standard round robin recipe, but I don't understand some of the concepts in it and would prefer a simpler solution.

I want to achieve something like this using a function, but I haven't been able to come close:

```<code>MYLIST = ['apples', 'oranges', 'bananas', 'grapes', 'strawberries', 'pears']
>>>myfunc(MYLIST)
[['apples', 'grapes'], ['oranges', 'strawberries'], ['bananas', 'pears']]
</code>```

I'm very confused after attempting to solve this problem using a combination of for loops, while loops and if statements. Nothing I did worked.

I don't have any code that works or comes close to working. Any help would be appreciated. Thanks.

答:
since  you're new to python and you said that "Nothing I did worked." I guess you might not know that you can't pass some parameters to a function and make global effects inside the function.

here's a sample of what I'm saying

```<code>>>> def f(a):
       a = [0,1,2,3]

>>> t = [0,0,0,0]
>>> f(t)
>>> t
[0,0,0,0]
</code>```

how ever working with items of a list is ok

```<code>>>> def f(a):
        a[0] = 0
        a[1] = 1
        a[2] = 2
        a[3] = 3
>>> t = [0,0,0,0]
>>> f(t)
>>> t
[0,1,2,3]
</code>```

also another solution is to return the result

```<code>>>> def f(a):
       a = [0,1,2,3]
       return a

>>> t = [0,0,0,0]
>>> t = f(t)
>>> t
[0,1,2,3]
</code>```

Body:
I am new to python and trying to learn how to round robin of a list into a list of lists. I saw posts with answers pointing to a standard round robin recipe, but I don't understand some of the concepts in it and would prefer a simpler solution.

I want to achieve something like this using a function, but I haven't been able to come close:

MYLIST = ['apples', 'oranges', 'bananas', 'grapes', 'strawberries', 'pears']
>>>myfunc(MYLIST)
[['apples', 'grapes'], ['oranges', 'strawberries'], ['bananas', 'pears']]

I'm very confused after attempting to solve this problem using a combination of for loops, while loops and if statements. Nothing I did worked.

I don't have any code that works or comes close to working. Any help would be appreciated. Thanks.

Body:
since  you're new to python and you said that "Nothing I did worked." I guess you might not know that you can't pass some parameters to a function and make global effects inside the function.

here's a sample of what I'm saying

>>> def f(a):
       a = [0,1,2,3]

>>> t = [0,0,0,0]
>>> f(t)
>>> t
[0,0,0,0]

how ever working with items of a list is ok

>>> def f(a):
        a[0] = 0
        a[1] = 1
        a[2] = 2
        a[3] = 3
>>> t = [0,0,0,0]
>>> f(t)
>>> t
[0,1,2,3]

also another solution is to return the result

>>> def f(a):
       a = [0,1,2,3]
       return a

>>> t = [0,0,0,0]
>>> t = f(t)
>>> t
[0,1,2,3]


问:
How to automatically import external images on blogspot
i have a blogspot. I'm always copy images from other blogs. And i only have method : save it (image) to my computer and upload it in blogger editor.

I see the wordpress have plugin automatically import external images to library (host on wordpress). Now I want a way to do it with blogspot. When i click Post in Post Editor : All external images automatically upload to blogger and hosted on google such as url:

https://lh4.googleusercontent.com/-kFISeyzwNp0/WG9xA1aUrsI/AAAAAAAAAeA/ITMC__2wl6YkP_01LnbdOyIpVj_7s6i4wCLcB/s1600/b1.jpg

I wonder google API can do this ? Or creating a tool in hosting can do it ?

答: Sorry But blogger has its own limitations..Its not possible on blogger/blogspot platform.. you have to do it manually!</p>


问:
Unable to modify the properties of objects within an IEnumerable<T>
I am having a problem making changes to the properties of objects in an IEnumerable collection.  I pass the collection to another method to remove duplicate information across the entities within the collection.  This works within the method but once the method is done executing and returns to the caller the changes are lost. However, if I convert the IEnumerable to a list it works as expected.  My only guess is that because when I call ToList it becomes a concrete type and that allows it to work, but that shouldn't be a limitation, right?

Also it is worth nothing that this isn't in the context of deferred execution.
This ended up not being true, the compiler was rewriting the RetrieveTrackingFilters method to take advantage of deferred execution

This is the trimmed down code:

```<code>public IEnumerable<TrackingFilter> RetrieveTrackingFilters(string proNumber)
{
    var trackingFilters = new EntityCollection<TrackingOverviewFilterEntity>(new TrackingOverviewFilterEntityFactory());

    var filter = new RelationPredicateBucket();
    filter.Relations.Add(TrackingOverviewFilterEntity.Relations.TrackingOverviewEntityUsingTrackingOverviewId);
    filter.PredicateExpression.Add(TrackingOverviewFields.ProNumber == proNumber);

    DataAccessAdapterFactory.Instance().FetchEntityCollection(trackingFilters, filter);

    return BuildTrackingFilterColl(trackingFilters); //Just news up a DTO object and populates it
}

public TrackingSummaryViewModel RetrieveTrackingSummary(string proNumber)
{
    ...
    var trackingFilters = this._TrackingOverviewDataController.RetrieveTrackingFilters(proNumber).ToList(); //Works
    //var trackingFilters = this._TrackingOverviewDataController.RetrieveTrackingFilters(proNumber); //Doesn't work

    RemoveDuplicateFilterData(trackingFilters); //If I don't do a ToList() then the changes that occur in this method call do not persist
    ...
}

private static void RemoveDuplicateFilterData(IEnumerable<TrackingFilter> filters)
{
    var valuePairs = new Dictionary<string, IList<object>>();

    foreach (var filter in filters)
    {
        if (valuePairs.ContainsKey("comments") && valuePairs["comments"].Contains(filter.Comments))
        {
            filter.Comments = string.Empty;
        }
        else if (!string.IsNullOrWhiteSpace(filter.Comments))
        {
            if (!valuePairs.ContainsKey("comments"))
            {
                valuePairs.Add("comments", new List<object>());
            }

            valuePairs["comments"].Add(filter.Comments);
        }
    }

    ...
}
</code>```

答:
If your RetrieveTrackingFilters(proNumber) returns an IQueryable, then this would cause new objects to be created each time you enumerate it: once within RemoveDuplicateFilterData (the changes there would then be lost) and once when you do something with it later in RetrieveTrackingSummary (a fresh, untouched copy would be provided at this point).

Try changing .ToList() to .AsEnumerable(). It should still work the same.

Body:
I am having a problem making changes to the properties of objects in an IEnumerable collection.  I pass the collection to another method to remove duplicate information across the entities within the collection.  This works within the method but once the method is done executing and returns to the caller the changes are lost. However, if I convert the IEnumerable to a list it works as expected.  My only guess is that because when I call ToList it becomes a concrete type and that allows it to work, but that shouldn't be a limitation, right?

Also it is worth nothing that this isn't in the context of deferred execution.
This ended up not being true, the compiler was rewriting the RetrieveTrackingFilters method to take advantage of deferred execution

This is the trimmed down code:

public IEnumerable<TrackingFilter> RetrieveTrackingFilters(string proNumber)
{
    var trackingFilters = new EntityCollection<TrackingOverviewFilterEntity>(new TrackingOverviewFilterEntityFactory());

    var filter = new RelationPredicateBucket();
    filter.Relations.Add(TrackingOverviewFilterEntity.Relations.TrackingOverviewEntityUsingTrackingOverviewId);
    filter.PredicateExpression.Add(TrackingOverviewFields.ProNumber == proNumber);

    DataAccessAdapterFactory.Instance().FetchEntityCollection(trackingFilters, filter);

    return BuildTrackingFilterColl(trackingFilters); //Just news up a DTO object and populates it
}

public TrackingSummaryViewModel RetrieveTrackingSummary(string proNumber)
{
    ...
    var trackingFilters = this._TrackingOverviewDataController.RetrieveTrackingFilters(proNumber).ToList(); //Works
    //var trackingFilters = this._TrackingOverviewDataController.RetrieveTrackingFilters(proNumber); //Doesn't work

    RemoveDuplicateFilterData(trackingFilters); //If I don't do a ToList() then the changes that occur in this method call do not persist
    ...
}

private static void RemoveDuplicateFilterData(IEnumerable<TrackingFilter> filters)
{
    var valuePairs = new Dictionary<string, IList<object>>();

    foreach (var filter in filters)
    {
        if (valuePairs.ContainsKey("comments") && valuePairs["comments"].Contains(filter.Comments))
        {
            filter.Comments = string.Empty;
        }
        else if (!string.IsNullOrWhiteSpace(filter.Comments))
        {
            if (!valuePairs.ContainsKey("comments"))
            {
                valuePairs.Add("comments", new List<object>());
            }

            valuePairs["comments"].Add(filter.Comments);
        }
    }

    ...
}


问:
How to delete all records from table in sqlite with Android?
My app has two buttons, the first button is for deleting record on user input and the second button is for deleting all records. But when I want to delete data it shows the message

"Your application has been forcefully stopped".

Please check my code and give me some suggestion.

```<code>public void deleteAll()
{
    //SQLiteDatabase db = this.getWritableDatabase();
   // db.delete(TABLE_NAME,null,null);
    //db.execSQL("delete * from"+ TABLE_NAME);
    db.execSQL("TRUNCATE table" + TABLE_NAME);
    db.close();
}
</code>```

and

```<code>public void delete(String id)
{
    String[] args={id};
    getWritableDatabase().delete("texts", "_ID=?", args);
}
</code>```

But it shows the following Log cat error.

```<code>03-07 15:57:07.143: ERROR/AndroidRuntime(287): Uncaught handler: thread main exiting due to uncaught exception
03-07 15:57:07.153: ERROR/AndroidRuntime(287): java.lang.NullPointerException
03-07 15:57:07.153: ERROR/AndroidRuntime(287):     at com.example.MySQLiteHelper.delete(MySQLiteHelper.java:163)
03-07 15:57:07.153: ERROR/AndroidRuntime(287):     at com.example.Settings$4.onClick(Settings.java:94)
-07 15:57:07.153: ERROR/AndroidRuntime(287):     at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:158)
03-07 15:57:07.153: ERROR/AndroidRuntime(287):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-07 15:57:07.153: ERROR/AndroidRuntime(287):     at android.os.Looper.loop(Looper.java:123)
03-07 15:57:07.153: ERROR/AndroidRuntime(287):     at android.app.ActivityThread.main(ActivityThread.java:4203)
03-07 15:57:07.153: ERROR/AndroidRuntime(287):     at java.lang.reflect.Method.invokeNative(Native Method)
03-07 15:57:07.153: ERROR/AndroidRuntime(287):     at java.lang.reflect.Method.invoke(Method.java:521)
03-07 15:57:07.153: ERROR/AndroidRuntime(287):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
03-07 15:57:07.153: ERROR/AndroidRuntime(287):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
03-07 15:57:07.153: ERROR/AndroidRuntime(287):     at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
I use this class to handle database.I hope it will help some one in future.

Happy coding.

```<code>public class Database {

private static class DBHelper extends SQLiteOpenHelper {

    /**
     * Database name
     */
    private static final String DB_NAME = "db_name";

    /**
     * Table Names
     */
    public static final String TABLE_CART = "DB_CART";

    /**
     *  Cart Table Columns
     */
    public static final String CART_ID_PK = "_id";// Primary key

    public static final String CART_DISH_NAME = "dish_name";
    public static final String CART_DISH_ID = "menu_item_id";
    public static final String CART_DISH_QTY = "dish_qty";
    public static final String CART_DISH_PRICE = "dish_price";

    /**
     * String to create reservation tabs table
     */
    private final String CREATE_TABLE_CART = "CREATE TABLE IF NOT EXISTS "
            + TABLE_CART + " ( "
            + CART_ID_PK + " INTEGER PRIMARY KEY, "
            + CART_DISH_NAME + " TEXT , "
            + CART_DISH_ID + " TEXT , "
            + CART_DISH_QTY + " TEXT , "
            + CART_DISH_PRICE + " TEXT);";

    public DBHelper(Context context) {
        super(context, DB_NAME, null, 2);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_CART);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
        db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_CART);
        onCreate(db);
    }

}

     /**
      * CART handler
      */
      public static class Cart {

    /**
     * Check if Cart is available or not
     *
     * @param context
     * @return
     */
    public static boolean isCartAvailable(Context context) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        boolean exists = false;

        try {
            String query = "SELECT * FROM " + DBHelper.TABLE_CART;
            Cursor cursor = db.rawQuery(query, null);
            exists = (cursor.getCount() > 0);
            cursor.close();
            db.close();
        } catch (SQLiteException e) {
            db.close();
        }

        return exists;
    }

    /**
     * Insert values in cart table
     *
     * @param context
     * @param dishName
     * @param dishPrice
     * @param dishQty
     * @return
     */
    public static boolean insertItem(Context context, String itemId, String dishName, String dishPrice, String dishQty) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DBHelper.CART_DISH_ID, "" + itemId);
        values.put(DBHelper.CART_DISH_NAME, "" + dishName);
        values.put(DBHelper.CART_DISH_PRICE, "" + dishPrice);
        values.put(DBHelper.CART_DISH_QTY, "" + dishQty);

        try {
            db.insert(DBHelper.TABLE_CART, null, values);
            db.close();
            return true;
        } catch (SQLiteException e) {
            db.close();
            return false;
        }
    }

    /**
     * Check for specific record by name
     *
     * @param context
     * @param dishName
     * @return
     */
    public static boolean isItemAvailable(Context context, String dishName) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        boolean exists = false;

        String query = "SELECT * FROM " + DBHelper.TABLE_CART + " WHERE "
                + DBHelper.CART_DISH_NAME + " = '" + String.valueOf(dishName) + "'";

        try {
            Cursor cursor = db.rawQuery(query, null);

            exists = (cursor.getCount() > 0);
            cursor.close();

        } catch (SQLiteException e) {

            e.printStackTrace();
            db.close();

        }

        return exists;
    }

    /**
     * Update cart item by item name
     *
     * @param context
     * @param dishName
     * @param dishPrice
     * @param dishQty
     * @return
     */
    public static boolean updateItem(Context context, String itemId, String dishName, String dishPrice, String dishQty) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DBHelper.CART_DISH_ID, itemId);
        values.put(DBHelper.CART_DISH_NAME, dishName);
        values.put(DBHelper.CART_DISH_PRICE, dishPrice);
        values.put(DBHelper.CART_DISH_QTY, dishQty);

        try {

            String[] args = new String[]{dishName};
            db.update(DBHelper.TABLE_CART, values, DBHelper.CART_DISH_NAME + "=?", args);

            db.close();

            return true;
        } catch (SQLiteException e) {
            db.close();

            return false;
        }
    }

    /**
     * Get cart list
     *
     * @param context
     * @return
     */
    public static ArrayList<CartModel> getCartList(Context context) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        ArrayList<CartModel> cartList = new ArrayList<>();

        try {
            String query = "SELECT * FROM " + DBHelper.TABLE_CART + ";";

            Cursor cursor = db.rawQuery(query, null);

            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {

                cartList.add(new CartModel(
                        cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_ID)),
                        cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_NAME)),
                        cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_QTY)),
                        Integer.parseInt(cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_PRICE)))
                ));
            }

            db.close();

        } catch (SQLiteException e) {
            db.close();
        }
        return cartList;
    }

   /**
     * Get total amount of cart items
     *
     * @param context
     * @return
     */
    public static String getTotalAmount(Context context) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        double totalAmount = 0.0;

        try {
            String query = "SELECT * FROM " + DBHelper.TABLE_CART + ";";

            Cursor cursor = db.rawQuery(query, null);

            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {

                totalAmount = totalAmount + Double.parseDouble(cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_PRICE))) *
                        Double.parseDouble(cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_QTY)));
            }

            db.close();

        } catch (SQLiteException e) {
            db.close();
        }

        if (totalAmount == 0.0)
            return "";
        else
            return "" + totalAmount;
    }

    /**
     * Get item quantity
     *
     * @param context
     * @param dishName
     * @return
     */
    public static String getItemQty(Context context, String dishName) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        Cursor cursor = null;
        String query = "SELECT * FROM " + DBHelper.TABLE_CART + " WHERE " + DBHelper.CART_DISH_NAME + " = '" + dishName + "';";
        String quantity = "0";

        try {
            cursor = db.rawQuery(query, null);

            if (cursor.getCount() > 0) {

                cursor.moveToFirst();
                quantity = cursor.getString(cursor
                        .getColumnIndex(DBHelper.CART_DISH_QTY));

                return quantity;
            }

        } catch (SQLiteException e) {
            e.printStackTrace();
        }

        return quantity;
    }

    /**
     * Delete cart item by name
     *
     * @param context
     * @param dishName
     */
    public static void deleteCartItem(Context context, String dishName) {
        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        try {

            String[] args = new String[]{dishName};
            db.delete(DBHelper.TABLE_CART, DBHelper.CART_DISH_NAME + "=?", args);

            db.close();
        } catch (SQLiteException e) {
            db.close();
            e.printStackTrace();
        }

    }

}//End of cart class

/**
 * Delete database table
 *
 * @param context
 */
public static void deleteCart(Context context) {
    DBHelper dbHelper = new DBHelper(context);
    SQLiteDatabase db = dbHelper.getReadableDatabase();

    try {

        db.execSQL("DELETE FROM " + DBHelper.TABLE_CART);

    } catch (SQLiteException e) {
        e.printStackTrace();
    }

}
</code>```

}

Usage:

```<code>  if(Database.Cart.isCartAvailable(context)){

       Database.deleteCart(context);

   }
</code>```

Body:
My app has two buttons, the first button is for deleting record on user input and the second button is for deleting all records. But when I want to delete data it shows the message

"Your application has been forcefully stopped".

Please check my code and give me some suggestion.

public void deleteAll()
{
    //SQLiteDatabase db = this.getWritableDatabase();
   // db.delete(TABLE_NAME,null,null);
    //db.execSQL("delete * from"+ TABLE_NAME);
    db.execSQL("TRUNCATE table" + TABLE_NAME);
    db.close();
}

and

public void delete(String id)
{
    String[] args={id};
    getWritableDatabase().delete("texts", "_ID=?", args);
}

But it shows the following Log cat error.

03-07 15:57:07.143: ERROR/AndroidRuntime(287): Uncaught handler: thread main exiting due to uncaught exception
03-07 15:57:07.153: ERROR/AndroidRuntime(287): java.lang.NullPointerException
03-07 15:57:07.153: ERROR/AndroidRuntime(287):     at com.example.MySQLiteHelper.delete(MySQLiteHelper.java:163)
03-07 15:57:07.153: ERROR/AndroidRuntime(287):     at com.example.Settings$4.onClick(Settings.java:94)
-07 15:57:07.153: ERROR/AndroidRuntime(287):     at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:158)
03-07 15:57:07.153: ERROR/AndroidRuntime(287):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-07 15:57:07.153: ERROR/AndroidRuntime(287):     at android.os.Looper.loop(Looper.java:123)
03-07 15:57:07.153: ERROR/AndroidRuntime(287):     at android.app.ActivityThread.main(ActivityThread.java:4203)
03-07 15:57:07.153: ERROR/AndroidRuntime(287):     at java.lang.reflect.Method.invokeNative(Native Method)
03-07 15:57:07.153: ERROR/AndroidRuntime(287):     at java.lang.reflect.Method.invoke(Method.java:521)
03-07 15:57:07.153: ERROR/AndroidRuntime(287):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
03-07 15:57:07.153: ERROR/AndroidRuntime(287):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
03-07 15:57:07.153: ERROR/AndroidRuntime(287):     at dalvik.system.NativeStart.main(Native Method)

Body:
I use this class to handle database.I hope it will help some one in future.

Happy coding.

public class Database {

private static class DBHelper extends SQLiteOpenHelper {

    /**
     * Database name
     */
    private static final String DB_NAME = "db_name";

    /**
     * Table Names
     */
    public static final String TABLE_CART = "DB_CART";

    /**
     *  Cart Table Columns
     */
    public static final String CART_ID_PK = "_id";// Primary key

    public static final String CART_DISH_NAME = "dish_name";
    public static final String CART_DISH_ID = "menu_item_id";
    public static final String CART_DISH_QTY = "dish_qty";
    public static final String CART_DISH_PRICE = "dish_price";

    /**
     * String to create reservation tabs table
     */
    private final String CREATE_TABLE_CART = "CREATE TABLE IF NOT EXISTS "
            + TABLE_CART + " ( "
            + CART_ID_PK + " INTEGER PRIMARY KEY, "
            + CART_DISH_NAME + " TEXT , "
            + CART_DISH_ID + " TEXT , "
            + CART_DISH_QTY + " TEXT , "
            + CART_DISH_PRICE + " TEXT);";

    public DBHelper(Context context) {
        super(context, DB_NAME, null, 2);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_CART);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
        db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_CART);
        onCreate(db);
    }

}

     /**
      * CART handler
      */
      public static class Cart {

    /**
     * Check if Cart is available or not
     *
     * @param context
     * @return
     */
    public static boolean isCartAvailable(Context context) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        boolean exists = false;

        try {
            String query = "SELECT * FROM " + DBHelper.TABLE_CART;
            Cursor cursor = db.rawQuery(query, null);
            exists = (cursor.getCount() > 0);
            cursor.close();
            db.close();
        } catch (SQLiteException e) {
            db.close();
        }

        return exists;
    }

    /**
     * Insert values in cart table
     *
     * @param context
     * @param dishName
     * @param dishPrice
     * @param dishQty
     * @return
     */
    public static boolean insertItem(Context context, String itemId, String dishName, String dishPrice, String dishQty) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DBHelper.CART_DISH_ID, "" + itemId);
        values.put(DBHelper.CART_DISH_NAME, "" + dishName);
        values.put(DBHelper.CART_DISH_PRICE, "" + dishPrice);
        values.put(DBHelper.CART_DISH_QTY, "" + dishQty);

        try {
            db.insert(DBHelper.TABLE_CART, null, values);
            db.close();
            return true;
        } catch (SQLiteException e) {
            db.close();
            return false;
        }
    }

    /**
     * Check for specific record by name
     *
     * @param context
     * @param dishName
     * @return
     */
    public static boolean isItemAvailable(Context context, String dishName) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        boolean exists = false;

        String query = "SELECT * FROM " + DBHelper.TABLE_CART + " WHERE "
                + DBHelper.CART_DISH_NAME + " = '" + String.valueOf(dishName) + "'";

        try {
            Cursor cursor = db.rawQuery(query, null);

            exists = (cursor.getCount() > 0);
            cursor.close();

        } catch (SQLiteException e) {

            e.printStackTrace();
            db.close();

        }

        return exists;
    }

    /**
     * Update cart item by item name
     *
     * @param context
     * @param dishName
     * @param dishPrice
     * @param dishQty
     * @return
     */
    public static boolean updateItem(Context context, String itemId, String dishName, String dishPrice, String dishQty) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DBHelper.CART_DISH_ID, itemId);
        values.put(DBHelper.CART_DISH_NAME, dishName);
        values.put(DBHelper.CART_DISH_PRICE, dishPrice);
        values.put(DBHelper.CART_DISH_QTY, dishQty);

        try {

            String[] args = new String[]{dishName};
            db.update(DBHelper.TABLE_CART, values, DBHelper.CART_DISH_NAME + "=?", args);

            db.close();

            return true;
        } catch (SQLiteException e) {
            db.close();

            return false;
        }
    }

    /**
     * Get cart list
     *
     * @param context
     * @return
     */
    public static ArrayList<CartModel> getCartList(Context context) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        ArrayList<CartModel> cartList = new ArrayList<>();

        try {
            String query = "SELECT * FROM " + DBHelper.TABLE_CART + ";";

            Cursor cursor = db.rawQuery(query, null);

            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {

                cartList.add(new CartModel(
                        cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_ID)),
                        cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_NAME)),
                        cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_QTY)),
                        Integer.parseInt(cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_PRICE)))
                ));
            }

            db.close();

        } catch (SQLiteException e) {
            db.close();
        }
        return cartList;
    }

   /**
     * Get total amount of cart items
     *
     * @param context
     * @return
     */
    public static String getTotalAmount(Context context) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        double totalAmount = 0.0;

        try {
            String query = "SELECT * FROM " + DBHelper.TABLE_CART + ";";

            Cursor cursor = db.rawQuery(query, null);

            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {

                totalAmount = totalAmount + Double.parseDouble(cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_PRICE))) *
                        Double.parseDouble(cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_QTY)));
            }

            db.close();

        } catch (SQLiteException e) {
            db.close();
        }

        if (totalAmount == 0.0)
            return "";
        else
            return "" + totalAmount;
    }

    /**
     * Get item quantity
     *
     * @param context
     * @param dishName
     * @return
     */
    public static String getItemQty(Context context, String dishName) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        Cursor cursor = null;
        String query = "SELECT * FROM " + DBHelper.TABLE_CART + " WHERE " + DBHelper.CART_DISH_NAME + " = '" + dishName + "';";
        String quantity = "0";

        try {
            cursor = db.rawQuery(query, null);

            if (cursor.getCount() > 0) {

                cursor.moveToFirst();
                quantity = cursor.getString(cursor
                        .getColumnIndex(DBHelper.CART_DISH_QTY));

                return quantity;
            }

        } catch (SQLiteException e) {
            e.printStackTrace();
        }

        return quantity;
    }

    /**
     * Delete cart item by name
     *
     * @param context
     * @param dishName
     */
    public static void deleteCartItem(Context context, String dishName) {
        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        try {

            String[] args = new String[]{dishName};
            db.delete(DBHelper.TABLE_CART, DBHelper.CART_DISH_NAME + "=?", args);

            db.close();
        } catch (SQLiteException e) {
            db.close();
            e.printStackTrace();
        }

    }

}//End of cart class

/**
 * Delete database table
 *
 * @param context
 */
public static void deleteCart(Context context) {
    DBHelper dbHelper = new DBHelper(context);
    SQLiteDatabase db = dbHelper.getReadableDatabase();

    try {

        db.execSQL("DELETE FROM " + DBHelper.TABLE_CART);

    } catch (SQLiteException e) {
        e.printStackTrace();
    }

}

}

Usage:

  if(Database.Cart.isCartAvailable(context)){

       Database.deleteCart(context);

   }


问:
Android cannot display a list view to another activity
I am going to display ordered destination information from a list of selected destinations. For example, the user can select some destinations in the list of 10 places, and based on the distance the priority I set, the second activity will display a calculated route for the user.

The priority value of each destination is stored in a cloud database, and I tested that I could successfully get the data. I will use the data to calculate the route.

There is no error in LogCAT, however, the ordered list view cannot display in the second activity. PLEASE help me, it has bothered me for more than three days.

here is my code (first activity):

```<code>public class DestinationActivity extends Activity implements OnClickListener, NumberPicker.OnValueChangeListener {

private TextView from_place, date, days, start_time, end_time, number, money_view;
private Button addButton, subButton;
private ImageView backButton, telephone;
private ListView listView;
private Button destinationOk_btn;

private Tip startTip;

private Calendar calendar;
private DatePickerDialog dialog;
private TimePickerDialog dialog2;

private List<Destination> destinationList = new ArrayList<Destination>();

private DestinationAdapter adapter;

private int number_value = 1;

private String time_start;
private String time_end;
private int travel_days;
double travelTime;//total traveling time
double travel_time;
//long car_time;
private int money;
private int num = 1;

//private SQLiteDatabase db;
//private DestinationDBHelper dbHelper;

private ArrayList<Integer> select_placeID = new ArrayList<Integer>(); //selected destinations
public Map<Integer,Double> weightMap;
public List<Plan> planList = new ArrayList<Plan>();//

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.destination_layout);

    Bmob.initialize(this, BmobConfig.APP_ID);

    listView = (ListView) findViewById(R.id.list_destination);

    destinationOk_btn = (Button) findViewById(R.id.okButton);

    initDestinations();

    adapter = new DestinationAdapter(destinationList, DestinationActivity.this);
    //adapter = new DestinationAdapter(this, destinationList, DestinationAdapter.getIsSelected());
    listView.setAdapter(adapter);

    from_place = (TextView) findViewById(R.id.from_place);
    date = (TextView) findViewById(R.id.date);
    start_time = (TextView) findViewById(R.id.time);
    end_time = (TextView) findViewById(R.id.end_time);
    number = (TextView) findViewById(R.id.number);
    money_view = (TextView) findViewById(R.id.request_money_et);
    addButton = (Button) findViewById(btn_add);
    subButton = (Button) findViewById(btn_sub);
    backButton = (ImageView) findViewById(R.id.back);
    telephone = (ImageView) findViewById(R.id.telephone);
    days = (EditText) findViewById(R.id.days);

    //listeners
    from_place.setOnClickListener(this);
    date.setOnClickListener(this);
    start_time.setOnClickListener(this);
    number.setOnClickListener(this);
    destinationOk_btn.setOnClickListener(this);
    addButton.setOnClickListener(this);
    subButton.setOnClickListener(this);
    backButton.setOnClickListener(this);
    telephone.setOnClickListener(this);
    end_time.setOnClickListener(this);

    //submit button
    destinationOk_btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            select_placeID.clear();

            for (int i = 0; i < destinationList.size(); i++) {
                if (DestinationAdapter.getIsSelected().get(i)) {
                    select_placeID.add(i);
                }

            }

            if (select_placeID.size() == 0) {
                AlertDialog.Builder builder1 = new AlertDialog.Builder(DestinationActivity.this);
                builder1.setMessage("no records");
                builder1.show();
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(DestinationActivity.this);

                builder.setMessage("waiting for magic...");
                builder.show();

                /**
                 * calculate the route
                 */
                if (validate()) {
                    new calRoute().execute();
                }

                Intent intent = new Intent();
                intent.setClass(DestinationActivity.this, ActivityPlan.class);

                intent.putParcelableArrayListExtra("planInfo", (ArrayList<? extends Parcelable>) planList);

                startActivity(intent);

            }
        }

    });
    }

//initialize the data
private void initDestinations() {
    Destination destination1 = new Destination("香山", R.drawable.xiangshan);
    destinationList.add(destination1);
    Destination destination2 = new Destination("天安门", R.drawable.car);
    destinationList.add(destination2);
    Destination destination3 = new Destination("后海", R.drawable.car);
    destinationList.add(destination3);
    Destination destination4 = new Destination("五道口", R.drawable.car);
    destinationList.add(destination4);
    Destination destination5 = new Destination("朝阳公园", R.drawable.car);
    destinationList.add(destination5);
    Destination destination6 = new Destination("雍和宫", R.drawable.car);
    destinationList.add(destination6);
    Destination destination7 = new Destination("八达岭长城", R.drawable.car);
    destinationList.add(destination7);
    Destination destination8 = new Destination("颐和园", R.drawable.car);
    destinationList.add(destination8);
    Destination destination9 = new Destination("三里屯", R.drawable.car);
    destinationList.add(destination9);
    Destination destination10 = new Destination("故宫", R.drawable.car);
    destinationList.add(destination10);
}

@Override
public void onClick(View v) {
    //.............
}

//number picker
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
    Log.i("value is","" + newVal);
}

/**
 * 异步处理
 */
private class calRoute extends AsyncTask<Void, Void, List<Plan>>{

    public calRoute(){
        // TODO Auto-generated constructor stub
    }

    @Override
    protected List<Plan> doInBackground(Void... params) {

        List<Plan> result = calculate(time_start, time_end, travel_days);

        return result;
    }

    //UI
    @Override
    protected void onPostExecute(List<Plan> result) {
        super.onPostExecute(result);
        if (result != null) {
            Toast.makeText(DestinationActivity.this, "success", Toast.LENGTH_SHORT).show();
        }
    }
}

/**
 *plan calculation
 **/
public List<Plan> calculate(String time_start, String time_end, int travel_days) {

    SimpleDateFormat df = new SimpleDateFormat(("HH:mm"));

    Date starttime = new Date();
    Date endtime = new Date();
    try {
        starttime = df.parse(time_start);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    try {
        endtime = df.parse(time_end);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    double l = endtime.getTime() - starttime.getTime();
    double hour = (l / (60 * 60 * 1000));
    double min = ((l / (60 * 1000)) - hour * 60);

    if(min == 0){
        min = 60;
    }
    else {
        travel_time = ((1.0 * travel_days * hour) * (min / 60)); //以小时为单位计算旅行时长calculate total travel time
        DecimalFormat decimalFormat = new DecimalFormat("#.0");
        travelTime = Double.parseDouble(decimalFormat.format(travel_time));//保留一位小数
    }

    //获取不同地点的priority
    weightMap = new LinkedHashMap<Integer, Double>();

    int totalPriority = 0;//总优先级total priority

   // where I am
    final Destination start = new Destination(116.355231, 39.95222);//当前位置

    final HashMap<Integer, Integer> pMap = new HashMap<Integer, Integer>();
    final HashMap<Integer, String> nameMap = new HashMap<Integer, String>();
    final HashMap<Integer, Destination> objectMap = new LinkedHashMap<Integer, Destination>();//储存每个destination的经纬度
    /**
     * 向后端云bmob根据id查询景点的priority
     */
    new Thread (new Runnable(){

        @Override
        public void run() {
            BmobQuery<Destination> query = new BmobQuery<Destination>();
            for (int id : select_placeID) {

                query.addWhereEqualTo("id", id);

                //查询数据, 子查询
                //query.addWhereContainedIn("id", select_placeID);

                //返回10条数据，如果不加上这条语句，默认返回10条数据
                //query.setLimit(10);

                //执行查询方法
                query.findObjects(new FindListener<Destination>() {
                    @Override
                    public void done(List<Destination> list, BmobException e) {
                        if (e == null) {
                            System.out.println("查询成功：共" + list.size() + "条数据。");
                            for (Destination destination : list) {
                                //获得priority的信息
                                int p = destination.getPriority();
                                //获得数据的objectId信息
                                int id = destination.getId();

                                String name = destination.getName();

                                //获取经纬度
                                double longitude = destination.getLongitude();
                                double latitute = destination.getLatitute();

                                objectMap.put(id, new Destination(longitude, latitute));

                                //计算距离
                                double dis = DistanceUtil.distance(start.getLongitude(), start.getLatitute(),
                                        longitude, latitute);

                                pMap.put(id, p);
                                weightMap.put(id, dis);
                                nameMap.put(id, name);

                            }
                        } else {
                            Log.i("bmob", "失败：" + e.getMessage() + "," + e.getErrorCode());
                        }
                    }
                });
            }
        }
    }).start();

    //遍历整个pMap
    for (int v : pMap.values()) {
        totalPriority = totalPriority + v;
    }

    //计算weight并生成最终map
    double weight = 0.0;
    for (Map.Entry<Integer, Double> hm : weightMap.entrySet()) {
        double hm2Value = pMap.get(hm.getKey());
        weight = totalPriority / hm.getValue() * hm2Value;

        weightMap.put(hm.getKey(), weight);
    }

    /**
     * 按照weight值来排序
     * 判断是否传递数据给plan_activity
     */
    MapUtil.sortByValue(weightMap);

    //排好序后计算距离
    Iterator it = weightMap.entrySet().iterator();
    int order = 0;
    while (it.hasNext()) {
        order++;
        Map.Entry entry = (Map.Entry) it.next();
        objectMap.put(order, objectMap.get(entry.getKey()));//有哪些id，并且位置已排列好
    }

    PlanTask planTask = new PlanTask();//封装了每个plan计算的方法
    //遍历map中的值,打印plan
    for (Map.Entry<Integer, Double> entry : weightMap.entrySet()) {
        System.out.println("id= " + entry.getKey());

        double play_time = planTask.calPlay_time(weightMap.size(),
                weightMap.get(entry.getKey()), travelTime);

        //到下一个目的地需要多久开车时间
        //按id找到destination，获取经纬度
        double driving_time = planTask.calDrive_time(DistanceUtil.distance(
                objectMap.get(entry.getKey()).getLatitute(),
                objectMap.get(entry.getKey()).getLongitude(),
                objectMap.get(entry.getKey() + 1).getLatitute(),
                objectMap.get(entry.getKey() + 1).getLongitude()
        ));

        String arrive_time = "hello world";//未完待续

        String place_name = nameMap.get(entry.getKey());

        Plan plan = new Plan(place_name, arrive_time, driving_time, play_time);

        //传递plan对象list
        planList.add(entry.getKey(), plan);
    }

    return planList;

}

//验证用户输入是否完整
public boolean validate(){
    //先计算旅游总时间
    time_start = start_time.getText().toString();
    time_end = end_time.getText().toString();
    try {
        travel_days = Integer.parseInt(days.getText().toString());
    } catch (NumberFormatException e) {
        Toast.makeText(DestinationActivity.this, "游玩天数不正确", Toast.LENGTH_SHORT).show();
    }

        if (StringUtils.isBlank(time_start)) {
            Toast.makeText(DestinationActivity.this, "请输入出发时间", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (StringUtils.isBlank(time_end)) {
            Toast.makeText(DestinationActivity.this, "请输入结束时间", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (travel_days <=0 ){
            Toast.makeText(DestinationActivity.this, "请输入游玩天数", Toast.LENGTH_SHORT).show();
            return false;
        }

    return true;

}

  }
</code>```

this is the code of the second activity:

```<code>public class ActivityPlan extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.plan_layout);

    List<Plan> plans = new ArrayList<Plan>();

    Intent intent = getIntent();
    plans = intent.getParcelableArrayListExtra("planInfo");

    PlanAdapter adapter = new PlanAdapter(ActivityPlan.this,
            R.layout.item_plan, plans);

    ListView listView = (ListView) findViewById(R.id.plan_list);
    listView.setAdapter(adapter);

}

}
</code>```

and the code of the model Plan, which I will display on the second activity:

```<code>public class Plan implements Parcelable {

private String place_name;
private String arrive_time;
private double play_time;
private double driving_time;

public Plan(){

}

public Plan(String place_name, String arrive_time, double driving_time, double play_time) {
    this.place_name = place_name;
    this.arrive_time = arrive_time;
    this.driving_time = driving_time;
    this.play_time = play_time;
}

protected Plan(Parcel in) {
    place_name = in.readString();
    arrive_time = in.readString();
    play_time = in.readDouble();
    driving_time = in.readLong();
}

@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {

    // TODO Auto-generated method stub
    dest.writeString(place_name);
    dest.writeString(arrive_time);
    dest.writeDouble(play_time);
    dest.writeDouble(driving_time);
}

public static final Creator<Plan> CREATOR = new Creator<Plan>() {

    @Override
    public Plan createFromParcel(Parcel source) {
        Plan planInfo  = new Plan();
        planInfo.place_name = source.readString();
        planInfo.arrive_time = source.readString();
        planInfo.play_time= source.readDouble();
        planInfo.driving_time = source.readDouble();

        return planInfo;
    }

    @Override
    public Plan[] newArray(int size) {
        return new Plan[size];
    }
};

public String getPlace_name() {
    return place_name;
}
public String getArrive_time() {
    return arrive_time;
}
public double getPlay_time() {
    return play_time;
}
public double getDriving_time() {
    return driving_time;
}

public void setPlace_name(String place_name){
    this.place_name = place_name;
}

public void setArrive_time(String arrive_time){
    this.arrive_time = arrive_time;
}

public void setPlay_time(double play_time){this.play_time = play_time;}

public void setDriving_time(double driving_time){
    this.driving_time = driving_time;
}

}
</code>```

I am new in Android development and I feel so confused now,
1. why the ordered information cannot be display on the second activity,  2. when I debug, I found that the variable "travelTime" is always 0.0, and the size of planList which I will use to display the information is zero, why is it?? Please help me!! thank you so much!

答:
put below lines in OnPostExecute method instead of where you put it now. . </p>

```<code>    Intent intent = new Intent();
            intent.setClass(DestinationActivity.this, ActivityPlan.class);

            intent.putParcelableArrayListExtra("planInfo", (ArrayList<? extends Parcelable>) planList);

            startActivity(intent);
</code>```

Body:
I am going to display ordered destination information from a list of selected destinations. For example, the user can select some destinations in the list of 10 places, and based on the distance the priority I set, the second activity will display a calculated route for the user.

The priority value of each destination is stored in a cloud database, and I tested that I could successfully get the data. I will use the data to calculate the route.

There is no error in LogCAT, however, the ordered list view cannot display in the second activity. PLEASE help me, it has bothered me for more than three days.

here is my code (first activity):

public class DestinationActivity extends Activity implements OnClickListener, NumberPicker.OnValueChangeListener {

private TextView from_place, date, days, start_time, end_time, number, money_view;
private Button addButton, subButton;
private ImageView backButton, telephone;
private ListView listView;
private Button destinationOk_btn;

private Tip startTip;

private Calendar calendar;
private DatePickerDialog dialog;
private TimePickerDialog dialog2;

private List<Destination> destinationList = new ArrayList<Destination>();

private DestinationAdapter adapter;

private int number_value = 1;

private String time_start;
private String time_end;
private int travel_days;
double travelTime;//total traveling time
double travel_time;
//long car_time;
private int money;
private int num = 1;

//private SQLiteDatabase db;
//private DestinationDBHelper dbHelper;

private ArrayList<Integer> select_placeID = new ArrayList<Integer>(); //selected destinations
public Map<Integer,Double> weightMap;
public List<Plan> planList = new ArrayList<Plan>();//

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.destination_layout);

    Bmob.initialize(this, BmobConfig.APP_ID);

    listView = (ListView) findViewById(R.id.list_destination);

    destinationOk_btn = (Button) findViewById(R.id.okButton);

    initDestinations();

    adapter = new DestinationAdapter(destinationList, DestinationActivity.this);
    //adapter = new DestinationAdapter(this, destinationList, DestinationAdapter.getIsSelected());
    listView.setAdapter(adapter);

    from_place = (TextView) findViewById(R.id.from_place);
    date = (TextView) findViewById(R.id.date);
    start_time = (TextView) findViewById(R.id.time);
    end_time = (TextView) findViewById(R.id.end_time);
    number = (TextView) findViewById(R.id.number);
    money_view = (TextView) findViewById(R.id.request_money_et);
    addButton = (Button) findViewById(btn_add);
    subButton = (Button) findViewById(btn_sub);
    backButton = (ImageView) findViewById(R.id.back);
    telephone = (ImageView) findViewById(R.id.telephone);
    days = (EditText) findViewById(R.id.days);

    //listeners
    from_place.setOnClickListener(this);
    date.setOnClickListener(this);
    start_time.setOnClickListener(this);
    number.setOnClickListener(this);
    destinationOk_btn.setOnClickListener(this);
    addButton.setOnClickListener(this);
    subButton.setOnClickListener(this);
    backButton.setOnClickListener(this);
    telephone.setOnClickListener(this);
    end_time.setOnClickListener(this);

    //submit button
    destinationOk_btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            select_placeID.clear();

            for (int i = 0; i < destinationList.size(); i++) {
                if (DestinationAdapter.getIsSelected().get(i)) {
                    select_placeID.add(i);
                }

            }

            if (select_placeID.size() == 0) {
                AlertDialog.Builder builder1 = new AlertDialog.Builder(DestinationActivity.this);
                builder1.setMessage("no records");
                builder1.show();
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(DestinationActivity.this);

                builder.setMessage("waiting for magic...");
                builder.show();

                /**
                 * calculate the route
                 */
                if (validate()) {
                    new calRoute().execute();
                }

                Intent intent = new Intent();
                intent.setClass(DestinationActivity.this, ActivityPlan.class);

                intent.putParcelableArrayListExtra("planInfo", (ArrayList<? extends Parcelable>) planList);

                startActivity(intent);

            }
        }

    });
    }

//initialize the data
private void initDestinations() {
    Destination destination1 = new Destination("香山", R.drawable.xiangshan);
    destinationList.add(destination1);
    Destination destination2 = new Destination("天安门", R.drawable.car);
    destinationList.add(destination2);
    Destination destination3 = new Destination("后海", R.drawable.car);
    destinationList.add(destination3);
    Destination destination4 = new Destination("五道口", R.drawable.car);
    destinationList.add(destination4);
    Destination destination5 = new Destination("朝阳公园", R.drawable.car);
    destinationList.add(destination5);
    Destination destination6 = new Destination("雍和宫", R.drawable.car);
    destinationList.add(destination6);
    Destination destination7 = new Destination("八达岭长城", R.drawable.car);
    destinationList.add(destination7);
    Destination destination8 = new Destination("颐和园", R.drawable.car);
    destinationList.add(destination8);
    Destination destination9 = new Destination("三里屯", R.drawable.car);
    destinationList.add(destination9);
    Destination destination10 = new Destination("故宫", R.drawable.car);
    destinationList.add(destination10);
}

@Override
public void onClick(View v) {
    //.............
}

//number picker
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
    Log.i("value is","" + newVal);
}

/**
 * 异步处理
 */
private class calRoute extends AsyncTask<Void, Void, List<Plan>>{

    public calRoute(){
        // TODO Auto-generated constructor stub
    }

    @Override
    protected List<Plan> doInBackground(Void... params) {

        List<Plan> result = calculate(time_start, time_end, travel_days);

        return result;
    }

    //UI
    @Override
    protected void onPostExecute(List<Plan> result) {
        super.onPostExecute(result);
        if (result != null) {
            Toast.makeText(DestinationActivity.this, "success", Toast.LENGTH_SHORT).show();
        }
    }
}

/**
 *plan calculation
 **/
public List<Plan> calculate(String time_start, String time_end, int travel_days) {

    SimpleDateFormat df = new SimpleDateFormat(("HH:mm"));

    Date starttime = new Date();
    Date endtime = new Date();
    try {
        starttime = df.parse(time_start);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    try {
        endtime = df.parse(time_end);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    double l = endtime.getTime() - starttime.getTime();
    double hour = (l / (60 * 60 * 1000));
    double min = ((l / (60 * 1000)) - hour * 60);

    if(min == 0){
        min = 60;
    }
    else {
        travel_time = ((1.0 * travel_days * hour) * (min / 60)); //以小时为单位计算旅行时长calculate total travel time
        DecimalFormat decimalFormat = new DecimalFormat("#.0");
        travelTime = Double.parseDouble(decimalFormat.format(travel_time));//保留一位小数
    }

    //获取不同地点的priority
    weightMap = new LinkedHashMap<Integer, Double>();

    int totalPriority = 0;//总优先级total priority

   // where I am
    final Destination start = new Destination(116.355231, 39.95222);//当前位置

    final HashMap<Integer, Integer> pMap = new HashMap<Integer, Integer>();
    final HashMap<Integer, String> nameMap = new HashMap<Integer, String>();
    final HashMap<Integer, Destination> objectMap = new LinkedHashMap<Integer, Destination>();//储存每个destination的经纬度
    /**
     * 向后端云bmob根据id查询景点的priority
     */
    new Thread (new Runnable(){

        @Override
        public void run() {
            BmobQuery<Destination> query = new BmobQuery<Destination>();
            for (int id : select_placeID) {

                query.addWhereEqualTo("id", id);

                //查询数据, 子查询
                //query.addWhereContainedIn("id", select_placeID);

                //返回10条数据，如果不加上这条语句，默认返回10条数据
                //query.setLimit(10);

                //执行查询方法
                query.findObjects(new FindListener<Destination>() {
                    @Override
                    public void done(List<Destination> list, BmobException e) {
                        if (e == null) {
                            System.out.println("查询成功：共" + list.size() + "条数据。");
                            for (Destination destination : list) {
                                //获得priority的信息
                                int p = destination.getPriority();
                                //获得数据的objectId信息
                                int id = destination.getId();

                                String name = destination.getName();

                                //获取经纬度
                                double longitude = destination.getLongitude();
                                double latitute = destination.getLatitute();

                                objectMap.put(id, new Destination(longitude, latitute));

                                //计算距离
                                double dis = DistanceUtil.distance(start.getLongitude(), start.getLatitute(),
                                        longitude, latitute);

                                pMap.put(id, p);
                                weightMap.put(id, dis);
                                nameMap.put(id, name);

                            }
                        } else {
                            Log.i("bmob", "失败：" + e.getMessage() + "," + e.getErrorCode());
                        }
                    }
                });
            }
        }
    }).start();

    //遍历整个pMap
    for (int v : pMap.values()) {
        totalPriority = totalPriority + v;
    }

    //计算weight并生成最终map
    double weight = 0.0;
    for (Map.Entry<Integer, Double> hm : weightMap.entrySet()) {
        double hm2Value = pMap.get(hm.getKey());
        weight = totalPriority / hm.getValue() * hm2Value;

        weightMap.put(hm.getKey(), weight);
    }

    /**
     * 按照weight值来排序
     * 判断是否传递数据给plan_activity
     */
    MapUtil.sortByValue(weightMap);

    //排好序后计算距离
    Iterator it = weightMap.entrySet().iterator();
    int order = 0;
    while (it.hasNext()) {
        order++;
        Map.Entry entry = (Map.Entry) it.next();
        objectMap.put(order, objectMap.get(entry.getKey()));//有哪些id，并且位置已排列好
    }

    PlanTask planTask = new PlanTask();//封装了每个plan计算的方法
    //遍历map中的值,打印plan
    for (Map.Entry<Integer, Double> entry : weightMap.entrySet()) {
        System.out.println("id= " + entry.getKey());

        double play_time = planTask.calPlay_time(weightMap.size(),
                weightMap.get(entry.getKey()), travelTime);

        //到下一个目的地需要多久开车时间
        //按id找到destination，获取经纬度
        double driving_time = planTask.calDrive_time(DistanceUtil.distance(
                objectMap.get(entry.getKey()).getLatitute(),
                objectMap.get(entry.getKey()).getLongitude(),
                objectMap.get(entry.getKey() + 1).getLatitute(),
                objectMap.get(entry.getKey() + 1).getLongitude()
        ));

        String arrive_time = "hello world";//未完待续

        String place_name = nameMap.get(entry.getKey());

        Plan plan = new Plan(place_name, arrive_time, driving_time, play_time);

        //传递plan对象list
        planList.add(entry.getKey(), plan);
    }

    return planList;

}

//验证用户输入是否完整
public boolean validate(){
    //先计算旅游总时间
    time_start = start_time.getText().toString();
    time_end = end_time.getText().toString();
    try {
        travel_days = Integer.parseInt(days.getText().toString());
    } catch (NumberFormatException e) {
        Toast.makeText(DestinationActivity.this, "游玩天数不正确", Toast.LENGTH_SHORT).show();
    }

        if (StringUtils.isBlank(time_start)) {
            Toast.makeText(DestinationActivity.this, "请输入出发时间", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (StringUtils.isBlank(time_end)) {
            Toast.makeText(DestinationActivity.this, "请输入结束时间", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (travel_days <=0 ){
            Toast.makeText(DestinationActivity.this, "请输入游玩天数", Toast.LENGTH_SHORT).show();
            return false;
        }

    return true;

}

  }

this is the code of the second activity:

public class ActivityPlan extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.plan_layout);

    List<Plan> plans = new ArrayList<Plan>();

    Intent intent = getIntent();
    plans = intent.getParcelableArrayListExtra("planInfo");

    PlanAdapter adapter = new PlanAdapter(ActivityPlan.this,
            R.layout.item_plan, plans);

    ListView listView = (ListView) findViewById(R.id.plan_list);
    listView.setAdapter(adapter);

}

}

and the code of the model Plan, which I will display on the second activity:

public class Plan implements Parcelable {

private String place_name;
private String arrive_time;
private double play_time;
private double driving_time;

public Plan(){

}

public Plan(String place_name, String arrive_time, double driving_time, double play_time) {
    this.place_name = place_name;
    this.arrive_time = arrive_time;
    this.driving_time = driving_time;
    this.play_time = play_time;
}

protected Plan(Parcel in) {
    place_name = in.readString();
    arrive_time = in.readString();
    play_time = in.readDouble();
    driving_time = in.readLong();
}

@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {

    // TODO Auto-generated method stub
    dest.writeString(place_name);
    dest.writeString(arrive_time);
    dest.writeDouble(play_time);
    dest.writeDouble(driving_time);
}

public static final Creator<Plan> CREATOR = new Creator<Plan>() {

    @Override
    public Plan createFromParcel(Parcel source) {
        Plan planInfo  = new Plan();
        planInfo.place_name = source.readString();
        planInfo.arrive_time = source.readString();
        planInfo.play_time= source.readDouble();
        planInfo.driving_time = source.readDouble();

        return planInfo;
    }

    @Override
    public Plan[] newArray(int size) {
        return new Plan[size];
    }
};

public String getPlace_name() {
    return place_name;
}
public String getArrive_time() {
    return arrive_time;
}
public double getPlay_time() {
    return play_time;
}
public double getDriving_time() {
    return driving_time;
}

public void setPlace_name(String place_name){
    this.place_name = place_name;
}

public void setArrive_time(String arrive_time){
    this.arrive_time = arrive_time;
}

public void setPlay_time(double play_time){this.play_time = play_time;}

public void setDriving_time(double driving_time){
    this.driving_time = driving_time;
}

}

I am new in Android development and I feel so confused now,
1. why the ordered information cannot be display on the second activity,  2. when I debug, I found that the variable "travelTime" is always 0.0, and the size of planList which I will use to display the information is zero, why is it?? Please help me!! thank you so much!

Body:
put below lines in OnPostExecute method instead of where you put it now. .

    Intent intent = new Intent();
            intent.setClass(DestinationActivity.this, ActivityPlan.class);

            intent.putParcelableArrayListExtra("planInfo", (ArrayList<? extends Parcelable>) planList);

            startActivity(intent);


问:
onClick handler is triggered on each render cycle
I have default state like this

```<code>this.state = {
  selectedTab : 'tab1'
}
</code>```

then

My render method like this

```<code>render(){
   const { selectedTab } = this.state;
   return(
      <li>tab1</li><li>tab2</li>
      <div id="content">
         {selectedTab == 'tab1' ? this.renderTab1Content() : this.renderTab2Content()}
      </div>
   )
}
</code>```

Everything worked above. But I failed to implement switch tab using click event.

I tried to bind onclick event on my li to change the state of selectedTab, but I got infinity loop error. Like this

```<code><li onClick={this.setState({selectedTab :'tab1'})}>Tab 1</li>
<li onClick={this.setState({selectedTab :'someothertab'})}>Tab 2/li>
</code>```

Why?

答:
Every time your li gets rendered, the setState is automatically called and hence you get into a loop.  You should do something like this.

Create a method in the component like this

```<code>setActiveTab = (tab) => {
 this.setState({selectedTab : tab});
}
</code>```

Then in your render method rewrite your li like this

```<code><li onClick={() => this.setActiveTab('tab1')}>Tab 1</li>
<li onClick={() => this.setActiveTab('someothertab')}>Tab 2/li>
</code>```

Body:
I have default state like this

this.state = {
  selectedTab : 'tab1'
}

then

My render method like this

render(){
   const { selectedTab } = this.state;
   return(

tab1

tab2

         {selectedTab == 'tab1' ? this.renderTab1Content() : this.renderTab2Content()}

   )
}

Everything worked above. But I failed to implement switch tab using click event.

I tried to bind onclick event on my li to change the state of selectedTab, but I got infinity loop error. Like this

Tab 1

Tab 2/li>

Why?

Body:
Every time your li gets rendered, the setState is automatically called and hence you get into a loop.  You should do something like this.

Create a method in the component like this

setActiveTab = (tab) => {
 this.setState({selectedTab : tab});
}

Then in your render method rewrite your li like this

<li onClick={() => this.setActiveTab('tab1')}>Tab 1</li>
<li onClick={() => this.setActiveTab('someothertab')}>Tab 2/li>


问:
Concurrency: Processes vs Threads
What are the main advantages of using a model for concurrency based on processes over one
based on threads and in what contexts is the latter appropriate?</p>

答:
The disadvantage of using a process-based model is that it will be slower. You will have to copy data between the concurrent parts of your program.

The disadvantage of using a thread-based model is that you will probably get it wrong. It may sound mean, but it's true-- show me code based on threads and I'll show you a bug. I've found bugs in threaded code that has run "correctly" for 10 years.

The advantages of using a process-based model are numerous. The separation forces you to think in terms of protocols and formal communication patterns, which means its far more likely that you will get it right. Processes communicating with each other are easier to scale out across multiple machines.  Multiple concurrent processes allows one process to crash without necessarily crashing the others.

The advantage of using a thread-based model is that it is fast.

It may be obvious which of the two I prefer, but in case it isn't: processes, every day of the week and twice on Sunday. Threads are too hard: I haven't ever met anybody who could write correct multi-threaded code; those that claim to be able to usually don't know enough about the space yet.

Title: Concurrency: Processes vs Threads