问:
heroku deploy error in RoR(Github deploy) what should I do with postgresql error?
I'm deploying small app from C9 to github then to Heroku!
In heroku deploy dashboard, it says it's been deployed, but when I open the app, it just gives me error msg.
So I searched a lot of Stackoverflow answers and was following the direction from Heroku website(https://devcenter.heroku.com/articles/sqlite3) to remove sqlite3 and install the gem pg.

I did replace gem 'sqlite3' to gem 'pg' and did 'bundle install', and then

It says I need to convert my   config/database.yml file, So I replaced it like this:

```<code>development:
  adapter: postgresql
  database: my_database_development
  pool: 5
  timeout: 5000
test:
  adapter: postgresql
  database: my_database_test
  pool: 5
  timeout: 5000

production:
  adapter: postgresql
  database: my_database_production
  pool: 5
  timeout: 5000
</code>```

and then when I come back to c9 bash and type 'rake db:create',
it shows me

```<code>**rake aborted!
ActiveRecord::NoDatabaseError: FATAL:  database "my_database_development" does not exist**
</code>```

this error.

someone said 'bundle exec rake db:setup' would work, so I did, and then it shows

```<code>**Couldn't create database for {"adapter"=>"postgresql", "database"=>"my_database_test", "pool"=>5, "timeout"=>5000}
/home/ubuntu/workspace/db/schema.rb doesn't exist yet. Run `rake db:migrate` to create it, then try again. If you do not intend to use a database, you should instead alter /home/ubuntu/workspace/config/application.rb to limit the frameworks that will be loaded.**
</code>```

I don't know how to react to this msg.... when I type 'rake db:migrate' and it shows this again.

```<code>rake aborted!
ActiveRecord::NoDatabaseError: FATAL:  database "my_database_development" does not exist
</code>```

I'm not using database, so maybe I can try something on 'config/application.rb' file, but how should I do??

答:
It wasn't necessary to change your development and test databases, those could still have used sqlite3 and so your C9 instance would have continued to work.

(Although there are some advantages to using a consistent adapter across all environments)

If this is just a hobby exercise I would be tempted to keep sqlite3 for development and test.

Also, Heroku replaces the database.yml with its own version so you don't need a production stanza in database.yml

You do need the pg gem, but you can specify it is only loaded in production and you can specify the sqlite3 gem is only loaded in development and test.  Do that in your Gemfile and then bundle.

```<code>group :development, :test do
  gem 'sqlite3'
end

group :production do
  gem 'pg'
end
</code>```

If you want to use PostgreSQL in your C9 instance, you have to install PostgreSQL (the database, not just the adapter).  It's not a simple process.

This wiki explains how you would install it.

https://wiki.postgresql.org/wiki/Detailed_installation_guides

Body:
I'm deploying small app from C9 to github then to Heroku!
In heroku deploy dashboard, it says it's been deployed, but when I open the app, it just gives me error msg.
So I searched a lot of Stackoverflow answers and was following the direction from Heroku website(https://devcenter.heroku.com/articles/sqlite3) to remove sqlite3 and install the gem pg.

I did replace gem 'sqlite3' to gem 'pg' and did 'bundle install', and then

It says I need to convert my   config/database.yml file, So I replaced it like this:

development:
  adapter: postgresql
  database: my_database_development
  pool: 5
  timeout: 5000
test:
  adapter: postgresql
  database: my_database_test
  pool: 5
  timeout: 5000

production:
  adapter: postgresql
  database: my_database_production
  pool: 5
  timeout: 5000

and then when I come back to c9 bash and type 'rake db:create',
it shows me

**rake aborted!
ActiveRecord::NoDatabaseError: FATAL:  database "my_database_development" does not exist**

this error.

someone said 'bundle exec rake db:setup' would work, so I did, and then it shows

**Couldn't create database for {"adapter"=>"postgresql", "database"=>"my_database_test", "pool"=>5, "timeout"=>5000}
/home/ubuntu/workspace/db/schema.rb doesn't exist yet. Run `rake db:migrate` to create it, then try again. If you do not intend to use a database, you should instead alter /home/ubuntu/workspace/config/application.rb to limit the frameworks that will be loaded.**

I don't know how to react to this msg.... when I type 'rake db:migrate' and it shows this again.

rake aborted!
ActiveRecord::NoDatabaseError: FATAL:  database "my_database_development" does not exist

I'm not using database, so maybe I can try something on 'config/application.rb' file, but how should I do??

Body:
It wasn't necessary to change your development and test databases, those could still have used sqlite3 and so your C9 instance would have continued to work.

(Although there are some advantages to using a consistent adapter across all environments)

If this is just a hobby exercise I would be tempted to keep sqlite3 for development and test.

Also, Heroku replaces the database.yml with its own version so you don't need a production stanza in database.yml

You do need the pg gem, but you can specify it is only loaded in production and you can specify the sqlite3 gem is only loaded in development and test.  Do that in your Gemfile and then bundle.

group :development, :test do
  gem 'sqlite3'
end

group :production do
  gem 'pg'
end

If you want to use PostgreSQL in your C9 instance, you have to install PostgreSQL (the database, not just the adapter).  It's not a simple process.

This wiki explains how you would install it.

https://wiki.postgresql.org/wiki/Detailed_installation_guides


来源: stackexchange

问:
loading json from text file
I am trying to run this code but it creates error.

```<code>import json
import requests
import pprint
data = []
with open('data.txt') as o1:
  for line in o1:
    data.append(json.loads(line))
    print(data)
    print(" \n")
print(data)
url = 'http://xyz.abcdfx.in/devicedata'
body_json=json.dumps(data)
headers = {'Content-Type':'application/json'}
d = requests.post(url, data = body_json, headers=headers)
pprint.pprint(d.json())
</code>```

it shows

```<code>Value Error: No json object could be Decoded
</code>```

I am new to programming and not able to figure out what is the problem.

答:
It seems like you are trying to parse the json file line by line, but the json objects may (and usually are) span more than one line. You need to have the entire file in order to parse it:

```<code> with open('data.txt') as o1:
      data = json.loads(o1.read()) # read ALL the file and parse. no loops
 print(data)
</code>```

ContentLicense: CC BY-SA 3.0

Title: loading json from text file

Body:
I am trying to run this code but it creates error.

import json
import requests
import pprint
data = []
with open('data.txt') as o1:
  for line in o1:
    data.append(json.loads(line))
    print(data)
    print(" \n")
print(data)
url = 'http://xyz.abcdfx.in/devicedata'
body_json=json.dumps(data)
headers = {'Content-Type':'application/json'}
d = requests.post(url, data = body_json, headers=headers)
pprint.pprint(d.json())

it shows

Value Error: No json object could be Decoded

I am new to programming and not able to figure out what is the problem.

Body:
It seems like you are trying to parse the json file line by line, but the json objects may (and usually are) span more than one line. You need to have the entire file in order to parse it:

 with open('data.txt') as o1:
      data = json.loads(o1.read()) # read ALL the file and parse. no loops
 print(data)


问:
splitting the value and displaying in a formatted way
I am getting a json array value and parsing it and i am displaying it in a jsp page inside the textarea. To make it more readable i am splitting it by ',' and displaying it.

```<code>var splitStr = retrievedValue.value1
var output = splitStr.split(",");
for (var i = 0; i < output.length; i++) {
  document.getElementById("textarea").value += (output[i] +'\n');
}
</code>```

so the output is like

```<code>{"ind":""
"ser":[{"serv":[{"cos":0.0
"max":0.0
"start":{"eve":"B"
</code>```

but i like the output to be like

```<code>{"ind":""
"ser":
    [{"serv":
        [{"cos":0.0
"max":0.0
"start":
    {"eve":"B"
</code>```

i tried splitting again by ":[" by not getting the desired output.

答:
Why not use the format of JSON.stringify?

var json = '{"ind":"","ser":[{"serv":[{"cos":0.0,"max":0.0,"start":{"eve":"B"}}]}]}';

document.getElementById('out').value = JSON.stringify(JSON.parse(json), 0, 4);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea id="out", cols="40" rows="20"></textarea></code>```

Body:
I am getting a json array value and parsing it and i am displaying it in a jsp page inside the textarea. To make it more readable i am splitting it by ',' and displaying it.

var splitStr = retrievedValue.value1
var output = splitStr.split(",");
for (var i = 0; i < output.length; i++) {
  document.getElementById("textarea").value += (output[i] +'\n');
}

so the output is like

{"ind":""
"ser":[{"serv":[{"cos":0.0
"max":0.0
"start":{"eve":"B"

but i like the output to be like

{"ind":""
"ser":
    [{"serv":
        [{"cos":0.0
"max":0.0
"start":
    {"eve":"B"

i tried splitting again by ":[" by not getting the desired output.

Body:
Why not use the format of JSON.stringify?

var json = '{"ind":"","ser":[{"serv":[{"cos":0.0,"max":0.0,"start":{"eve":"B"}}]}]}';

document.getElementById('out').value = JSON.stringify(JSON.parse(json), 0, 4);

<textarea id="out", cols="40" rows="20"></textarea>


问:
[C++]Would this be a valid approach for a 'sleep' function in a thread?
I would like to implement a sleep() function in my thread class, but I don't know if this is a valid/proper way to do it.
This is my entire thread class (thread.h):

```<code>#include <process.h>

struct RUNNABLE{
    virtual void run() = 0;
};

class thread{
public:
    void start(void *ptr){
        DWORD thr_id;
        HANDLE thr_handl = (HANDLE)_beginthreadex(NULL, 0, thread_proc, ptr, 0, (unsigned int*)&thr_id);
    }

    void sleep(int sleep_time, bool alertable){
        SleepEx(sleep_time, alertable);
    }
private:
    static unsigned int __stdcall thread_proc(void *param){
        ((RUNNABLE*)param)->run();
        _endthreadex(0);
        return 0;
    }
};
</code>```

And as you're probably able to sort out, this is my sleep() function:

```<code>void sleep(int sleep_time, bool alertable){
    SleepEx(sleep_time, alertable);
}
</code>```

But will this make the actual thread contained inside this thread instance sleep for the specified amount of milliseconds?

Best regards,
Benjamin :).

EDIT:

So according to atzz, I could define the sleep function as a static member function, and have that call ::SleepEx(), and that would allow me to call it like this:

```<code>class test : RUNNABLE{
    virtual void run(){
        printf("hi");
        thread::sleep(1000, false);
    }
};
</code>```

and then that'll cause the thread executing the 'test' runnable to sleep 1000 milliseonds?

答:
If you need to suspend newly created thread, you should use SuspendThread instead or pass CREATE_SUSPENDED to _beginthreadex(), but this can cause deadlocks in some cases

see http://msdn.microsoft.com/en-us/library/ms686345%28v=VS.85%29.aspx

Body:
I would like to implement a sleep() function in my thread class, but I don't know if this is a valid/proper way to do it.
This is my entire thread class (thread.h):

#include <process.h>

struct RUNNABLE{
    virtual void run() = 0;
};

class thread{
public:
    void start(void *ptr){
        DWORD thr_id;
        HANDLE thr_handl = (HANDLE)_beginthreadex(NULL, 0, thread_proc, ptr, 0, (unsigned int*)&thr_id);
    }

    void sleep(int sleep_time, bool alertable){
        SleepEx(sleep_time, alertable);
    }
private:
    static unsigned int __stdcall thread_proc(void *param){
        ((RUNNABLE*)param)->run();
        _endthreadex(0);
        return 0;
    }
};

And as you're probably able to sort out, this is my sleep() function:

void sleep(int sleep_time, bool alertable){
    SleepEx(sleep_time, alertable);
}

But will this make the actual thread contained inside this thread instance sleep for the specified amount of milliseconds?

Best regards,
Benjamin :).

EDIT:

So according to atzz, I could define the sleep function as a static member function, and have that call ::SleepEx(), and that would allow me to call it like this:

class test : RUNNABLE{
    virtual void run(){
        printf("hi");
        thread::sleep(1000, false);
    }
};

and then that'll cause the thread executing the 'test' runnable to sleep 1000 milliseonds?

ContentLicense: CC BY-SA 2.5


问:
php JSON_DECODE for different data length
From mysql, I have a data BLOB data type which has two different scenarios (Please see below). I am trying to put them into a string. Below is the process that I am doing:

1. Query:

```<code>$names= $results[0]->name;
print_r($names);
</code>```

First scenario:

```<code>[{"Name":"Mike"},{"Name":"Sean"}]
</code>```

Second scenario:

```<code>{"Name":"Mike Smith","Spaces":"1"}
</code>```

2. JSON_DECODE

```<code>$data =  json_decode(stripslashes($names),true);
print_r($data);
</code>```

First scenario:

```<code>    Array
        (
            [0] => Array
                (
                    [Name] => Mike
                )

            [1] => Array
                (
                    [Name] => Smith
                )
        )
</code>```

Second scenario:

```<code>    Array
        (
            [Name] => Mike Smith
            [Spaces] => 1
        )
</code>```

3. What I am trying to do: To put them into a string

```<code>$string = '';

for ($i=0; $i <sizeof($data) ; $i++){
    $row = $data[$i];
    $name = $row -> Name;

    if(isset($row -> Spaces)){
        $number = '(' . $row -> Spaces . ')';

    }else{
        $number = '';

    };
    $string .=  $name . $number . ', ';

};

//Remove last comma
$refined = rtrim($string,', ');

print_r($refined);
</code>```

4. ISSUE

The issue I am having is that because the data can have two different scenarios like shown in the "1.Query", I can't predict or generalize it and getting errors like "Trying to get property of non-object".

How can I fix this?

答:
Well I'll edit my answer for better understanding

```<code>$str1 = '[{"Name":"Mike"},{"Name":"Sean"}]';
$str2 = '{"Name":"Mike Smith","Spaces":"1"}';

$json1 = json_decode($str1, false);
$json2 = json_decode($str2, false);

if(is_object($json1))
    { echo 'json1 is object<br>'; } else
    { echo 'json1 is NOT object<br>'; }

if(is_object($json2))
    { echo 'json2 is object'; } else
    { echo 'json2 is NOT object'; }
</code>```

http://php.net/manual/en/function.is-object.php

Body:
From mysql, I have a data BLOB data type which has two different scenarios (Please see below). I am trying to put them into a string. Below is the process that I am doing:

1. Query:

$names= $results[0]->name;
print_r($names);

First scenario:

[{"Name":"Mike"},{"Name":"Sean"}]

Second scenario:

{"Name":"Mike Smith","Spaces":"1"}

2. JSON_DECODE

$data =  json_decode(stripslashes($names),true);
print_r($data);

First scenario:

    Array
        (
            [0] => Array
                (
                    [Name] => Mike
                )

            [1] => Array
                (
                    [Name] => Smith
                )
        )

Second scenario:

    Array
        (
            [Name] => Mike Smith
            [Spaces] => 1
        )

3. What I am trying to do: To put them into a string

$string = '';

for ($i=0; $i <sizeof($data) ; $i++){
    $row = $data[$i];
    $name = $row -> Name;

    if(isset($row -> Spaces)){
        $number = '(' . $row -> Spaces . ')';

    }else{
        $number = '';

    };
    $string .=  $name . $number . ', ';

};

//Remove last comma
$refined = rtrim($string,', ');

print_r($refined);

4. ISSUE

The issue I am having is that because the data can have two different scenarios like shown in the "1.Query", I can't predict or generalize it and getting errors like "Trying to get property of non-object".

How can I fix this?

Body:
Well I'll edit my answer for better understanding

$str1 = '[{"Name":"Mike"},{"Name":"Sean"}]';
$str2 = '{"Name":"Mike Smith","Spaces":"1"}';

$json1 = json_decode($str1, false);
$json2 = json_decode($str2, false);

if(is_object($json1))
    { echo 'json1 is object<br>'; } else
    { echo 'json1 is NOT object<br>'; }

if(is_object($json2))
    { echo 'json2 is object'; } else
    { echo 'json2 is NOT object'; }

http://php.net/manual/en/function.is-object.php


问:
How To Get Hidden TD Value when i click on a TR
im trying to make a task manger based on web system that can monitor tasks at work , im using html and php .
im trying to show all the tasks in table and when i click on a task (row) i want to get a hidden td value (id of task) and send it as arg to another page for more information about the task .
i searched the web how can i do that , but i didnt realy understand how to do it with my table .
here is my table code

```<code>                   <table id="thickets_show">
                    <tr id="show_ticket_table_header">
                        <td>Work Week</td>
                        <td>Task Submited Date</td>
                        <td>Task Submited Time</td>
                        <td>Task</td>
                        <td>Project</td>
                        <td>Task Owner</td>
                        <td>Task Assigend to</td>
                        <td>Priority</td>
                        <td>Status</td>
                        <td>Task Total Work Time</td>
                        <td>Task Due Date</td>
                        <td>Task Finish Date</td>
                        <td>Team</td>
                    </tr>';
                    foreach ($tasks as $key => $value) {
                        if ($value['ticket_status']=="done")
                            echo '<tr id="done_ticket" >';
                        elseif ($value['ticket_priority']=="high")
                             echo '<tr id="high_ticket" class="ticket_raw">';
                        else
                            echo '<tr class="ticket_raw">';
                        echo '
                                <td>
                                    '.$value['work_week'].'
                                </td>
                                <td>
                                    '.$value['ticket_date'].'
                                </td>
                                <td>
                                    '.$value['ticket_time_submit'].'
                                </td>
                                <td>
                                    '.$value['ticket_request'].'
                                </td>
                                <td>
                                    '.$value['ticket_project'].'
                                </td>
                                <td>
                                    '.$value['ticket_onwer'].'
                                </td>
                                <td>
                                    '.$value['ticket_assigned_user'].'
                                </td>
                                <td>
                                    '.$value['ticket_priority'].'
                                </td>
                                <td>
                                    '.$value['ticket_status'].'
                                </td>
                                <td>
                                    '.$value['ticket_worktime'].'
                                </td>
                                <td>
                                    '.$value['ticket_due_date'].'
                                </td>
                                <td>
                                    '.$value['ticket_finish_date'].'
                                </td>
                                <td>
                                    '.$value['team'].'
                                </td>
                                <td style="display:none;" id="ticket_id class="divOne">
                                    '.$value['id'].'
                                </td>
                              </tr>
</code>```

this is the function that im using

```<code>$(function(){
            $(".ticket_raw" ).on(\'click\',function(e){
                e.preventDefault();
                var id = $(this).attr("#ticket_id");
                alert(id);
            });
        });
</code>```

答:
The td has the id ticket_id, so you can use document.getElementById():

var td = document.getElementById('ticket_id');
var value = td.textContent;
```

<p>Or, using jQuery:</p>

<pre class="lang-js prettyprint-override"><code>var td = $('#ticket_id');
var value = td.text();
</code>```

Body:
im trying to make a task manger based on web system that can monitor tasks at work , im using html and php .
im trying to show all the tasks in table and when i click on a task (row) i want to get a hidden td value (id of task) and send it as arg to another page for more information about the task .
i searched the web how can i do that , but i didnt realy understand how to do it with my table .
here is my table code

                        Work Week
                        Task Submited Date
                        Task Submited Time
                        Task
                        Project
                        Task Owner
                        Task Assigend to
                        Priority
                        Status
                        Task Total Work Time
                        Task Due Date
                        Task Finish Date
                        Team

';
                    foreach ($tasks as $key => $value) {
                        if ($value['ticket_status']=="done")
                            echo '
';
                        elseif ($value['ticket_priority']=="high")
                             echo '
';
                        else
                            echo '
';
                        echo '

                                    '.$value['work_week'].'

                                    '.$value['ticket_date'].'

                                    '.$value['ticket_time_submit'].'

                                    '.$value['ticket_request'].'

                                    '.$value['ticket_project'].'

                                    '.$value['ticket_onwer'].'

                                    '.$value['ticket_assigned_user'].'

                                    '.$value['ticket_priority'].'

                                    '.$value['ticket_status'].'

                                    '.$value['ticket_worktime'].'

                                    '.$value['ticket_due_date'].'

                                    '.$value['ticket_finish_date'].'

                                    '.$value['team'].'

                                    '.$value['id'].'

this is the function that im using

$(function(){
            $(".ticket_raw" ).on(\'click\',function(e){
                e.preventDefault();
                var id = $(this).attr("#ticket_id");
                alert(id);
            });
        });

Body:
The td has the id ticket_id, so you can use document.getElementById():

var td = document.getElementById('ticket_id');
var value = td.textContent;

Or, using jQuery:

var td = $('#ticket_id');
var value = td.text();


问:
Filter only parameters that are present in the request
There are lots of articles that are about Java 8 lambda operations however I couldn't find what I need until now. I tried to convert them to my approach unfortunately I couldn't succeed

Imagine that you have request that comes in POJO such as ;

```<code>public class DummyRequest {

    private String name;
    private String surname;
    private String country;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country= country;
    }

}
</code>```

During REST/SOAP request surname variable will be assigned as null.

```<code>List<Person> persons = Arrays.asList(
                new Person("maria", "gambert", "italy"),
                new Person("jack", "johson", "usa"),
                new Person("johnson", "jack", "usa"),
                new Person("kate", "julia", "spain"),
                new Person("jack","bob","uk");

DummyRequest dr = new DummyRequest();
dr.setName("jack");
dr.setCountry("usa");
</code>```

If I knew in advance that the surname field would be null, I could manage to filter the list like this, ignoring that field:

```<code>List<Person> result4 = persons.stream().
filter(x -> dummyRequest.getName().equals(x.getName())).
filter( x-> dummyRequest.getCountry().equals(x.getCountry())).
collect(Collectors.toList());
</code>```

However I don't know which fields will be null and which will not. How could I instead filter my data according to non-null request parameters only?

答:
If you want to only apply the filter for which the dummyRequest contains a non-null value, you would have to dynamically build your stream for the most efficient solution.

This could easily be done by implementing a helper method that conditionally applies a filter:

```<code>public static <T, V> Stream<T> filterIfNotNull(Stream<T> stream, V filterValue, Function<T, V> property) {
    if (filterValue == null) {
        return stream;
    }

    return stream.filter(t -> filterValue.equals(property.apply(t)));
}
</code>```

(in your example T would always be Person and V would always be String, but this generic version allows more reusability without additional complexity at the call site)

Then the stream/collect can be implemented like this:

```<code>Stream<Person> personStream = persons.stream();
personStream = filterIfNotNull(personStream, dummyRequest.getName(), Person::getName);
personStream = filterIfNotNull(personStream, dummyRequest.getSurname(), Person::getSurname);
personStream = filterIfNotNull(personStream, dummyRequest.getCountry(), Person::getCountry);
List<Person> result4 = personStream.collect(Collectors.toList());
</code>```

This technique guarantees that the null-check on the request's properties is only applied once.

Body:
There are lots of articles that are about Java 8 lambda operations however I couldn't find what I need until now. I tried to convert them to my approach unfortunately I couldn't succeed

Imagine that you have request that comes in POJO such as ;

public class DummyRequest {

    private String name;
    private String surname;
    private String country;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country= country;
    }

}

During REST/SOAP request surname variable will be assigned as null.

List<Person> persons = Arrays.asList(
                new Person("maria", "gambert", "italy"),
                new Person("jack", "johson", "usa"),
                new Person("johnson", "jack", "usa"),
                new Person("kate", "julia", "spain"),
                new Person("jack","bob","uk");

DummyRequest dr = new DummyRequest();
dr.setName("jack");
dr.setCountry("usa");

If I knew in advance that the surname field would be null, I could manage to filter the list like this, ignoring that field:

List<Person> result4 = persons.stream().
filter(x -> dummyRequest.getName().equals(x.getName())).
filter( x-> dummyRequest.getCountry().equals(x.getCountry())).
collect(Collectors.toList());

However I don't know which fields will be null and which will not. How could I instead filter my data according to non-null request parameters only?

Body:
If you want to only apply the filter for which the dummyRequest contains a non-null value, you would have to dynamically build your stream for the most efficient solution.

This could easily be done by implementing a helper method that conditionally applies a filter:

public static <T, V> Stream<T> filterIfNotNull(Stream<T> stream, V filterValue, Function<T, V> property) {
    if (filterValue == null) {
        return stream;
    }

    return stream.filter(t -> filterValue.equals(property.apply(t)));
}

(in your example T would always be Person and V would always be String, but this generic version allows more reusability without additional complexity at the call site)

Then the stream/collect can be implemented like this:

Stream<Person> personStream = persons.stream();
personStream = filterIfNotNull(personStream, dummyRequest.getName(), Person::getName);
personStream = filterIfNotNull(personStream, dummyRequest.getSurname(), Person::getSurname);
personStream = filterIfNotNull(personStream, dummyRequest.getCountry(), Person::getCountry);
List<Person> result4 = personStream.collect(Collectors.toList());

This technique guarantees that the null-check on the request's properties is only applied once.


问:
How to create Custom WPA Hotspot with ssid and password in android?
I am using the following code for creating the Wifi-hotspot configuration.
I am able to create the Hotspot configuration and able to  enable it. but i have give configuration for WPA-PSK, But it always taken as OPEN network.

```<code>public boolean setHotSpot(String SSID,String passWord){
Method[] mMethods = mWifiManager.getClass().getDeclaredMethods();

    for(Method mMethod: mMethods){

        if(mMethod.getName().equals("setWifiApEnabled")) {
            WifiConfiguration netConfig = new WifiConfiguration();
             netConfig.SSID = SSID ;
                netConfig.preSharedKey = passWord;
                netConfig.hiddenSSID = true;
                netConfig.status = WifiConfiguration.Status.ENABLED;
                netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
                netConfig.allowedKeyManagement.set(4);
                netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
                netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);

            try {
                mMethod.invoke(mWifiManager, netConfig,true);
                mWifiManager.saveConfiguration();
                return true;

            } catch (Exception e) {
                e.printStackTrace();
                CommonUtil.log(TAG,"Exception : "+e.getLocalizedMessage());
            }
        }
    }
return false;
</code>```

}

After run this app the Hotspot got enabled. Please check the image below.

How to set the WPA_PSK wifi configuration in android app?

As per below answer i have modified the code below.

```<code>public boolean setHotSpot(String SSID, String passWord) {
    boolean apstatus;
    WifiConfiguration netConfig = new WifiConfiguration();
    if (passWord == "") {
        netConfig.SSID = SSID;
        netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
        netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    } else {
        netConfig.SSID = SSID;
        netConfig.preSharedKey = passWord;
                /*netConfig.hiddenSSID = true;
                netConfig.status = WifiConfiguration.Status.ENABLED;
                netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
                netConfig.allowedKeyManagement.set(4);
                netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
                netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);*/
        netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
        netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    }

    try {
        Method setWifiApMethod = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
        //setWifiApMethod.invoke(mWifiManager, previousConfigurations, false);
        //Thread.sleep(2000);
        apstatus = (Boolean) setWifiApMethod.invoke(mWifiManager, netConfig, true);
    } catch (Exception e) {
        CommonUtil.log(TAG, e.getMessage());
        return false;
    }
    return apstatus;
}
</code>```

答:
I have done this in my app. Please check my code below.

First add below permissions to your manifest.

```<code><uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
</code>```

Then create below MyHotspotManager .java class

```<code>public class MyHotspotManager {
    private WifiConfiguration wifiCon;
    private HotspotDetails hotspotDetails;
    private WifiManager mWifiManager;

    public MyHotspotManager(WifiManager wifiManager){
        this.mWifiManager = wifiManager;
    }

    public boolean setHotspot(HotspotDetails hotspotDetails) {
        this.hotspotDetails = hotspotDetails;
        boolean apstatus;
        wifiCon = new WifiConfiguration();
        wifiCon.SSID = hotspotDetails.getSsid();
        wifiCon.preSharedKey = hotspotDetails.getPassword();
        wifiCon.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
        wifiCon.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        wifiCon.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        wifiCon.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        try {
            Method setWifiApMethod = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
            //setWifiApMethod.invoke(mWifiManager, previousConfigurations, false);
            //Thread.sleep(2000);
            apstatus = (Boolean) setWifiApMethod.invoke(mWifiManager, wifiCon, true);
        } catch (Exception e) {
            Log.e(this.getClass().toString(), "", e);
            return false;
        }

        return apstatus;
    }

}
</code>```

After that you can call the setHotspot method anywhere in you activity like below. Here I had to check whether app has the ACTION_MANAGE_WRITE_SETTINGS permission.

```<code>public void OnButtonClick(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.System.canWrite(getApplicationContext())) {
                Toast.makeText(this, "Please try again after giving access to Change system settings", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, 200);

            }else{
                createHotspot();
            }
        }

    }

    private void createHotspot(){
        HotspotDetails hotspotDetails = new HotspotDetails();
        hotspotDetails.setSsid("TestStackOverFlow");
        hotspotDetails.setPassword("654321");
        new MyHotspotManager((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE))
                .setHotspot(hotspotDetails);
    }
</code>```

But if you want you can omit permission request part by changing your targetSdkVersion to 21 in build.gradle. Now you can call it like below

```<code>    public void OnButtonClick(View view) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            if (!Settings.System.canWrite(getApplicationContext())) {
//                Toast.makeText(this, "Please try again after giving access to Change system settings", Toast.LENGTH_SHORT).show();
//                Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse("package:" + getPackageName()));
//                startActivityForResult(intent, 200);
//
//            }else{
//            }
//        }

        createHotspot();
    }

    private void createHotspot(){
        HotspotDetails hotspotDetails = new HotspotDetails();
        hotspotDetails.setSsid("TestStackOverFlow");
        hotspotDetails.setPassword("654321");
        new MyHotspotManager((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE))
                .setHotspot(hotspotDetails);
    }
</code>```

This my HotspotDetails.java class

```<code>public class HotspotDetails {
    private String ssid;
    private String password;

    public String getSsid() {
        return ssid;
    }

    public void setSsid(String ssid) {
        this.ssid = ssid;
    }

    public String getPassword() {
        return password;
    }

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

    @Override
    public String toString() {
        return ssid + ":" + password;
    }
}
</code>```

Body:
I am using the following code for creating the Wifi-hotspot configuration.
I am able to create the Hotspot configuration and able to  enable it. but i have give configuration for WPA-PSK, But it always taken as OPEN network.

public boolean setHotSpot(String SSID,String passWord){
Method[] mMethods = mWifiManager.getClass().getDeclaredMethods();

    for(Method mMethod: mMethods){

        if(mMethod.getName().equals("setWifiApEnabled")) {
            WifiConfiguration netConfig = new WifiConfiguration();
             netConfig.SSID = SSID ;
                netConfig.preSharedKey = passWord;
                netConfig.hiddenSSID = true;
                netConfig.status = WifiConfiguration.Status.ENABLED;
                netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
                netConfig.allowedKeyManagement.set(4);
                netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
                netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);

            try {
                mMethod.invoke(mWifiManager, netConfig,true);
                mWifiManager.saveConfiguration();
                return true;

            } catch (Exception e) {
                e.printStackTrace();
                CommonUtil.log(TAG,"Exception : "+e.getLocalizedMessage());
            }
        }
    }
return false;

}

After run this app the Hotspot got enabled. Please check the image below.

How to set the WPA_PSK wifi configuration in android app?

As per below answer i have modified the code below.

public boolean setHotSpot(String SSID, String passWord) {
    boolean apstatus;
    WifiConfiguration netConfig = new WifiConfiguration();
    if (passWord == "") {
        netConfig.SSID = SSID;
        netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
        netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    } else {
        netConfig.SSID = SSID;
        netConfig.preSharedKey = passWord;
                /*netConfig.hiddenSSID = true;
                netConfig.status = WifiConfiguration.Status.ENABLED;
                netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
                netConfig.allowedKeyManagement.set(4);
                netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
                netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);*/
        netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
        netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    }

    try {
        Method setWifiApMethod = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
        //setWifiApMethod.invoke(mWifiManager, previousConfigurations, false);
        //Thread.sleep(2000);
        apstatus = (Boolean) setWifiApMethod.invoke(mWifiManager, netConfig, true);
    } catch (Exception e) {
        CommonUtil.log(TAG, e.getMessage());
        return false;
    }
    return apstatus;
}

Body:
I have done this in my app. Please check my code below.

First add below permissions to your manifest.

<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />

Then create below MyHotspotManager .java class

public class MyHotspotManager {
    private WifiConfiguration wifiCon;
    private HotspotDetails hotspotDetails;
    private WifiManager mWifiManager;

    public MyHotspotManager(WifiManager wifiManager){
        this.mWifiManager = wifiManager;
    }

    public boolean setHotspot(HotspotDetails hotspotDetails) {
        this.hotspotDetails = hotspotDetails;
        boolean apstatus;
        wifiCon = new WifiConfiguration();
        wifiCon.SSID = hotspotDetails.getSsid();
        wifiCon.preSharedKey = hotspotDetails.getPassword();
        wifiCon.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
        wifiCon.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        wifiCon.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        wifiCon.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        try {
            Method setWifiApMethod = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
            //setWifiApMethod.invoke(mWifiManager, previousConfigurations, false);
            //Thread.sleep(2000);
            apstatus = (Boolean) setWifiApMethod.invoke(mWifiManager, wifiCon, true);
        } catch (Exception e) {
            Log.e(this.getClass().toString(), "", e);
            return false;
        }

        return apstatus;
    }

}

After that you can call the setHotspot method anywhere in you activity like below. Here I had to check whether app has the ACTION_MANAGE_WRITE_SETTINGS permission.

public void OnButtonClick(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.System.canWrite(getApplicationContext())) {
                Toast.makeText(this, "Please try again after giving access to Change system settings", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, 200);

            }else{
                createHotspot();
            }
        }

    }

    private void createHotspot(){
        HotspotDetails hotspotDetails = new HotspotDetails();
        hotspotDetails.setSsid("TestStackOverFlow");
        hotspotDetails.setPassword("654321");
        new MyHotspotManager((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE))
                .setHotspot(hotspotDetails);
    }

But if you want you can omit permission request part by changing your targetSdkVersion to 21 in build.gradle. Now you can call it like below

    public void OnButtonClick(View view) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            if (!Settings.System.canWrite(getApplicationContext())) {
//                Toast.makeText(this, "Please try again after giving access to Change system settings", Toast.LENGTH_SHORT).show();
//                Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse("package:" + getPackageName()));
//                startActivityForResult(intent, 200);
//
//            }else{
//            }
//        }

        createHotspot();
    }

    private void createHotspot(){
        HotspotDetails hotspotDetails = new HotspotDetails();
        hotspotDetails.setSsid("TestStackOverFlow");
        hotspotDetails.setPassword("654321");
        new MyHotspotManager((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE))
                .setHotspot(hotspotDetails);
    }

This my HotspotDetails.java class

public class HotspotDetails {
    private String ssid;
    private String password;

    public String getSsid() {
        return ssid;
    }

    public void setSsid(String ssid) {
        this.ssid = ssid;
    }

    public String getPassword() {
        return password;
    }

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

    @Override
    public String toString() {
        return ssid + ":" + password;
    }
}


问:
IE bug with min-width?
I have given a div a min-width , and a percentage width . It seems to be working as expected on Chrome and FF , but in IE ( 7 & 9 ) , the min-width is not enforced . The following code illustrates the behaviour in t.</p>

```<code><div style="background-color:#fc0;min-width:500px; width:10%;">
test
</div>
</code>```

答:
Here's a snippet for simulating min-height in IE5+. It should be useful for what you want to do.

I guess it'll probably work for width changing the auto for whatever value you want.

```<code>height: auto!important; /* for good browsers */
height: 175px; /* for IE5+ */
min-height: 175px; /* for good browsers */
</code>```

Title: IE bug with min-width?

Body:
I have given a div a min-width , and a percentage width . It seems to be working as expected on Chrome and FF , but in IE ( 7 & 9 ) , the min-width is not enforced . The following code illustrates the behaviour in t.

test

Body:
Here's a snippet for simulating min-height in IE5+. It should be useful for what you want to do.

I guess it'll probably work for width changing the auto for whatever value you want.

height: auto!important; /* for good browsers */
height: 175px; /* for IE5+ */
min-height: 175px; /* for good browsers */


问:
Google Maps HTML5 click to get lat, long
I'm trying to build a mobile HTML5 webapp in which user can click on the map to get lat/long from Google Maps. Is there a code example? I tried googling but only found some website that does that but no soucecode example.

This is because I'm going to use HTML5 geolocation to display the current location first, but if it's not accurate then users can specify that by themselves.

Thanks a lot.

答:
You have to use event argument.

```<code> google.maps.event.addListener(map, 'click', function(event) {
     marker = new google.maps.Marker({position: event.latLng, map: map});
     console.log(event.latLng);   // Get latlong info as object.
     console.log( "Latitude: "+event.latLng.lat()+" "+", longitude: "+event.latLng.lng()); // Get separate lat long.
 });
</code>```

Body:
You have to use event argument.

 google.maps.event.addListener(map, 'click', function(event) {
     marker = new google.maps.Marker({position: event.latLng, map: map});
     console.log(event.latLng);   // Get latlong info as object.
     console.log( "Latitude: "+event.latLng.lat()+" "+", longitude: "+event.latLng.lng()); // Get separate lat long.
 });


问:
JQuery - Why event.target doesn't work in this situation?
just wondering why when i click inside the container the alert popups despite the if statement for it to not show on click.

Also how would I test for the children inside?

https://jsfiddle.net/w8fd3m67/

$(window).on("click", function(event) {
  var container = $("#container");
  if ((event.target) !== container) {
    alert("clicked outside");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  height: 600px;
}

#container {
  padding: 2rem;
  background: grey;
}</code>```

```

Cheers

答:
You're comparing a DOM element to a jQuery object which will never match. Create a jQuery object out of the target and check if it is a descendant of #container. This also works if you have child elements under #container.

Updated fiddle

```<code>$(window).on("click", function(event) {
  if ($(event.target).closest('#container').length == 0){
    alert("clicked outside");
  }
});
</code>```

Body:
just wondering why when i click inside the container the alert popups despite the if statement for it to not show on click.

Also how would I test for the children inside?

https://jsfiddle.net/w8fd3m67/

$(window).on("click", function(event) {
  var container = $("#container");
  if ((event.target) !== container) {
    alert("clicked outside");
  }
});

body {
  height: 600px;
}

#container {
  padding: 2rem;
  background: grey;
}

Cheers

Body:
You're comparing a DOM element to a jQuery object which will never match. Create a jQuery object out of the target and check if it is a descendant of #container. This also works if you have child elements under #container.

Updated fiddle

$(window).on("click", function(event) {
  if ($(event.target).closest('#container').length == 0){
    alert("clicked outside");
  }
});


问:
Android : why does defining the widgets in this part (i.e MainActivity ) Cause an error
If I define the following lines

```<code>myText =(TextView)findViewById(R.id.textView);
button=(Button)findViewById(R.id.button);
</code>```

in onCreate the program runs smoothly but if I do that in Main Activity then it causes an error.

```<code>import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    myText =(TextView)findViewById(R.id.textView); //error
    button=(Button)findViewById(R.id.button);

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

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

                if(myText.getVisibility()==View.VISIBLE){

                    myText.setVisibility(View.INVISIBLE);
                }else
                {
                    myText.setVisibility(View.VISIBLE);
                }

            }
        });
    }
}
</code>```

答:
In the case of an Activity, findViewById starts the search from the content view (set with setContentView) of the activity which is the view hierarchy inflated from the layout resource.

So until in the onCreate the setContentView is called..findViewById wont work.

Java initializes class variables at class load time. If you make "myText" and "button" as class variables and initializes with findViewById , it just wont work because setContentView has not been called yet

Body:
If I define the following lines

myText =(TextView)findViewById(R.id.textView);
button=(Button)findViewById(R.id.button);

in onCreate the program runs smoothly but if I do that in Main Activity then it causes an error.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    myText =(TextView)findViewById(R.id.textView); //error
    button=(Button)findViewById(R.id.button);

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

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

                if(myText.getVisibility()==View.VISIBLE){

                    myText.setVisibility(View.INVISIBLE);
                }else
                {
                    myText.setVisibility(View.VISIBLE);
                }

            }
        });
    }
}


问:
Read txt and add in jtable
I am new to java and I need to create a program that reads text from a txt file and puts it into a jtable, the format in the txt file  will be like "b3:42".  And I need to read those and put b3 in the first column of the table and 42 in the next column. Could you help me ? And sorry for my english.</p>

答:
you can refer below code .</p>

```<code>import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.*;
public class HelloWorld{
    private static final String FILENAME = "input.txt";
     public static void main(String []args){
        BufferedReader br = null;
        FileReader fr = null;
        try {
            fr = new FileReader(FILENAME);
            br = new BufferedReader(fr);

            String s;
            String[][] data = new String[2][2];

            br = new BufferedReader(new FileReader(FILENAME));
            int i = 0;
            while ((s = br.readLine()) != null) {
                 data[i]= s.split(":");
                i++;
            }

           String column[]={"COL1","COL2"};
            JTable jt=new JTable(data,column);
        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            try {

                if (br != null)
                    br.close();

                if (fr != null)
                    fr.close();

            } catch (IOException ex) {

                ex.printStackTrace();

            }

        }
     }
}
</code>```

Title: Read txt and add in jtable

Body:
you can refer below code .

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.*;
public class HelloWorld{
    private static final String FILENAME = "input.txt";
     public static void main(String []args){
        BufferedReader br = null;
        FileReader fr = null;
        try {
            fr = new FileReader(FILENAME);
            br = new BufferedReader(fr);

            String s;
            String[][] data = new String[2][2];

            br = new BufferedReader(new FileReader(FILENAME));
            int i = 0;
            while ((s = br.readLine()) != null) {
                 data[i]= s.split(":");
                i++;
            }

           String column[]={"COL1","COL2"};
            JTable jt=new JTable(data,column);
        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            try {

                if (br != null)
                    br.close();

                if (fr != null)
                    fr.close();

            } catch (IOException ex) {

                ex.printStackTrace();

            }

        }
     }
}


问:
Displaying a stock iOS notification banner when your app is open and in the foreground?
When Apple's official iOS Messages app is open and in the foreground, new messages from other contacts trigger a stock, native iOS notification alert banner. See image below.

Is this possible in 3rd party apps on the App Store? Local and/or Push Notifications for your app while your app is open and in the foreground?

When testing my app, notifications are received but no iOS alert UI is shown.

But this behavior is seen in Apple's official Messages app:

The Local and Remote Notification Programming Guide says:

When the operating system delivers a local notification or remote notification and the target app is not running in the foreground, it can present the notification to the user through an alert, icon badge number, or sound.

If the app is running in the foreground when the notification is delivered, the app delegate receives a local or remote notification.

So yes, we can receive the notification data while in the foreground. But I see no way to present the native iOS notification alert UI.

```<code>-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    // I know we still receive the notification `userInfo` payload in the foreground.
    // This question is about displaying the stock iOS notification alert UI.

    // Yes, one *could* use a 3rd party toast alert framework.
    [self use3rdPartyToastAlertFrameworkFromGithub]
}
</code>```

Is Messages then using a private API to display the alert while in the foreground?

For the purpose of this question, please do not suggest any 3rd party "toast" pop-up alerts on github or etc. I'm only interested if this can be done using the stock, native iOS Local or Push Notification alerts UI while your application is open and in the foreground.

答:
Swift 3 version

This shows an alert when the application is in the foreground.

```<code>if #available(iOS 10.0, *)
{
    // need to setup the global notification delegate somewhere when your app starts
    //
    UNUserNotificationCenter.current().delegate = applicationDelegate

    // to show a message
    //
    let content = UNMutableNotificationContent()
    content.body = "MESSAGE"

    let request = UNNotificationRequest(identifier: "fred", content: content, trigger: nil)
    UNUserNotificationCenter.current().add(request)
    {
       error in // called when message has been sent

       debugPrint("Error: \(error)")
    }
}
</code>```

ApplicationDelegate's implementation of UNUserNotificationCenterDelegate

```<code>@available(iOS 10.0, *)
public func userNotificationCenter(_ center : UNUserNotificationCenter, willPresent notification : UNNotification, withCompletionHandler completionHandler : @escaping (UNNotificationPresentationOptions) -> Void)
{
    completionHandler([.alert]) // only-always show the alert
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When Apple's official iOS Messages app is open and in the foreground, new messages from other contacts trigger a stock, native iOS notification alert banner. See image below.

Is this possible in 3rd party apps on the App Store? Local and/or Push Notifications for your app while your app is open and in the foreground?

When testing my app, notifications are received but no iOS alert UI is shown.

But this behavior is seen in Apple's official Messages app:

The Local and Remote Notification Programming Guide says:

When the operating system delivers a local notification or remote notification and the target app is not running in the foreground, it can present the notification to the user through an alert, icon badge number, or sound.

If the app is running in the foreground when the notification is delivered, the app delegate receives a local or remote notification.

So yes, we can receive the notification data while in the foreground. But I see no way to present the native iOS notification alert UI.

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    // I know we still receive the notification `userInfo` payload in the foreground.
    // This question is about displaying the stock iOS notification alert UI.

    // Yes, one *could* use a 3rd party toast alert framework.
    [self use3rdPartyToastAlertFrameworkFromGithub]
}

Is Messages then using a private API to display the alert while in the foreground?

For the purpose of this question, please do not suggest any 3rd party "toast" pop-up alerts on github or etc. I'm only interested if this can be done using the stock, native iOS Local or Push Notification alerts UI while your application is open and in the foreground.

Body:
Swift 3 version

This shows an alert when the application is in the foreground.

if #available(iOS 10.0, *)
{
    // need to setup the global notification delegate somewhere when your app starts
    //
    UNUserNotificationCenter.current().delegate = applicationDelegate

    // to show a message
    //
    let content = UNMutableNotificationContent()
    content.body = "MESSAGE"

    let request = UNNotificationRequest(identifier: "fred", content: content, trigger: nil)
    UNUserNotificationCenter.current().add(request)
    {
       error in // called when message has been sent

       debugPrint("Error: \(error)")
    }
}

ApplicationDelegate's implementation of UNUserNotificationCenterDelegate

@available(iOS 10.0, *)
public func userNotificationCenter(_ center : UNUserNotificationCenter, willPresent notification : UNNotification, withCompletionHandler completionHandler : @escaping (UNNotificationPresentationOptions) -> Void)
{
    completionHandler([.alert]) // only-always show the alert
}


问:
WPF App with WCF Data - EF, Linq2Sql or WCF Data Services - None Seem 'Easy'
I am doing something I consider to be pretty normal (although I personally haven't had to do it before), and I have assumed there'd be a 'no-brainer' way forward, but Im yet to find it - which is really frustrating.

I will be creating a WPF application, which is a data-oriented business application. My data will come from a remote IIS server (that I control) that has a standard SQL server 2008 database, so Web services/WCF seem to be the way forward. The remote service needs to be secure (reasonably) via a user (of the WPF client) username/password login.

I dont want to use 3rd party ORM products, but I expect the data layer (between the service and the database) to be able to cope with very simple ORM type functionality (I really dont want to hand-craft a data retrieval and persistence layer). Im not worried about concurrency very much as this will be a fairly simple app.

My options seem to be one of the following:

ADO.NET Entity Framework over WCF

Linq2Sql over WCF

WCF Data Services

On further investigation, none of the above seem to be the 'no brainer' Im after

1) ADO.NET entity Framework - Ive had a play with this and getting all sorts of issues serializing objects over WCF. Even when  I try to generate POCO entities and use them, Im having to decorate service contracts with custom attributes just to get it to not error all the time, and I seem to have to hand-crank anything more than a flat object graph. It seems to me that EF simply isn't designed to be exposed via a service.

2) Linq2Sql - This doesn't seem much better than EF. I seem to have to hand-crank too much stuff. Ive tried the designer and SQLMetal but nothing seems to 'just work' - it all needs fiddling with.

3) WCF Data Services - this seems like a good option on the face of it, but essentially it seems like I'm just exposing my SQL database tables 'in the raw' over the service layer. Im not an expert in this technology by any means but it seems like a potentially dangerous approach, and on top of that it doesnt seem to support any kind of access security as standard (you have to hack it to require authentication it seems).

As I said, this scenario feels like it should have a no-brainer solution, but Im still scratching my head. Ive done lots of things with .NET technologies, but to be honest this area represents a bit of a hole in my understanding, so I apologize if any of my comments or assumptions are naive.

Of course, it may well be that the 'hacky' long-way-round on EF or Linq2SQL may be all I can do, in which case I can roll up my sleeves, and accept the fact that I haven't missed a more elegant solution.

Any help/advice will be much appreciated.

答:
This is a tad subjective, but i'll offer my opinion.

First of all, forget L2SQL - it's basically obsolete and doesn't have the full POCO support of EF4 (it can be done, but needs XML tinkering, or SQLMetal generation), which means serializaing your entities will be a left-to-right entity cloning nightmare.

I would go with ADO.NET Entity Framework over WCF, Entity Framework 4.0 specifically. You will have a wealth of flexibility in your model (including the ability to apply OO principles such as inheritance).

Use Self-Tracking-Entities. Yes, you have to decorate service contracts - this is by design, and there are many reasons for this.

You could always use DTO's, as opposed to serializing the actual EF entities.

OData is really good as well in it's flexibility and simplicity. But if your only consuming your model via a single client application, a specialized service layer (WCF) is a better approach IMO.


问:
How to find words beginning with capital letters in string literals in Intellij?
[A-Z][a-zA-Z]+

matches

fieldWithPath("fruits")

I was expecting it to only match something like below

fieldWithPath("FruitasdASSAdaasd")

Note: I'm using the inbuilt search in Intellij

答: Probably you did not check the "case sensitive" option. IDEA is case-insensitive by default.</p>


问:
Custom Yii2 TimestampBehavior
I have behavior in my model

```<code>public function behaviors()
{
    return [
        [
            'class' => SluggableBehavior::className(),
            'attribute' => 'title',
            // 'slugAttribute' => 'slug',
        ],
        [
            'class' => TimestampBehavior::className(),
            'createdAtAttribute' => 'created_at',
            'updatedAtAttribute' => 'updated_at',
            'value' => time(),
        ],
    ];
}
</code>```

Everything is working. But I need that only in one action does not work.
It is necessary that in actionView did not change "update_at" attribute. My actionView:

```<code>$model = $this->findModel($id);
$model->views++;
$model->save();
</code>```

How can I do this as correctly as possible?

答:
Use:

```<code>$model->save(false, ['views']);
</code>```

First parameter determines if validation should run (for this example it's not necessary), second determines attributes which should be saved.

Yii2 ActiveRecord - save() or Yii2 ActiveRecord - updateCounters() (which is better)

Title: Custom Yii2 TimestampBehavior

Body:
I have behavior in my model

public function behaviors()
{
    return [
        [
            'class' => SluggableBehavior::className(),
            'attribute' => 'title',
            // 'slugAttribute' => 'slug',
        ],
        [
            'class' => TimestampBehavior::className(),
            'createdAtAttribute' => 'created_at',
            'updatedAtAttribute' => 'updated_at',
            'value' => time(),
        ],
    ];
}

Everything is working. But I need that only in one action does not work.
It is necessary that in actionView did not change "update_at" attribute. My actionView:

$model = $this->findModel($id);
$model->views++;
$model->save();

How can I do this as correctly as possible?

Body:
Use:

$model->save(false, ['views']);

First parameter determines if validation should run (for this example it's not necessary), second determines attributes which should be saved.

Yii2 ActiveRecord - save() or Yii2 ActiveRecord - updateCounters() (which is better)


问:
Angular 4 - How to properly use .find()?
I've read most of questions similar to this, but still, I don't understand how to make .find() work in my app.

I have a service with API:

```<code>export class VehicleService {
  private defUrl = 'API';

  constructor(private http: Http) { }

  getVehicleByVehicleId(vehicleid?: any) {
    const url = (!vehicleid) ? this.defUrl : 'API1&vehicle_id=' + vehicleid;
    return this.http.get(url)
      .map(res => res.json());
  }

    searchVehicleId(description?: string) {
    const url = (!description) ? this.defUrl : 'API2&description=' + description;
    return this.http.get(url)
      .map(res => res.json().vehicles);
  }
}
</code>```

Component

```<code>export class VehicleComponent implements OnInit {

  ngOnInit() {

    this.searchQuery = new FormGroup({
      vehicleDescription: new FormControl('', Validators.required)
    });
  }

  constructor(private vehicleService: VehicleService) { }

  public fleet: Fleet[];
  public description: Description[];
  public searchQuery: FormGroup;
  public searchVehicleId: any;

  public searchByVehicleId(searchQuery) {
    this.vehicleService
      .searchVehicleId(searchQuery.value.vehicleDescription)
      .subscribe(searchQuery => {
        this.description = searchQuery;
        this.searchVehicleId = this.description.find() // <= HOW TO IMPLEMENT THIS?
    this.vehicleService
      .getVehicleByVehicleId(this.searchVehicleId)
      .subscribe(searchQuery => {
        this.vehicle = searchQuery;
      })
      });
  }
interface Vehicle {
  status: number;
  dallases: Vehicle[];
}

interface VehicleDetails {
  vehicle_id: number;
  dallassettings: string;
  dallasupdated: string;
  dallas_list: DallasList[];
}

interface DallasList {
  number: number;
  auth: number;
}

//////////////////////////////////
//////////////////////////////////

interface Description {
  vehicles: DescriptionDetails[];
}

interface DescriptionDetails {
  id: number;
  custom_description: string;
  description: string;
}
</code>```

API2

```<code>{
    "vehicles": [{
        "description": "SKODA ROOMSTER",
        "id": 123456,
        "custom_description": ""
    }, {
        "description": "SKODA ROOMSTER",
        "id": 123456789,
        "custom_description": ""
    }]
}
</code>```

So, what I do here is: pass description inside FormGroup - vehicleDescription field to searchByVehicleId method. Here I want to find id of passed vehicleDescription velue (it's "description" field in API2). When we find the id, we use it to further in this.vehicleService.getVehicleByVehicleId...

Main problem is - I have no idea, how to properly implement .find().

Thanks

答:
The MDN docs:</p>

```<code>this.searchVehicleId = this.description.find(x => x.id === someId);
</code>```

Body:
I've read most of questions similar to this, but still, I don't understand how to make .find() work in my app.

I have a service with API:

export class VehicleService {
  private defUrl = 'API';

  constructor(private http: Http) { }

  getVehicleByVehicleId(vehicleid?: any) {
    const url = (!vehicleid) ? this.defUrl : 'API1&vehicle_id=' + vehicleid;
    return this.http.get(url)
      .map(res => res.json());
  }

    searchVehicleId(description?: string) {
    const url = (!description) ? this.defUrl : 'API2&description=' + description;
    return this.http.get(url)
      .map(res => res.json().vehicles);
  }
}

Component

export class VehicleComponent implements OnInit {

  ngOnInit() {

    this.searchQuery = new FormGroup({
      vehicleDescription: new FormControl('', Validators.required)
    });
  }

  constructor(private vehicleService: VehicleService) { }

  public fleet: Fleet[];
  public description: Description[];
  public searchQuery: FormGroup;
  public searchVehicleId: any;

  public searchByVehicleId(searchQuery) {
    this.vehicleService
      .searchVehicleId(searchQuery.value.vehicleDescription)
      .subscribe(searchQuery => {
        this.description = searchQuery;
        this.searchVehicleId = this.description.find() // <= HOW TO IMPLEMENT THIS?
    this.vehicleService
      .getVehicleByVehicleId(this.searchVehicleId)
      .subscribe(searchQuery => {
        this.vehicle = searchQuery;
      })
      });
  }
interface Vehicle {
  status: number;
  dallases: Vehicle[];
}

interface VehicleDetails {
  vehicle_id: number;
  dallassettings: string;
  dallasupdated: string;
  dallas_list: DallasList[];
}

interface DallasList {
  number: number;
  auth: number;
}

//////////////////////////////////
//////////////////////////////////

interface Description {
  vehicles: DescriptionDetails[];
}

interface DescriptionDetails {
  id: number;
  custom_description: string;
  description: string;
}

API2

{
    "vehicles": [{
        "description": "SKODA ROOMSTER",
        "id": 123456,
        "custom_description": ""
    }, {
        "description": "SKODA ROOMSTER",
        "id": 123456789,
        "custom_description": ""
    }]
}

So, what I do here is: pass description inside FormGroup - vehicleDescription field to searchByVehicleId method. Here I want to find id of passed vehicleDescription velue (it's "description" field in API2). When we find the id, we use it to further in this.vehicleService.getVehicleByVehicleId...

Main problem is - I have no idea, how to properly implement .find().

Thanks

Body:
The MDN docs:

this.searchVehicleId = this.description.find(x => x.id === someId);


问:
gcc/diab: keep unused function / sections
I have a project in which I would like to keep certain functions / sections in the linking phase.

I tried:

```<code>static void stub_enforcer(void) __attribute__ ((used))
</code>```

But this is for the compiler, and not for the linker.

Now that the linker takes charge and -gc-sections is used, the function I wanted to keep is "gone" :(

```<code>Removing unused section '.text.func2' in file './src/func2.o'
</code>```

How can I instruct the linker not to remove the functions I need.

The reason I want to do this is a post build usage of the function, by changing stuff on the binary.

答:
I have found a solution by controlling the LD script,

I have put the stub_enforcer in a section, and used KEEP() command to make sure the linker will not throw it.

It works.

Body:
I have a project in which I would like to keep certain functions / sections in the linking phase.

I tried:

static void stub_enforcer(void) __attribute__ ((used))

But this is for the compiler, and not for the linker.

Now that the linker takes charge and -gc-sections is used, the function I wanted to keep is "gone" :(

Removing unused section '.text.func2' in file './src/func2.o'

How can I instruct the linker not to remove the functions I need.

The reason I want to do this is a post build usage of the function, by changing stuff on the binary.


问:
text-overflow in span element not cutting texta outside element width
I'm trying to make a div with 3 spans inside where the middle one should "compress", ie cut the extra text when the size of the div is small.

The result I'm looking for is

```<code>A Very lon... A
          ^ here it should get cut with "text-overflow: ellipsis;"
</code>```

Somehow the text-overflow: ellipsis; is not being applied to the span.

Any idea what I am missing?

Tried with width, display, overflow and nothing seems to work... tested both Chrome and Firefox.

div {
  border-radius: 5px;
  border: 1px solid #333;
  padding: 10px 20px;
  width: 100px;
}

div span {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

#long-text {
  width: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <span>A</span>
  <span id="long-text">Very long text here....</span>
  <span>A</span>
</div></code>```

答:
as XYZ said span is an inline element. And you need to change it's display property to block or inline-block depending on the desired effect. In your case it will be </p>

```<code>#long-text{
display: inline-block
width: 35px;
}
</code>```

Body:
I'm trying to make a div with 3 spans inside where the middle one should "compress", ie cut the extra text when the size of the div is small.

The result I'm looking for is

A Very lon... A
          ^ here it should get cut with "text-overflow: ellipsis;"

Somehow the text-overflow: ellipsis; is not being applied to the span.

Any idea what I am missing?

Tried with width, display, overflow and nothing seems to work... tested both Chrome and Firefox.

div {
  border-radius: 5px;
  border: 1px solid #333;
  padding: 10px 20px;
  width: 100px;
}

div span {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

#long-text {
  width: 20px;
}

  A
  Very long text here....
  A

Body:
as XYZ said span is an inline element. And you need to change it's display property to block or inline-block depending on the desired effect. In your case it will be

#long-text{
display: inline-block
width: 35px;
}


问:
Android Snackbar not appearing when I click Option Item
I'm trying to display a Snackbar whenever I click my option item but when I do that, my app crashes. Does anyone know what is wrong here and what can be done to resolve this issue?

java

```<code>public class MainActivity extends AppCompatActivity {
    private static CoordinatorLayout coordinatorLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            Snackbar.make(coordinatorLayout, "Single Line SnackBar Demo.", Snackbar.LENGTH_SHORT).show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
</code>```

Logcat

```<code>04-17 09:22:58.260 20108-20108/com.apptacularapps.snackbar E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.apptacularapps.snackbar, PID: 20108
                                                                             java.lang.NullPointerException
                                                                                at android.support.design.widget.Snackbar.<init>(Snackbar.java:183)
                                                                                at android.support.design.widget.Snackbar.make(Snackbar.java:215)
                                                                                at com.apptacularapps.snackbar.MainActivity.onOptionsItemSelected(MainActivity.java:49)
                                                                                at android.app.Activity.onMenuItemSelected(Activity.java:2600)
                                                                                at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:404)
                                                                                at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:179)
                                                                                at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
                                                                                at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
                                                                                at android.support.v7.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:69)
                                                                                at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:169)
                                                                                at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:760)
                                                                                at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:811)
                                                                                at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
                                                                                at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:958)
                                                                                at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:948)
                                                                                at android.support.v7.view.menu.MenuPopupHelper.onItemClick(MenuPopupHelper.java:191)
                                                                                at android.widget.AdapterView.performItemClick(AdapterView.java:299)
                                                                                at android.widget.AbsListView.performItemClick(AbsListView.java:1113)
                                                                                at android.widget.AbsListView$PerformClick.run(AbsListView.java:2911)
                                                                                at android.widget.AbsListView$3.run(AbsListView.java:3645)
                                                                                at android.os.Handler.handleCallback(Handler.java:733)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:136)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5001)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
                                                                                at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
Initialise CoordinatorLayout or pass any child view of CoordinatorLayout

i.e.

```<code>coordinatorLayout = (CoordinatorLayout) findViewById(R.id.yourCoordinatorLayoutId);
</code>```

OR

```<code>TextView textView = (TextView) findViewById(R.id.yourTextViewID);
</code>```

where your TexView is residing inside your CoordinatorLayout and then pass this view to your Snackbar like:

```<code>Snackbar.make(textView, "Single Line SnackBar Demo.", Snackbar.LENGTH_SHORT).show();
</code>```

Body:
I'm trying to display a Snackbar whenever I click my option item but when I do that, my app crashes. Does anyone know what is wrong here and what can be done to resolve this issue?

java

public class MainActivity extends AppCompatActivity {
    private static CoordinatorLayout coordinatorLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            Snackbar.make(coordinatorLayout, "Single Line SnackBar Demo.", Snackbar.LENGTH_SHORT).show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Logcat

04-17 09:22:58.260 20108-20108/com.apptacularapps.snackbar E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.apptacularapps.snackbar, PID: 20108
                                                                             java.lang.NullPointerException
                                                                                at android.support.design.widget.Snackbar.<init>(Snackbar.java:183)
                                                                                at android.support.design.widget.Snackbar.make(Snackbar.java:215)
                                                                                at com.apptacularapps.snackbar.MainActivity.onOptionsItemSelected(MainActivity.java:49)
                                                                                at android.app.Activity.onMenuItemSelected(Activity.java:2600)
                                                                                at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:404)
                                                                                at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:179)
                                                                                at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
                                                                                at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
                                                                                at android.support.v7.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:69)
                                                                                at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:169)
                                                                                at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:760)
                                                                                at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:811)
                                                                                at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
                                                                                at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:958)
                                                                                at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:948)
                                                                                at android.support.v7.view.menu.MenuPopupHelper.onItemClick(MenuPopupHelper.java:191)
                                                                                at android.widget.AdapterView.performItemClick(AdapterView.java:299)
                                                                                at android.widget.AbsListView.performItemClick(AbsListView.java:1113)
                                                                                at android.widget.AbsListView$PerformClick.run(AbsListView.java:2911)
                                                                                at android.widget.AbsListView$3.run(AbsListView.java:3645)
                                                                                at android.os.Handler.handleCallback(Handler.java:733)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:136)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5001)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
                                                                                at dalvik.system.NativeStart.main(Native Method)

Body:
Initialise CoordinatorLayout or pass any child view of CoordinatorLayout

i.e.

coordinatorLayout = (CoordinatorLayout) findViewById(R.id.yourCoordinatorLayoutId);

OR

TextView textView = (TextView) findViewById(R.id.yourTextViewID);

where your TexView is residing inside your CoordinatorLayout and then pass this view to your Snackbar like:

Snackbar.make(textView, "Single Line SnackBar Demo.", Snackbar.LENGTH_SHORT).show();


问:
How to pass an integer to a parameter through HashMap?
Am new to java and have a query.Please suggest me a solution :

Am doing API level testing and need to pass the request body parameters of a service like below :

答:
Convert your integer value in string and then pass it, as your method expect String parameter, you cannot directly pass integer</p>

```<code>sell.requestAdd( "Amount",String.valueOf(Your_Integer_Value));
</code>```

Body:
Convert your integer value in string and then pass it, as your method expect String parameter, you cannot directly pass integer

sell.requestAdd( "Amount",String.valueOf(Your_Integer_Value));


答: You can create a class which holds string and int values. In other words, HaspMap<String,Object>.

Title: How to pass an integer to a parameter through HashMap?

Body:
Am new to java and have a query.Please suggest me a solution :

Am doing API level testing and need to pass the request body parameters of a service like below :


问:
Orientation corners of a QR-code
As of now, when Android Vision detects a QR-code, the array "Barcode.cornerPoints" (which contains the code's corner points) is populated in a seemingly random order. I need is to determine which 3 out of the 4 corner points that contains "orientation squares".

The current approach I am using is very unsatisfying:

For every detected QR-code, I am forced to create a bitmap and attempt to find the QR-code again with another library (Zxing) that always returns the corner points in a consistent order with respect to rotation.

If Zxing finds the QR-code (which sadly doesn't happen about four times out of five), I need to cross-check and match the Zxing-corners with Android Vision corners.

What I would like is to get the array "Barcode.cornerPoints" populated with respect to orientation.

For example and clarification:

```<code>cornerPoints[0] = //First corner-point with an orientation square
cornerPoints[1] = //Second corner-point with an orientation square
cornerPoints[2] = //Third corner-point with an orientation square
cornerPoints[3] = //The corner-point that does not contain a orientation square
</code>```

> Like in this picture <

I have been trying to find a clever workaround to this issue for quire a while now but I can't come up with any good solution, and it does not appear as Google has open source'd the code used when population the qrCorners array so i can't extend it...

Any help out there? I am not the only one who has been looking for a solution to this issue:

https://github.com/googlesamples/android-vision/issues/103

答:
I am in a similar situation as well. What might help you to know is that Android Vision does not return the corner points in a completely random order.

I believe that the detector scans the image from top left to bottom right of the frame. The QR-code-corner which is detected first in the image will be returned as corner 0 and the rest in a clockwise direction.

What would be really helpful was if Android Vision returned the corners like you said, in a "static" order depending on orientation. I barely see any reason for the chosen way to return the corner points. Maybe better performance? For the QR-code to be read it has to be done according to a certain orientation which is determined by the corners of the QR-code. Which means Android Vision already has identified the orientation and corners but does not give this information to us.
Maybe this could be added in future updates?

Title: Orientation corners of a QR-code

Body:
As of now, when Android Vision detects a QR-code, the array "Barcode.cornerPoints" (which contains the code's corner points) is populated in a seemingly random order. I need is to determine which 3 out of the 4 corner points that contains "orientation squares".

The current approach I am using is very unsatisfying:

For every detected QR-code, I am forced to create a bitmap and attempt to find the QR-code again with another library (Zxing) that always returns the corner points in a consistent order with respect to rotation.

If Zxing finds the QR-code (which sadly doesn't happen about four times out of five), I need to cross-check and match the Zxing-corners with Android Vision corners.

What I would like is to get the array "Barcode.cornerPoints" populated with respect to orientation.

For example and clarification:

cornerPoints[0] = //First corner-point with an orientation square
cornerPoints[1] = //Second corner-point with an orientation square
cornerPoints[2] = //Third corner-point with an orientation square
cornerPoints[3] = //The corner-point that does not contain a orientation square

> Like in this picture <

I have been trying to find a clever workaround to this issue for quire a while now but I can't come up with any good solution, and it does not appear as Google has open source'd the code used when population the qrCorners array so i can't extend it...

Any help out there? I am not the only one who has been looking for a solution to this issue:

https://github.com/googlesamples/android-vision/issues/103


问:
lambda parameter deduced incorrect
why is this code incorrect under C++14 or even C++17?</p>

```<code>template <typename T>
function<T(T, T)> ReturnLambda () {
    return [] (T x, T y) { return x*y; };
    // return [] (auto x, auto y) { return x*y; };    // also incorrect
}

int main() {
    auto f = ReturnLambda();
    cout << f(3, 4) << endl;

}
</code>```

答:
Template argument deduction only works with function arguments, while ReturnLambda() doesn't have any of that; There's just no way to deduce the template argument T when invoking ReturnLambda(); you have to specify it explicitly. e.g.

```<code>auto f = ReturnLambda<int>();
</code>```

Title: lambda parameter deduced incorrect

Body:
why is this code incorrect under C++14 or even C++17?

template <typename T>
function<T(T, T)> ReturnLambda () {
    return [] (T x, T y) { return x*y; };
    // return [] (auto x, auto y) { return x*y; };    // also incorrect
}

int main() {
    auto f = ReturnLambda();
    cout << f(3, 4) << endl;

}

Body:
Template argument deduction only works with function arguments, while ReturnLambda() doesn't have any of that; There's just no way to deduce the template argument T when invoking ReturnLambda(); you have to specify it explicitly. e.g.

auto f = ReturnLambda<int>();


问:
Reaching a control, within a ContentControl from view's code behind
My view's XAML is only containing a custom control.

A bit further, in a Resource Dictionary, I have a Style for this custom control, and inside this, I have a TextBox. My goal would be to reach this TextBox from the view's code behind, and set it's focus, when the view's DataContext changed.

I tried to use x:Name to give a name to the custom control on the view's XAML, and also give a name to the TextBox inside the control's style (so essentially trying to reach it from code behind like: this.MyCustomControl.SearchTextBox). This did not work.

What would be the best practice to solve this issue?

答:
Try visual tree helper

```<code>            VisualTreeHelper.GetChild(object, index)
</code>```

msdn link

Body:
Try visual tree helper

            VisualTreeHelper.GetChild(object, index)

msdn link