问:
Qt How sent post HTTPS with SSL
Qt How send simple post HTTPS with SSL ?

The program is supposed to send posts via HTTPS using QNetworkAccessManager.

Below is a simple example of my code.

```<code>QUrlQuery params;
QByteArray dane;
params.addQueryItem("mWyslijpost", ui->lineEdit->text());
dane.append(params.toString());

QUrl url("https://81.2.244.83/Testpostssl/infotest.php");

QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
QNetworkReply *reply = manager->post(request, dane);

QFile certFile(":/crt/cert.crt");
Q_ASSERT(certFile.open(QIODevice::ReadOnly));

QSslCertificate cert(&certFile, QSsl::Pem);

QSslSocket * sslSocket = new QSslSocket(this);
sslSocket->addCaCertificate(cert);

sslSocket->connectToHostEncrypted(SERVER,  443);

if (!sslSocket->waitForEncrypted())
{
    qDebug() << "Info " << sslSocket->errorString();
    return false;
}

QSslConfiguration config = sslSocket->sslConfiguration();
config.setProtocol(QSsl::TlsV1_2);

sslSocket->setSslConfiguration(config);
reply->setSslConfiguration(config);

// wait
QEventLoop elCzekaj;
connect(reply, SIGNAL(finished()), &elCzekaj, SLOT(quit()));
elCzekaj.exec();

if(reply->error() == QNetworkReply::NoError)
{
    qDebug() << reply->readAll();
 }
else
{
    qDebug() << "Error...";
    qDebug() << reply->errorString();
}
</code>```

How to download certificates from server ?
How to configure QSsl ?

答:
To get the cert from the peer try something like this:

```<code>QSslSocket *socket = new QSslSocket();

QObject::connect(socket,
                 &QSslSocket::encrypted,
                 [=](){qDebug() << socket->peerCertificate() << " cert";}
);

socket->connectToHostEncrypted("stackoverflow.com", 443);
</code>```

Regarding the question: "How to configure QSsl", that depends on what you want to do. If you simply want to fetch something from a Webserver over TLS, just use the QNetworkAccessManager. The defaults there will do.

Title: Qt How sent post HTTPS with SSL

Body:
Qt How send simple post HTTPS with SSL ?

The program is supposed to send posts via HTTPS using QNetworkAccessManager.

Below is a simple example of my code.

QUrlQuery params;
QByteArray dane;
params.addQueryItem("mWyslijpost", ui->lineEdit->text());
dane.append(params.toString());

QUrl url("https://81.2.244.83/Testpostssl/infotest.php");

QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
QNetworkReply *reply = manager->post(request, dane);

QFile certFile(":/crt/cert.crt");
Q_ASSERT(certFile.open(QIODevice::ReadOnly));

QSslCertificate cert(&certFile, QSsl::Pem);

QSslSocket * sslSocket = new QSslSocket(this);
sslSocket->addCaCertificate(cert);

sslSocket->connectToHostEncrypted(SERVER,  443);

if (!sslSocket->waitForEncrypted())
{
    qDebug() << "Info " << sslSocket->errorString();
    return false;
}

QSslConfiguration config = sslSocket->sslConfiguration();
config.setProtocol(QSsl::TlsV1_2);

sslSocket->setSslConfiguration(config);
reply->setSslConfiguration(config);

// wait
QEventLoop elCzekaj;
connect(reply, SIGNAL(finished()), &elCzekaj, SLOT(quit()));
elCzekaj.exec();

if(reply->error() == QNetworkReply::NoError)
{
    qDebug() << reply->readAll();
 }
else
{
    qDebug() << "Error...";
    qDebug() << reply->errorString();
}

How to download certificates from server ?
How to configure QSsl ?

Body:
To get the cert from the peer try something like this:

QSslSocket *socket = new QSslSocket();

QObject::connect(socket,
                 &QSslSocket::encrypted,
                 [=](){qDebug() << socket->peerCertificate() << " cert";}
);

socket->connectToHostEncrypted("stackoverflow.com", 443);

Regarding the question: "How to configure QSsl", that depends on what you want to do. If you simply want to fetch something from a Webserver over TLS, just use the QNetworkAccessManager. The defaults there will do.


来源: stackexchange

问:
How to view a JSON object constructed using objects before using the post()
Hellloo...
I'm constructing a JSON object using JAVA eclipse and that object will be used in the

```<code>given()
.body(constructed)
.post("url")
</code>```

I wanted to review the constructed JSON object before sending it in the post.

can you guys tell is there any way that the request sent will be seen.?

答:
you may use fiddler tool to monitor the requests and response (network traffic) from your system. Link to install fiddler http://www.telerik.com/fiddler
you can debug traffic from PC and mobile devices and check that the proper cookies, headers, and cache directives are transferred between the client and server.</p>

ContentLicense: CC BY-SA 3.0

Body:
Hellloo...
I'm constructing a JSON object using JAVA eclipse and that object will be used in the

given()
.body(constructed)
.post("url")

I wanted to review the constructed JSON object before sending it in the post.

can you guys tell is there any way that the request sent will be seen.?


问:
How do I provide databinding to an array using Aurelia and a mutiselect checkboxlist UI?
So when the page loads, if the checkboxes were already selected previously, and the data is in the database, then the checkboxes should display as being checked in the form. Currently they are not checked (not bound to the database).

Here is the html

```<code><div class="multiselect" style="width:170px; margin-top:30px">
<div class="selectBox" click.delegate="showCheckboxes('causes')">
<select>
<option style="font-weight:normal">Cause(s) to support</option>
</select>
<div class="overSelect"></div>
</div>
<iron-dropdown id="causes" horizontal-align="right" vertical-align="top" style="margin-top:25px;">
<div class="dropdown-content" style="background-color:white;box-sizing: border-box; max-width: 270px; max-height: 362px;overflow:auto;border:1px #dadada solid">
<label repeat.for="cause of causes" for="cause" style="display:block;text-align:left;margin-left:5px;margin-right:5px">
<input type="checkbox" value.bind="cause" checked.bind="selectedCause" change.delegate="causePicked()"> ${cause}
</label>
</div>
</iron-dropdown>
</div>
</code>```

here is the JavaScript

```<code>  causes = ['Christian', 'Environmental', 'Hunger', 'Animal Rights', 'Homeless', 'Veterans', 'Elderly', 'other'];
  talents = ['music', 'athletics', 'childcare', 'mechanics', 'construction', 'computers', 'communication', 'chess playing', 'listening', 'other'];
  works = ['hashbrown slinging', 'nail hammering', 'leaf removal', 'floor mopping', 'counseling', 'other'];
  selectedCause = [];
  selectedTalent = [];
  selectedWork = [];

  async activate() {
    this.uid = this.app.auth.getTokenPayload().sub;
    this.user = await this.app.appState.getUser(this.uid);
    //this.app.appState.user;
    this.role = this.user.userType;
    this.causes.sort();
    this.talents.sort();
    this.works.sort();
    if (this.user.userType === 'Charity'){
      this.role = 'Charity Manager';
    }
  }
</code>```

here is the link to repo and src code
https://github.com/WebJamApps/combined-front/blob/dev/src/dashboard-child-routes/user-account.html

https://github.com/WebJamApps/combined-front/blob/dev/src/dashboard-child-routes/user-account.js

Any suggestions are very appreciated, thanks

答:
I was able to do it and the code examples are here for anyone else trying to figure this out

https://github.com/WebJamApps/combined-front/blob/dev/src/dashboard-child-routes/user-account.html

https://github.com/WebJamApps/combined-front/blob/dev/src/dashboard-child-routes/user-account.js

Body:
So when the page loads, if the checkboxes were already selected previously, and the data is in the database, then the checkboxes should display as being checked in the form. Currently they are not checked (not bound to the database).

Here is the html

<select>
<option style="font-weight:normal">Cause(s) to support</option>
</select>

<iron-dropdown id="causes" horizontal-align="right" vertical-align="top" style="margin-top:25px;">

<input type="checkbox" value.bind="cause" checked.bind="selectedCause" change.delegate="causePicked()"> ${cause}

</iron-dropdown>

here is the JavaScript

  causes = ['Christian', 'Environmental', 'Hunger', 'Animal Rights', 'Homeless', 'Veterans', 'Elderly', 'other'];
  talents = ['music', 'athletics', 'childcare', 'mechanics', 'construction', 'computers', 'communication', 'chess playing', 'listening', 'other'];
  works = ['hashbrown slinging', 'nail hammering', 'leaf removal', 'floor mopping', 'counseling', 'other'];
  selectedCause = [];
  selectedTalent = [];
  selectedWork = [];

  async activate() {
    this.uid = this.app.auth.getTokenPayload().sub;
    this.user = await this.app.appState.getUser(this.uid);
    //this.app.appState.user;
    this.role = this.user.userType;
    this.causes.sort();
    this.talents.sort();
    this.works.sort();
    if (this.user.userType === 'Charity'){
      this.role = 'Charity Manager';
    }
  }

here is the link to repo and src code
https://github.com/WebJamApps/combined-front/blob/dev/src/dashboard-child-routes/user-account.html

https://github.com/WebJamApps/combined-front/blob/dev/src/dashboard-child-routes/user-account.js

Any suggestions are very appreciated, thanks


问:
Laravel validator, add parameter on validation
I have begun tinkering with validators in Laravel and seem to have programmed myself into a corner.

Background

I have a method which I use to check if an address exists through Google Maps. Since I started having just one file and validation in that file I just let it return an object containing if longitude and latitude matched and the formated address.

```<code>return (object) ['result' => (bool) $match, 'formatedAddress' => (string) $googleMaps->formatted_address];
</code>```

(Typecast for clarity, no actual typecast in code at this point.)

This worked well in the controller since I could reuse the variables within the method, but not so well after moving it to AppServiceProvider.

Question:

Is there a way to make Validator::extend() set a public parameter upon validation so I can reach the formatted address? Or do I have to go about doing this in another way?

Using PHP 5.6 and Laravel 5.4.

答:
I actually found the answer while tinkering a bit more. I made an error in my conditions so it did not even reach the point where I set the variable.
Basically, this is the solution:

```<code>Validator::extend('location', function (
    $attribute, $value, $parameters, $validator
) {
    $validator->location = true;
}
</code>```

Hope my slight error and oversight can help someone else to not get stuck in the same way.

Body:
I have begun tinkering with validators in Laravel and seem to have programmed myself into a corner.

Background

I have a method which I use to check if an address exists through Google Maps. Since I started having just one file and validation in that file I just let it return an object containing if longitude and latitude matched and the formated address.

return (object) ['result' => (bool) $match, 'formatedAddress' => (string) $googleMaps->formatted_address];

(Typecast for clarity, no actual typecast in code at this point.)

This worked well in the controller since I could reuse the variables within the method, but not so well after moving it to AppServiceProvider.

Question:

Is there a way to make Validator::extend() set a public parameter upon validation so I can reach the formatted address? Or do I have to go about doing this in another way?

Using PHP 5.6 and Laravel 5.4.

Body:
I actually found the answer while tinkering a bit more. I made an error in my conditions so it did not even reach the point where I set the variable.
Basically, this is the solution:

Validator::extend('location', function (
    $attribute, $value, $parameters, $validator
) {
    $validator->location = true;
}

Hope my slight error and oversight can help someone else to not get stuck in the same way.


问:
SQLiteDatabase.execSQL(query) - Multiple SQL commands inside the onCreate() method not working
I am new to android. I haven't worked with SQLite DBs before.

I think this is a very basic question, but I am unable to find the solution.

The code is here (assume declarations)

```<code>public void onCreate(SQLiteDatabase db) {

    String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + FORMULA + "("
            + CAT_CD + " TEXT ," + S_CAT_CD + " TEXT, PRIMARY
 KEY(CAT_CD,S_CAT_CD))";
    db.execSQL(CREATE_CATEGORIES_TABLE);

    String CREATE_CAT_DESC_TABLE="CREATE TABLE "+ FORMULA_CAT_DESC + "
("+CAT_CD+" TEXT PRIMARY KEY, "+ DESC +" TEXT ) ";
    db.execSQL(CREATE_CAT_DESC_TABLE);

    String CREATE_CURRENCY_TABLE="CREATE TABLE "+ VI_CURRENCY + "("+
CURRENCY_CD +" TEXT PRIMARY KEY, "+ CURRENCY_SIGN +" TEXT ) ";
    db.execSQL(CREATE_CURRENCY_TABLE);

   String query=  "INSERT INTO "+ VI_CURRENCY +" ("+CURRENCY_CD +",
"+CURRENCY_SIGN+ ") VALUES " +
            "('INR', '₹'), " +
            " ('USD','$') " +
            "('JPY','¥') ";
    db.execSQL(query);
 }
</code>```

The first three commands execute successfully, while by executing the insert command,  SQLite throws an exeption.

答:
If you want to insert multiple records, then you should take data in hashmap object in key value pair. Use iterator on the same and insert data in table.</p>

```<code>        Map<String,String> myMap = new HashMap<>();
        myMap.put("INR","₹");
        myMap.put("USD","$");
        myMap.put("JPY","¥");

 Iterator it = myMap.entrySet().iterator();
    while (it.hasNext()) {
      Map.Entry pair = (Map.Entry)it.next();
      String query1 =  "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " + "("+ pair.getKey()+ "," + pair.getvalue()+)" ;
    db.execSQL(query1);
    it.remove(); // avoids a ConcurrentModificationException
}
</code>```

Body:
I am new to android. I haven't worked with SQLite DBs before.

I think this is a very basic question, but I am unable to find the solution.

The code is here (assume declarations)

public void onCreate(SQLiteDatabase db) {

    String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + FORMULA + "("
            + CAT_CD + " TEXT ," + S_CAT_CD + " TEXT, PRIMARY
 KEY(CAT_CD,S_CAT_CD))";
    db.execSQL(CREATE_CATEGORIES_TABLE);

    String CREATE_CAT_DESC_TABLE="CREATE TABLE "+ FORMULA_CAT_DESC + "
("+CAT_CD+" TEXT PRIMARY KEY, "+ DESC +" TEXT ) ";
    db.execSQL(CREATE_CAT_DESC_TABLE);

    String CREATE_CURRENCY_TABLE="CREATE TABLE "+ VI_CURRENCY + "("+
CURRENCY_CD +" TEXT PRIMARY KEY, "+ CURRENCY_SIGN +" TEXT ) ";
    db.execSQL(CREATE_CURRENCY_TABLE);

   String query=  "INSERT INTO "+ VI_CURRENCY +" ("+CURRENCY_CD +",
"+CURRENCY_SIGN+ ") VALUES " +
            "('INR', '₹'), " +
            " ('USD','$') " +
            "('JPY','¥') ";
    db.execSQL(query);
 }

The first three commands execute successfully, while by executing the insert command,  SQLite throws an exeption.

Body:
If you want to insert multiple records, then you should take data in hashmap object in key value pair. Use iterator on the same and insert data in table.

        Map<String,String> myMap = new HashMap<>();
        myMap.put("INR","₹");
        myMap.put("USD","$");
        myMap.put("JPY","¥");

 Iterator it = myMap.entrySet().iterator();
    while (it.hasNext()) {
      Map.Entry pair = (Map.Entry)it.next();
      String query1 =  "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " + "("+ pair.getKey()+ "," + pair.getvalue()+)" ;
    db.execSQL(query1);
    it.remove(); // avoids a ConcurrentModificationException
}


问:
Different Table format style in datatable using laravel framework
Using datatable is it possible to achieve below mentioned table format?

答:
You should use rowspan on  not in tbody.
Example here</p>


问:
Issue on adding SSH key to GitHub
I have got an issue that seems about the format of SSH key used by GitHub. I used Git Bash to generate a new SSH key:

```<code>$ ssh-keygen -t rsa -C "youremail@youremail.com"
</code>```

Then, I copied the key to the SSH section in settings of my GitHub account page. However, it came with the issue notice as follows:

```<code>Key is invalid. It must begin with 'ssh-ed25519', 'ssh-rsa', 'ssh-dss', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', or 'ecdsa-sha2-nistp521'. Check that you're copying the public half of the key
</code>```

Following that, I edited my SSH key starting with ssh-rsa and my email address at the end. However, the issue is still there.

What is the solution to this?

答: I ran into the same problem and it turns out it was due to there being a - in the comment. GitHub apparently doesn't like -, but _ is OK though.

ContentLicense: CC BY-SA 4.0

Title: Issue on adding SSH key to GitHub

Body:
I have got an issue that seems about the format of SSH key used by GitHub. I used Git Bash to generate a new SSH key:

$ ssh-keygen -t rsa -C "youremail@youremail.com"

Then, I copied the key to the SSH section in settings of my GitHub account page. However, it came with the issue notice as follows:

Key is invalid. It must begin with 'ssh-ed25519', 'ssh-rsa', 'ssh-dss', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', or 'ecdsa-sha2-nistp521'. Check that you're copying the public half of the key

Following that, I edited my SSH key starting with ssh-rsa and my email address at the end. However, the issue is still there.

What is the solution to this?


问:
Python 3 TypeError: must be str, not bytes with sys.stdout.write()
I was looking for a way to run an external process from python script and print its stdout messages during the execution.

The code below works, but prints no stdout output during runtime. When it exits I am getting the following error:

sys.stdout.write(nextline) TypeError:must be str,not bytes

```<code>p = subprocess.Popen(["demo.exe"],stdout = subprocess.PIPE, stderr= subprocess.PIPE)
# Poll process for new output until finished
while True:
    nextline = p.stdout.readline()
    if nextline == '' and p.poll() != None:
        break
    sys.stdout.write(nextline)
    sys.stdout.flush()

output = p.communicate()[0]
exitCode = p.returncode
</code>```

I am using python 3.3.2

答:
While the accepted answer will work fine if the bytes you have from your subprocess are encoded using sys.stdout.encoding (or a compatible encoding, like reading from a tool that outputs ASCII and your stdout uses UTF-8), the correct way to write arbitrary bytes to stdout is:

```<code>sys.stdout.buffer.write(some_bytes_object)
</code>```

This will just output the bytes as-is, without trying to treat them as text-in-some-encoding.

Body:
I was looking for a way to run an external process from python script and print its stdout messages during the execution.

The code below works, but prints no stdout output during runtime. When it exits I am getting the following error:

sys.stdout.write(nextline) TypeError:must be str,not bytes

p = subprocess.Popen(["demo.exe"],stdout = subprocess.PIPE, stderr= subprocess.PIPE)
# Poll process for new output until finished
while True:
    nextline = p.stdout.readline()
    if nextline == '' and p.poll() != None:
        break
    sys.stdout.write(nextline)
    sys.stdout.flush()

output = p.communicate()[0]
exitCode = p.returncode

I am using python 3.3.2

Body:
While the accepted answer will work fine if the bytes you have from your subprocess are encoded using sys.stdout.encoding (or a compatible encoding, like reading from a tool that outputs ASCII and your stdout uses UTF-8), the correct way to write arbitrary bytes to stdout is:

sys.stdout.buffer.write(some_bytes_object)

This will just output the bytes as-is, without trying to treat them as text-in-some-encoding.


问:
Keep window on top WPF
I have problem to keep Window on TOP ? I work with MVVM WPF

I have this code in ConfigRole Model:

```<code>if (!System.Windows.Application.Current.Windows.OfType<ConfigRole>().Any())
{
    ConfigRoleModel configRoleModel = new ConfigRoleModel();
    ConfigRole winconfigRole = new ConfigRole();
    winconfigRole.DataContext = configRoleModel;
    winconfigRole.Show();
    winconfigRole.Topmost = true;
    winconfigRole.Focus();
}
</code>```

Here the new Window is Correct, it is on TOP,

but after that, I want to show other Window on TOP from ConfigRoleModel ,
this is code ConfigRoleModel :

```<code>if (!System.Windows.Application.Current.Windows.OfType<ButtonListView>().Any())
{
    ButtonListViewModel buttonListViewModel = new ButtonListViewModel();
    ButtonListView winconfigRole = new ButtonListView();
    winconfigRole.DataContext = buttonListViewModel;

    winconfigRole.Show();
    winconfigRole.Topmost = true;
    winconfigRole.Focus();
}
</code>```

So ,here I don't have this new Window on TOP!
I don't understand! it is the same code like the first ..

I try also with winconfigRole.ShowDialog();
and `Window.activate()

And the same Problem!

How can I fix it?

Thanks

答:
Set the Owner property the ConfigRole to the MainWindow (or whatever window you open it from) and the Owner property of ButtonListView to the ConfigRole window:

```<code>if (!System.Windows.Application.Current.Windows.OfType<ButtonListView>().Any())
{
    ButtonListViewModel buttonListViewModel = new ButtonListViewModel();
    ButtonListView winconfigRole = new ButtonListView();
    winconfigRole.DataContext = buttonListViewModel;
    winconfigRole.Owner = System.Windows.Application.Current.Windows.OfType<ConfigRole>().FirstOrDefault(); //<--
    winconfigRole.Show();
    winconfigRole.Topmost = true;
    winconfigRole.Focus();
}
</code>```

Title: Keep window on top WPF

Body:
I have problem to keep Window on TOP ? I work with MVVM WPF

I have this code in ConfigRole Model:

if (!System.Windows.Application.Current.Windows.OfType<ConfigRole>().Any())
{
    ConfigRoleModel configRoleModel = new ConfigRoleModel();
    ConfigRole winconfigRole = new ConfigRole();
    winconfigRole.DataContext = configRoleModel;
    winconfigRole.Show();
    winconfigRole.Topmost = true;
    winconfigRole.Focus();
}

Here the new Window is Correct, it is on TOP,

but after that, I want to show other Window on TOP from ConfigRoleModel ,
this is code ConfigRoleModel :

if (!System.Windows.Application.Current.Windows.OfType<ButtonListView>().Any())
{
    ButtonListViewModel buttonListViewModel = new ButtonListViewModel();
    ButtonListView winconfigRole = new ButtonListView();
    winconfigRole.DataContext = buttonListViewModel;

    winconfigRole.Show();
    winconfigRole.Topmost = true;
    winconfigRole.Focus();
}

So ,here I don't have this new Window on TOP!
I don't understand! it is the same code like the first ..

I try also with winconfigRole.ShowDialog();
and `Window.activate()

And the same Problem!

How can I fix it?

Thanks

Body:
Set the Owner property the ConfigRole to the MainWindow (or whatever window you open it from) and the Owner property of ButtonListView to the ConfigRole window:

if (!System.Windows.Application.Current.Windows.OfType<ButtonListView>().Any())
{
    ButtonListViewModel buttonListViewModel = new ButtonListViewModel();
    ButtonListView winconfigRole = new ButtonListView();
    winconfigRole.DataContext = buttonListViewModel;
    winconfigRole.Owner = System.Windows.Application.Current.Windows.OfType<ConfigRole>().FirstOrDefault(); //<--
    winconfigRole.Show();
    winconfigRole.Topmost = true;
    winconfigRole.Focus();
}


问:
Firebase one to one chat with Angular
I would like to make a one to one chat. Each user can contact another user.

Json structure would be :

```<code>{
  "messages" :
       "user1UID_user2UID" : {
             auto generated ID : {
                      "text" : "hello",
                      "timestamp" : 192564646546,
                      "name" : "user1"
             },
             auto generated ID : {
                      "text" : "hi",
                      "timestamp" : 192564646554,
                      "name" : "user2"
             }
         }
}
</code>```

When user1 connects to the app, he can see the list of every conversation of which he is a part.
Let's say he had initiated a conversation with user 2, and user 3 has a conversation with him too.

So we would have the following children :

user1UID_user2UID

user3UID_user1UID

How can I retrieve all the conversations User1 is involved in to ?

```<code>constructor(db: AngularFireDatabase) {
    this.messages= db.list('/messages/' + user1UID + "_" + user2UID); //but I don't know user2UID at this moment
}
</code>```

Can I make a Regex or do I have to store the conversation key (somewhere) every time it concerns him ?

Or I'm completely wrong and I do not look at the problem the right way?

答:
The key naming schema you use for the chat rooms is a variant of my answer here: http://stackoverflow.com/questions/33540479/best-way-to-manage-chat-channels-in-firebase. It's a variant, since you don't seem to order the UIDs lexicographically, which I recommend.

All my proposed algorithm does is generate a reproducible, unique, idempotent key for a chat room between specific users. And while those are very important properties for a data model, they don't magically solve other use-cases.

As often the case in NoSQL data modeling, you'll have to model the data to fit with the use-cases you want. So if your app requires that you show a list of chat rooms for each user, then you should include in your data model a list of chat rooms for each user:

```<code>userChatRooms
  user1UID
    user1UID_user2UID
    user1UID_user3UID
  user2UID
    user1UID_user2UID
    user1UID_user3UID
  user3UID
    user1UID_user3UID
</code>```

Now getting a list of the chat rooms for a user is as easy as reading /userChatRooms/$uid.

Title: Firebase one to one chat with Angular

Body:
I would like to make a one to one chat. Each user can contact another user.

Json structure would be :

{
  "messages" :
       "user1UID_user2UID" : {
             auto generated ID : {
                      "text" : "hello",
                      "timestamp" : 192564646546,
                      "name" : "user1"
             },
             auto generated ID : {
                      "text" : "hi",
                      "timestamp" : 192564646554,
                      "name" : "user2"
             }
         }
}

When user1 connects to the app, he can see the list of every conversation of which he is a part.
Let's say he had initiated a conversation with user 2, and user 3 has a conversation with him too.

So we would have the following children :

user1UID_user2UID

user3UID_user1UID

How can I retrieve all the conversations User1 is involved in to ?

constructor(db: AngularFireDatabase) {
    this.messages= db.list('/messages/' + user1UID + "_" + user2UID); //but I don't know user2UID at this moment
}

Can I make a Regex or do I have to store the conversation key (somewhere) every time it concerns him ?

Or I'm completely wrong and I do not look at the problem the right way?

Body:
The key naming schema you use for the chat rooms is a variant of my answer here: http://stackoverflow.com/questions/33540479/best-way-to-manage-chat-channels-in-firebase. It's a variant, since you don't seem to order the UIDs lexicographically, which I recommend.

All my proposed algorithm does is generate a reproducible, unique, idempotent key for a chat room between specific users. And while those are very important properties for a data model, they don't magically solve other use-cases.

As often the case in NoSQL data modeling, you'll have to model the data to fit with the use-cases you want. So if your app requires that you show a list of chat rooms for each user, then you should include in your data model a list of chat rooms for each user:

userChatRooms
  user1UID
    user1UID_user2UID
    user1UID_user3UID
  user2UID
    user1UID_user2UID
    user1UID_user3UID
  user3UID
    user1UID_user3UID

Now getting a list of the chat rooms for a user is as easy as reading /userChatRooms/$uid.


问:
Unable to get the proper result for the inorder traversal in binary tree, Java Datastructure
I have wrote the code for the preorder and inorder traversal in binary tree data structure, but the outcome of the preorder traversal is correct but i am getting some error in inorder traversal, can anyone show me the fault in my code.
Thanks in advance.</p>

```<code>public class treepractice {
static Node root = null;

static class Node{
    int data;
    Node left, right;
    Node(int d){
        data = d;
        left=right = null;
    }
}

public static void main(String[] agrs){
    treepractice tree = new treepractice();
    tree.root = new Node(1);
    tree.root.left = new Node(2);
    tree.root.right = new Node(3);
    tree.root.left.left = new Node(4);
    tree.root.left.right = new Node(5);
//  root.right.left = new Node(6);

    tree.printInorder(root);
    System.out.println();
    tree.printPreorder(root);
    System.out.println();

}

private static void printPreorder(Node root) {
    if(root == null)
        return;
        System.out.print(root.data + " ");
        printPreorder(root.left);
        printPreorder(root.right);
}

private static void printInorder(Node root) {
    if(root == null)
        return;
        printPreorder(root.left);
        System.out.print(root.data + " ");
        printPreorder(root.right);
}
}
</code>```

答:
In your code printInorder method should call recursively same method  </p>

```<code>  private static void printInorder(Node root) {
            if (root == null)
                return;
            printInorder(root.left);
            System.out.print(root.data + " ");
            printInorder(root.right);
        }
</code>```

Body:
I have wrote the code for the preorder and inorder traversal in binary tree data structure, but the outcome of the preorder traversal is correct but i am getting some error in inorder traversal, can anyone show me the fault in my code.
Thanks in advance.

public class treepractice {
static Node root = null;

static class Node{
    int data;
    Node left, right;
    Node(int d){
        data = d;
        left=right = null;
    }
}

public static void main(String[] agrs){
    treepractice tree = new treepractice();
    tree.root = new Node(1);
    tree.root.left = new Node(2);
    tree.root.right = new Node(3);
    tree.root.left.left = new Node(4);
    tree.root.left.right = new Node(5);
//  root.right.left = new Node(6);

    tree.printInorder(root);
    System.out.println();
    tree.printPreorder(root);
    System.out.println();

}

private static void printPreorder(Node root) {
    if(root == null)
        return;
        System.out.print(root.data + " ");
        printPreorder(root.left);
        printPreorder(root.right);
}

private static void printInorder(Node root) {
    if(root == null)
        return;
        printPreorder(root.left);
        System.out.print(root.data + " ");
        printPreorder(root.right);
}
}

Body:
In your code printInorder method should call recursively same method

  private static void printInorder(Node root) {
            if (root == null)
                return;
            printInorder(root.left);
            System.out.print(root.data + " ");
            printInorder(root.right);
        }


问:
How to capitalize words with brackets in sentence
I am using the following code to capitalize each word in a sentence, but I am unable to capitalize words with brackets attached.

PHP Code:

```<code>  <?php
     $str = "[this is the {command line (interface ";
     $output  = ucwords(strtolower($str));
     echo $output;
</code>```

Output:

[this Is The {command Line (interface

But my expected output should be:

[This Is The {Command Line (Interface

How can I handle words with brackets?
There may be multiple brackets.

For example:

[{this is the ({command line ({(interface

I want to find a general solution/function in PHP.

答:
This is another solution, you can add more delimiters in the for-each loop array if you want to handle more characters.</p>

```<code>function ucname($string) {
    $string =ucwords(strtolower($string));

    foreach (array('-', '\'') as $delimiter) {
      if (strpos($string, $delimiter)!==false) {
        $string =implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
      }
    }
    return $string;
}
?>
<?php
//TEST

$names =array(
  'JEAN-LUC PICARD',
  'MILES O\'BRIEN',
  'WILLIAM RIKER',
  'geordi la forge',
  'bEvErly CRuSHeR'
);
foreach ($names as $name) { print ucname("{$name}\n<br />"); }

//PRINTS:
/*
Jean-Luc Picard
Miles O'Brien
William Riker
Geordi La Forge
Beverly Crusher
*/
</code>```

Body:
I am using the following code to capitalize each word in a sentence, but I am unable to capitalize words with brackets attached.

PHP Code:

  <?php
     $str = "[this is the {command line (interface ";
     $output  = ucwords(strtolower($str));
     echo $output;

Output:

[this Is The {command Line (interface

But my expected output should be:

[This Is The {Command Line (Interface

How can I handle words with brackets?
There may be multiple brackets.

For example:

[{this is the ({command line ({(interface

I want to find a general solution/function in PHP.

Body:
This is another solution, you can add more delimiters in the for-each loop array if you want to handle more characters.

function ucname($string) {
    $string =ucwords(strtolower($string));

    foreach (array('-', '\'') as $delimiter) {
      if (strpos($string, $delimiter)!==false) {
        $string =implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
      }
    }
    return $string;
}
?>
<?php
//TEST

$names =array(
  'JEAN-LUC PICARD',
  'MILES O\'BRIEN',
  'WILLIAM RIKER',
  'geordi la forge',
  'bEvErly CRuSHeR'
);
foreach ($names as $name) { print ucname("{$name}\n<br />"); }

//PRINTS:
/*
Jean-Luc Picard
Miles O'Brien
William Riker
Geordi La Forge
Beverly Crusher
*/


问:
Firebase Admin SDK - How lacking is the Java release compared to the Node.JS?
I am looking to create a microservice in the backend of my android and iOS app that sends push notification requests to firebase (using maven to organize project). I would like to use the Java admin SDK for this as I am looking to make this call in the backend in this app server rather than right from the android or iOS side. I have been exploring this API and the Java version is missing two APIs that the Node.JS one currently has. I read up on what the two APIs do but I was wondering if anyone who has been working with the admin SDK know how the two Java APIs missing will handicap me in terms of features?</p>

答:
As of today, you won't find the following 2 APIs in the Java Admin SDK:

Firebase Cloud Messaging (FCM)

User management

User management API for Java is currently being developed. FCM will be added in the near future too.


问:
Google maps API Basic Example
I've been unable to get the basic Google maps example working on my site.  I have the following div on my page:

```<code><div id="map_canvas" style="width:100%; height:100%"></div>
</code>```

And the following in the head of my document:

```<code><script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
    function initialize() {
        var latlng = new google.maps.LatLng(-34.397, 150.644);
        var myOptions = {
            zoom: 8,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    }
    jQuery(document).ready(initialize);
</script>
</code>```

It appears that the elements are getting loaded into my DOM, but there is no visible map on the page.

答:
I tested your code and iw works fine if i use  as da_didi suggested.
Do you have an import directive for jquery.js?

ContentLicense: CC BY-SA 2.5

Title: Google maps API Basic Example

Body:
I've been unable to get the basic Google maps example working on my site.  I have the following div on my page:

And the following in the head of my document:

It appears that the elements are getting loaded into my DOM, but there is no visible map on the page.

Body:
I tested your code and iw works fine if i use <body onload="initialize()"> as da_didi suggested.
Do you have an import directive for jquery.js?


问:
String aggregate using a variable
Is is okay to use a variable to concatenate a value from several rows ( as an implicit aggregate function )? It seems to work fine on my machine, but I haven't seen it recommended.</p>

```<code>declare @v_str varchar(4000) = ''
select top 5 @v_str = @v_str + ',' + city_name from city_table order by city_name
print @v_str
</code>```

答:
From nvarchar concatenation / index / nvarchar(max) inexplicable behavior
"The correct behavior for an aggregate concatenation query is undefined."</p>

Title: String aggregate using a variable

Body:
Is is okay to use a variable to concatenate a value from several rows ( as an implicit aggregate function )? It seems to work fine on my machine, but I haven't seen it recommended.

declare @v_str varchar(4000) = ''
select top 5 @v_str = @v_str + ',' + city_name from city_table order by city_name
print @v_str


问:
How to find all documents with all specified array values in it in mongoDB?
This is my collection

```<code>{
    "_id" : ...,
    "name" : "sport",
}
{
    "_id" : ...,
    "name" : "art",
}
{
    "_id" : ...,
    "name" : "cars",
}
</code>```

This is an array I have got ["cars","sport"]
I just want to make sure that I have got cars and sport in my collection, if not(or just one doesn't exist) I would like to receive nothing.
I'm looking for a array-friendly like query like $in but and mode.

答:
following query should help you achieve this

```<code>//change test with your collection name
db.getCollection('test').aggregate(
    {
        $group: {
            _id: "collectionOfNames",
            "names": {$addToSet: "$name"}
        }
    },
    {
        $match: {"names": {$all: ["cars", "sport"]}}

    }
)
</code>```

We use $group to create an array "names" of the property name across all documents.
Then using $match and $all we check to make sure that the array "names" contains all of the elements from our query array.

Is this what you are looking for?

Body:
This is my collection

{
    "_id" : ...,
    "name" : "sport",
}
{
    "_id" : ...,
    "name" : "art",
}
{
    "_id" : ...,
    "name" : "cars",
}

This is an array I have got ["cars","sport"]
I just want to make sure that I have got cars and sport in my collection, if not(or just one doesn't exist) I would like to receive nothing.
I'm looking for a array-friendly like query like $in but and mode.

Body:
following query should help you achieve this

//change test with your collection name
db.getCollection('test').aggregate(
    {
        $group: {
            _id: "collectionOfNames",
            "names": {$addToSet: "$name"}
        }
    },
    {
        $match: {"names": {$all: ["cars", "sport"]}}

    }
)

We use $group to create an array "names" of the property name across all documents.
Then using $match and $all we check to make sure that the array "names" contains all of the elements from our query array.

Is this what you are looking for?


问:
how can I convert string into HTML. I want the actual href to show/display instead of the text
how can I convert string into HTML. I want the actual href to show/display instead of the text. </p>

```<code>    var zzz = "test";
    var value0 = 14251876;
    var value1 = "AAAA";

    var EmailSubject = 'Transcription Assigned   Due (' + zzz + ')';
    var EmailBody = 'Dear ' + zzz + ',\n\n' + 'A dictation for the following Service has been assigned to you;\n\n' + 'Service Name: ' + zzz + '\n\n' + 'Thank you,\n' + 'Assessments\n' + '(416) 111 - 2222';
    EmailBody = EmailBody + $($.parseHTML('<div><a href="/Apps/app_editevent.jsp?eventid=' + value1 + '" target="_blank">' + value0 + '</a></div>'));
    send_msg(false,'',20,0,'mailer@test.ca',1081636,'',EmailSubject,EmailBody);
</code>```

答: Just get rid of the $($.parseHTML()) bits and just add the string itself.

Body:
how can I convert string into HTML. I want the actual href to show/display instead of the text.

    var zzz = "test";
    var value0 = 14251876;
    var value1 = "AAAA";

    var EmailSubject = 'Transcription Assigned   Due (' + zzz + ')';
    var EmailBody = 'Dear ' + zzz + ',\n\n' + 'A dictation for the following Service has been assigned to you;\n\n' + 'Service Name: ' + zzz + '\n\n' + 'Thank you,\n' + 'Assessments\n' + '(416) 111 - 2222';
    EmailBody = EmailBody + $($.parseHTML('
' + value0 + '
'));
    send_msg(false,'',20,0,'mailer@test.ca',1081636,'',EmailSubject,EmailBody);


问:
Can MLLib classifiers be trained and used without a Spark installation?
I want to use some of the classifiers provided by MLLib (random forests, etc) but I want to use them without connecting to a Spark cluster.

If I need to somehow run some Spark stuff in-process so that I have a Spark context to use, that's fine. But I haven't been able to find any information or an example for such a use case.

So my two questions are:

Is there a way to use the MLLib classifiers without a Spark context at all?

Otherwise, can I use them by starting a Spark context in-process, without needing any kind of actual Spark installation?

答:
org.apache.spark.mllib models:

Cannot be trained without Spark cluster.

Usually can be used for predictions without cluster, with exception to distributed models like ALS.

org.apache.spark.ml models:

Require Spark cluster for training.

Require Spark cluster for predictions although it might change in the future (https://issues.apache.org/jira/browse/SPARK-10413)

There is a number of third party tools which are designed to export Spark ml models to the form which can be used in Spark agnostic environment (jpmml-spark and modeldb to enumerate a few, without special preference).

Spark mllib models have limited PMML support as well.

Commercial vendors usually provide their own tools for productionizing Spark models.

You can of course use local "cluster", but it is probably still a bit to heavy for most of possible applications. Starting a full context take at least a few seconds, and has significant memory footprint.

Also:

Best Practice to launch Spark Applications via Web Application?

How to serve a Spark MLlib model?


问:
Linux One Liner to return eth name, ip, mac and subnet
I have been trying to combine two queries I have into one. I am trying to get an output of IP info which will get compared to another query against the host file and eventually dumped into a database. My commands have to be simple one liners due to how they are deployed.  I can get what I need with these two, but is there a way to combined them.  The ip show puts out a multiline output and not sure how to combined the lines.

```<code>ip -o addr show | awk '/inet/ {print $9, $4}' | grep -v '127.0.0.1'
ip -o addr show | awk '/link/ {print $2, $13}' | grep -v lo
</code>```

Top gives most of the info and bottom gets the mac. This gives both but it is multi line so not sure how to awk out the values I need.  Any good thoughts or tricks?  Still new on the linux/bash.

```<code> ip -o addr show | grep -i 'ether\|inet'
</code>```

Example of an ip -o addr show command

```<code>1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN \            link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
1: lo    inet 127.0.0.1/8 scope host lo
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
2: eth0    inet x.x.x.x/24 brd x.x.x.x scope global eth0
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
3: eth1    inet x.x.x.x/24 brd x.x.x.x scope global eth1
4: eth2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
4: eth2    inet x.x.x.x/27 brd x.x.x.x scope global eth2
5: eth3: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
6: eth4: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
6: eth4    inet x.x.x.x/24 brd x.x.x.x scope global eth4
7: eth5: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
7: eth5    inet x.x.x.x/24 brd x.x.x.x scope global eth5
8: eth6: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
8: eth6    inet x.x.x.x/28 brd x.x.x.x scope global eth6
9: eth7: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
</code>```

答:
This is not 100% as accurate as the original, but it works with your input:

```<code>ip -o addr show | awk '/inet/ && !/127.0.0.1/ {print $9, $4} /link/ && ! /lo/ {print $2, $13}'
</code>```

If you want the output on one line,
then you can wrap the above command in echo $(...) like this:

```<code>echo $(ip -o addr show | awk '/inet/ && !/127.0.0.1/ {print $9, $4} /link/ && ! /lo/ {print $2, $13}')
</code>```

Body:
I have been trying to combine two queries I have into one. I am trying to get an output of IP info which will get compared to another query against the host file and eventually dumped into a database. My commands have to be simple one liners due to how they are deployed.  I can get what I need with these two, but is there a way to combined them.  The ip show puts out a multiline output and not sure how to combined the lines.

ip -o addr show | awk '/inet/ {print $9, $4}' | grep -v '127.0.0.1'
ip -o addr show | awk '/link/ {print $2, $13}' | grep -v lo

Top gives most of the info and bottom gets the mac. This gives both but it is multi line so not sure how to awk out the values I need.  Any good thoughts or tricks?  Still new on the linux/bash.

 ip -o addr show | grep -i 'ether\|inet'

Example of an ip -o addr show command

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN \            link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
1: lo    inet 127.0.0.1/8 scope host lo
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
2: eth0    inet x.x.x.x/24 brd x.x.x.x scope global eth0
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
3: eth1    inet x.x.x.x/24 brd x.x.x.x scope global eth1
4: eth2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
4: eth2    inet x.x.x.x/27 brd x.x.x.x scope global eth2
5: eth3: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
6: eth4: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
6: eth4    inet x.x.x.x/24 brd x.x.x.x scope global eth4
7: eth5: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
7: eth5    inet x.x.x.x/24 brd x.x.x.x scope global eth5
8: eth6: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
8: eth6    inet x.x.x.x/28 brd x.x.x.x scope global eth6
9: eth7: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN qlen 1000\    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff

Body:
This is not 100% as accurate as the original, but it works with your input:

ip -o addr show | awk '/inet/ && !/127.0.0.1/ {print $9, $4} /link/ && ! /lo/ {print $2, $13}'

If you want the output on one line,
then you can wrap the above command in echo $(...) like this:

echo $(ip -o addr show | awk '/inet/ && !/127.0.0.1/ {print $9, $4} /link/ && ! /lo/ {print $2, $13}')


问:
Ensure that users can only access their data in a REST API request
I'm working REST API right now with Jersey, Spring. Which shall be accessed with an Android/iOS later.
If I have for example user settings like this @Path("/user/{userID}/settings") in a Jersey Resource. How can i ensure that every user can access his/her settings only? I have read a lot about spring-security-oauth2. But as far as i understand you can only verify that the user is really the user but not make a difference if he/she can access other users settings?!

答:
What you need is called authorization.

Authorization can distingush level of accesses of each users.
It's major topic actually. You can use roles, permissions, ACL for securing the service.

The simplest way for solving your task is to use path /user/settings and find the authentication yourseft, like:

```<code>public Settings find() {
    UserDetails customUserDetails = (CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    return setingsService.findByUser(customUserDetails.getUsername());
}
</code>```

Create your CustomUserDetails:

```<code>public class CustomUserDetails implements UserDetails {

    private User user;

    private Collection<? extends GrantedAuthority> authorities;

    public CustomUserDetails(User user) {
        this.user = user;
    }

    public User getUser() {
        return user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();

        for (Authority authority : user.getAuthorities()) {
            authorities.add(new SimpleGrantedAuthority(authority.getName()));
        }

        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    // implement other methods

}
</code>```

And CustomUserDetailsService:

```<code>@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findByUsername(username);
            // check if exist
        }

        return new CustomUserDetails(user);
    }
}
</code>```

Body:
What you need is called authorization.

Authorization can distingush level of accesses of each users.
It's major topic actually. You can use roles, permissions, ACL for securing the service.

The simplest way for solving your task is to use path /user/settings and find the authentication yourseft, like:

public Settings find() {
    UserDetails customUserDetails = (CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    return setingsService.findByUser(customUserDetails.getUsername());
}

Create your CustomUserDetails:

public class CustomUserDetails implements UserDetails {

    private User user;

    private Collection<? extends GrantedAuthority> authorities;

    public CustomUserDetails(User user) {
        this.user = user;
    }

    public User getUser() {
        return user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();

        for (Authority authority : user.getAuthorities()) {
            authorities.add(new SimpleGrantedAuthority(authority.getName()));
        }

        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    // implement other methods

}

And CustomUserDetailsService:

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findByUsername(username);
            // check if exist
        }

        return new CustomUserDetails(user);
    }
}


问:
MySQL Trigger: UPDATE parent row AFTER DELETE in child row
I need to update the value of the parent table, when a child row is deleted.

Parent table: (answers)

id_answer

answer

votes (contains total of votes)

Children table: (answers_votes)

id_vote

id_answer

id_user

date_insert

ip

Each time a child row is deleted, the value of votes in the parent table must be decreased by 1.

This is my current sentence to create the trigger, but something is wrong with the UPDATE line, perhaps the votes-1? Any help will be appreciated. Thanks!

```<code>CREATE TRIGGER update_votes BEFORE DELETE on answers_votes
FOR EACH ROW
BEGIN
UPDATE answers SET answers.votes = (answers.votes-1) WHERE answers.id_answer = OLD.id_answer;
END
</code>```

Any ideas? Thanks!

答:
So, I suspect ; is the problem here. I've added $$ as the DELIMITER so that mysql client will not misinterpret ;.

Your modified trigger will be :

```<code>DELIMITER $$
CREATE TRIGGER update_votes
BEFORE DELETE ON answers_votes
FOR EACH ROW
BEGIN
  UPDATE answers SET answers.votes = (answers.votes -1 ) WHERE answers.id_answer = OLD.id_answer;
END$$
DELIMITER ;
</code>```

Note, it is DELIMITER ; not DELIMITER;

Hope this helps!

Body:
I need to update the value of the parent table, when a child row is deleted.

Parent table: (answers)

id_answer

answer

votes (contains total of votes)

Children table: (answers_votes)

id_vote

id_answer

id_user

date_insert

ip

Each time a child row is deleted, the value of votes in the parent table must be decreased by 1.

This is my current sentence to create the trigger, but something is wrong with the UPDATE line, perhaps the votes-1? Any help will be appreciated. Thanks!

CREATE TRIGGER update_votes BEFORE DELETE on answers_votes
FOR EACH ROW
BEGIN
UPDATE answers SET answers.votes = (answers.votes-1) WHERE answers.id_answer = OLD.id_answer;
END

Any ideas? Thanks!

Body:
So, I suspect ; is the problem here. I've added $$ as the DELIMITER so that mysql client will not misinterpret ;.

Your modified trigger will be :

DELIMITER $$
CREATE TRIGGER update_votes
BEFORE DELETE ON answers_votes
FOR EACH ROW
BEGIN
  UPDATE answers SET answers.votes = (answers.votes -1 ) WHERE answers.id_answer = OLD.id_answer;
END$$
DELIMITER ;

Note, it is DELIMITER ; not DELIMITER;

Hope this helps!


问:
Application not running on Android device
My application is running properly on emulator but not on device. Earlier I have run the same app on device many a times. I have turned USB- Debugging on my device, also set debuggable to true in manifest.

When I try to use command adb devices, it's showing me an empty list of devices.

Has anybody encountered same problem anytime?

Thanx in advance.

答: While connecting your device to desktop/laptop don't connect the device as a mass storage.</p>


问:
Using HtmlHelper in a Controller
Is it possible to use HtmlHelper in a controller, for-example to get the TextBox(...) method? not that I can't write the html that it generates myself, but I just want to understand how this works so I can create the best solution.</p>

答:
using System.Web.Mvc;

using System.Web.Mvc.Html;

```<code> HtmlHelper helper = new HtmlHelper(new ViewContext(ControllerContext, new            WebFormView(ControllerContext, "Index"), new ViewDataDictionary(), new TempDataDictionary(), new System.IO.StringWriter()), new ViewPage());
</code>```

OwnerDisplayName: Gil

Title: Using HtmlHelper in a Controller

Body:
using System.Web.Mvc;

using System.Web.Mvc.Html;

 HtmlHelper helper = new HtmlHelper(new ViewContext(ControllerContext, new            WebFormView(ControllerContext, "Index"), new ViewDataDictionary(), new TempDataDictionary(), new System.IO.StringWriter()), new ViewPage());


问:
How do arguments get passed when using .bind?
I am trying to bind separate functions to the left and right click of a button.
Unfortunately somehow python gives me this error when pressing the button:

```<code>Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1542, in __call__
    return self.func(*args)
TypeError: () takes no arguments (1 given)
</code>```

I think it has something to do with Tkinter also passing event information when calling the function.

This is the Code (I shortened it a bit and removed unnessecary things):

```<code>class Minefield():
    def __init__(self, X,Y,Parent,Array):
        self.Button = Tk.Button(Parent)
        self.Button.bind('<Button-1>',lambda: Array.Trigger(self.state,self.cordX,self.cordY) )  # NOTE: Array Function Trigger
        self.Button.bind('<Button-3>',lambda: self.setState(self.state,1))
class Array():
    def __init__(self):
        self.Array=[]
    def Trigger(self,X,Y):
        print "Trigger at", X, Y
        do_nothing()
</code>```

now my Question:

What parameters effectively get passed and how do I handle them in a function which has no intent of using other things than those defined in the parameters?

答:
When you bind a function to an event, tkinter will always pass one argument to the function. This argument is an object that contains information about the event, such as the widget that received the event, the key or mouse that caused the event, etc.

If you are calling a function that doesn't need the argument, just ignore it. If you need to use the function also outside the context of an event, give it a default value of None.

If you are passing additional arguments to your callback, you need to account for the event argument in your lambda. You don't have to use it, but your lambda needs to accept it. For example:

```<code>self.Button.bind('<Button-3>', lambda event: self.setState(self.state,1))
</code>```

Body:
I am trying to bind separate functions to the left and right click of a button.
Unfortunately somehow python gives me this error when pressing the button:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1542, in __call__
    return self.func(*args)
TypeError: () takes no arguments (1 given)

I think it has something to do with Tkinter also passing event information when calling the function.

This is the Code (I shortened it a bit and removed unnessecary things):

class Minefield():
    def __init__(self, X,Y,Parent,Array):
        self.Button = Tk.Button(Parent)
        self.Button.bind('<Button-1>',lambda: Array.Trigger(self.state,self.cordX,self.cordY) )  # NOTE: Array Function Trigger
        self.Button.bind('<Button-3>',lambda: self.setState(self.state,1))
class Array():
    def __init__(self):
        self.Array=[]
    def Trigger(self,X,Y):
        print "Trigger at", X, Y
        do_nothing()

now my Question:

What parameters effectively get passed and how do I handle them in a function which has no intent of using other things than those defined in the parameters?

Body:
When you bind a function to an event, tkinter will always pass one argument to the function. This argument is an object that contains information about the event, such as the widget that received the event, the key or mouse that caused the event, etc.

If you are calling a function that doesn't need the argument, just ignore it. If you need to use the function also outside the context of an event, give it a default value of None.

If you are passing additional arguments to your callback, you need to account for the event argument in your lambda. You don't have to use it, but your lambda needs to accept it. For example:

self.Button.bind('<Button-3>', lambda event: self.setState(self.state,1))


问:
"puts" method in rails 3
I've been doing some development with rails 3 and I was wondering why calling the "puts" method doesn't output to standard out.

How do I get this back?

答:
Instead of puts, use logger.info:

```<code>logger.info @collection.inspect
</code>```

Title: "puts" method in rails 3

Body:
Instead of puts, use logger.info:

logger.info @collection.inspect


问:
Deploy runnable spring boot jar to Heroku
I'm trying to get an executable Spring Boot jar to deploy on Heroku.

I have told Heroku to deploy from a github repository that contains only these files:

```<code>.
├── Procfile
└── current/
    └── <my application>.jar
</code>```

My Procfile looks like this:

```<code>web: java $JAVA_OPTS -Dserver.port=$PORT -jar current/*.jar
</code>```

This is the error I get in the Heroku build log when I try to deploy:

```<code>-----> Failed to detect app matching no buildpack
       More info: https://devcenter.heroku.com/articles/buildpacks#detection-
failure
 !     Push failed
</code>```

If I look at the heroku/java build pack project in github, I can see that there's a script called detect that checks for the existence of a pom.xml file:

https://github.com/heroku/heroku-buildpack-java/blob/master/bin/detect

I believe my project isn't being deployed because I don't have a pom in the root directory.

Is it possible to just deploy a project that contains only an executable jar and a Procfile?

答:
You'll want to use the JVM buildpack instead, which you can do by setting the heroku/jvm buildpack on the app instead of the heroku/java buildpack.

For example, you can run:

```<code>$ heroku buildpacks:set heroku/jvm
</code>```

Or set it in the Heroku Dashboard's Settings tab for the app

Body:
I'm trying to get an executable Spring Boot jar to deploy on Heroku.

I have told Heroku to deploy from a github repository that contains only these files:

.
├── Procfile
└── current/
    └── <my application>.jar

My Procfile looks like this:

web: java $JAVA_OPTS -Dserver.port=$PORT -jar current/*.jar

This is the error I get in the Heroku build log when I try to deploy:

-----> Failed to detect app matching no buildpack
       More info: https://devcenter.heroku.com/articles/buildpacks#detection-
failure
 !     Push failed

If I look at the heroku/java build pack project in github, I can see that there's a script called detect that checks for the existence of a pom.xml file:

https://github.com/heroku/heroku-buildpack-java/blob/master/bin/detect

I believe my project isn't being deployed because I don't have a pom in the root directory.

Is it possible to just deploy a project that contains only an executable jar and a Procfile?

Body:
You'll want to use the JVM buildpack instead, which you can do by setting the heroku/jvm buildpack on the app instead of the heroku/java buildpack.

For example, you can run:

$ heroku buildpacks:set heroku/jvm

Or set it in the Heroku Dashboard's Settings tab for the app


问:
Problems bulk insert elasticsearch curl powershell
I'm new to Elasticsearch and I'm following the tutorial loading sample data: https://www.elastic.co/guide/en/kibana/current/tutorial-load-dataset.html
When I try to bulk insert the data in powershell
'curl -H 'Content-Type: application/x-ndjson' -XPOST 'localhost:9200/shakespeare/_bulk?pretty' --data-binary "@shakespeare.json"'

I get the following error

PS C:\Development\elasticsearch-5.4.1\importdata> curl -H 'Content-Type: application/x-ndjson' -XPOST 'localhost:9200/shakespeare/_bulk?pretty' --data-binary "@shakespeare.json"
  Invoke-WebRequest : Cannot bind parameter 'Headers'. Cannot convert the "Content-Type: application/x-ndjson" value of type "System.St
  ring" to type "System.Collections.IDictionary".
  At line:1 char:9
  + curl -H 'Content-Type: application/x-ndjson' -XPOST 'localhost:9200/s ...
  +         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException
      + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

I've tried several things, read the bulk api documentation but with no result

Here're some examples of the content of the json file:

{"index":{"_index":"shakespeare","_type":"act","_id":0}}
{"line_id":1,"play_name":"Henry IV","speech_number":"","line_number":"","speaker":"","text_entry":"ACT I"}
{"index":{"_index":"shakespeare","_type":"scene","_id":1}}
{"line_id":2,"play_name":"Henry IV","speech_number":"","line_number":"","speaker":"","text_entry":"SCENE I. London. The palace."}
{"index":{"_index":"shakespeare","_type":"line","_id":2}}
{"line_id":3,"play_name":"Henry IV","speech_number":"","line_number":"","speaker":"","text_entry":"Enter KING HENRY, LORD JOHN OF LANCASTER, the EARL of WESTMORELAND, SIR WALTER BLUNT, and others"}

答:
I found the solution. Because I used curl on windows and with powershell, I had to translate

```<code>curl -H 'Content-Type: application/x-ndjson' -XPOST 'localhost:9200/shakespeare/_bulk?pretty' --data-binary @shakespeare.json
</code>```

to

```<code>PS C:\Development\elasticsearch-5.4.1\importdata> $postParams = @"
>> {"index":{"_index":"shakespeare","_type":"act","_id":0}}
>> {"line_id":1,"play_name":"Henry IV","speech_number":"","line_number":"","speaker":"","text_entry":"ACT I"}
>>
>> "@

PS C:\Development\elasticsearch-5.4.1\importdata> curl -H @{"Content-Type" = "application/x-ndjson"} -Method POST 'http://localhost:92
00/shakespeare/_bulk?pretty' -body $postParams
</code>```

When I use the demo file, the bulk insert didn't succeeded but that's another problem

PS C:\Development\elasticsearch-5.4.1\importdata> $postParams = Get-Content "shakespeare.json"

Body:
I found the solution. Because I used curl on windows and with powershell, I had to translate

curl -H 'Content-Type: application/x-ndjson' -XPOST 'localhost:9200/shakespeare/_bulk?pretty' --data-binary @shakespeare.json

to

PS C:\Development\elasticsearch-5.4.1\importdata> $postParams = @"
>> {"index":{"_index":"shakespeare","_type":"act","_id":0}}
>> {"line_id":1,"play_name":"Henry IV","speech_number":"","line_number":"","speaker":"","text_entry":"ACT I"}
>>
>> "@

PS C:\Development\elasticsearch-5.4.1\importdata> curl -H @{"Content-Type" = "application/x-ndjson"} -Method POST 'http://localhost:92
00/shakespeare/_bulk?pretty' -body $postParams

When I use the demo file, the bulk insert didn't succeeded but that's another problem

PS C:\Development\elasticsearch-5.4.1\importdata> $postParams = Get-Content "shakespeare.json"


问:
How do I pass Redux props to a separate component in a different Route with React Router v4?
I'm creating a real time chat app with react, react router v4 and redux. The problem is that, as you may know, react router v4 changes a lot of stuff and nesting routes is not working for me.

So I have this code with a nested route that is not working:

```<code><Route path='/' component={App}>
    <Route path="/user" component={AddUser}/>
</Route>
</code>```

It's giving me this error Warning: You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored.

Where component={App}, in the first <Route path='/' is a redux connect:

```<code>const App = connect(mapStateToProps, mapDispatchToProps)(Header)
</code>```

So my component App has all the the props I need. All works fine except by the fact that I need to pass those props from App to the nested route component AddUser.

How do I pass the redux props to a separate component in a different Route?

答:
I found a solution reading this blog post: https://medium.com/@5XvYrLT7/react-server-side-rendering-with-react-router-3-x-74cf87919b3

With react-router v4 you don’t do this any more, don’t nest :

```<code><Route component={App}>
    <Route component={Index} />
    <Route component={About} />
</Route>
</code>```

You do it like this now. App embeds your routes as-is:

```<code><App>
    <Switch>
        <Route exact path="/" component={Index} />
        <Route path="/about" component={About} />
    </Switch>
</App>
</code>```

Body:
I'm creating a real time chat app with react, react router v4 and redux. The problem is that, as you may know, react router v4 changes a lot of stuff and nesting routes is not working for me.

So I have this code with a nested route that is not working:

<Route path='/' component={App}>
    <Route path="/user" component={AddUser}/>
</Route>

It's giving me this error Warning: You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored.

Where component={App}, in the first <Route path='/' is a redux connect:

const App = connect(mapStateToProps, mapDispatchToProps)(Header)

So my component App has all the the props I need. All works fine except by the fact that I need to pass those props from App to the nested route component AddUser.

How do I pass the redux props to a separate component in a different Route?

Body:
I found a solution reading this blog post: https://medium.com/@5XvYrLT7/react-server-side-rendering-with-react-router-3-x-74cf87919b3

With react-router v4 you don’t do this any more, don’t nest :

<Route component={App}>
    <Route component={Index} />
    <Route component={About} />
</Route>

You do it like this now. App embeds your routes as-is:

<App>
    <Switch>
        <Route exact path="/" component={Index} />
        <Route path="/about" component={About} />
    </Switch>
</App>


问:
Dispatching C++ generated files into srcs and hdrs
In the Bazel official documentation there is an example explaining how to create a Java library built from regular java files and files generated by a :gen_java_srcs rule. I rewrite this code here for ease of reading:

```<code>java_library(
    name = "mylib",
    srcs = glob(["*.java"]) + [":gen_java_srcs"],
    deps = "...",
)

genrule(
    name = "gen_java_srcs",
    outs = [
        "Foo.java",
        "Bar.java",
    ],
    ...
)
</code>```

Now in a C++ perspective, I am in a scenario where the genrule generates two kind of files: .hpp and .cpp:

```<code>genrule(
    name = "gen_cpp_srcs",
    outs = [
        "myFile_1.hpp","myFile_2.hpp",...,"myFile_N.hpp",
        "myFile.cpp","myFile_2.cpp",...,"myFile_N.cpp",
    ],
    ...
)
</code>```

where N is some tens.

My problem/question is: how to write the cc_library rule, with an automatic dispatching of the hpp and cpp files into hdrs and srcs field?

I want something like:

```<code>cc_library(
    name = "mylib",
    srcs = glob(["*.cpp"]) + (howto: .cpp files of [":gen_cpp_srcs"]),
    hdrs = glob(["*.hpp"]) + (howto: .hpp files of [":gen_cpp_srcs"]),
    ...
)
</code>```

Some magic like:

```<code>output_filter(":gen_cpp_srcs","*.cpp")
</code>```

would be perfect, but I do not know enough of Bazel to make it real.

答:
Looks like you know the total number of files that should be generated. Can you put those in their own variables and then reuse them in both targets. Something like this in your BUILD file:</p>

```<code>output_cpp_files = [
   "myFile_1.cpp",
   "myFile_2.cpp",
   "myFile_3.cpp"
]

output_hpp_files = [
   "myFile_1.hpp",
   "myFile_2.hpp",
   "myFile_3.hpp"
]

genrule(
    name = "gen_cpp_srcs",
    outs = output_cpp_files + output_hpp_files,
    cmd = """
        touch $(OUTS)
    """
)

cc_library(
    name = "mylib",
    srcs = output_cpp_files,
    hdrs = output_hpp_files
)
</code>```

Body:
In the Bazel official documentation there is an example explaining how to create a Java library built from regular java files and files generated by a :gen_java_srcs rule. I rewrite this code here for ease of reading:

java_library(
    name = "mylib",
    srcs = glob(["*.java"]) + [":gen_java_srcs"],
    deps = "...",
)

genrule(
    name = "gen_java_srcs",
    outs = [
        "Foo.java",
        "Bar.java",
    ],
    ...
)

Now in a C++ perspective, I am in a scenario where the genrule generates two kind of files: .hpp and .cpp:

genrule(
    name = "gen_cpp_srcs",
    outs = [
        "myFile_1.hpp","myFile_2.hpp",...,"myFile_N.hpp",
        "myFile.cpp","myFile_2.cpp",...,"myFile_N.cpp",
    ],
    ...
)

where N is some tens.

My problem/question is: how to write the cc_library rule, with an automatic dispatching of the hpp and cpp files into hdrs and srcs field?

I want something like:

cc_library(
    name = "mylib",
    srcs = glob(["*.cpp"]) + (howto: .cpp files of [":gen_cpp_srcs"]),
    hdrs = glob(["*.hpp"]) + (howto: .hpp files of [":gen_cpp_srcs"]),
    ...
)

Some magic like:

output_filter(":gen_cpp_srcs","*.cpp")

would be perfect, but I do not know enough of Bazel to make it real.

Body:
Looks like you know the total number of files that should be generated. Can you put those in their own variables and then reuse them in both targets. Something like this in your BUILD file:

output_cpp_files = [
   "myFile_1.cpp",
   "myFile_2.cpp",
   "myFile_3.cpp"
]

output_hpp_files = [
   "myFile_1.hpp",
   "myFile_2.hpp",
   "myFile_3.hpp"
]

genrule(
    name = "gen_cpp_srcs",
    outs = output_cpp_files + output_hpp_files,
    cmd = """
        touch $(OUTS)
    """
)

cc_library(
    name = "mylib",
    srcs = output_cpp_files,
    hdrs = output_hpp_files
)


问:
How do I include a self-reference to a server control in an external method call?
I have an Asp.Net TextBox control whose enabled property I need to evaluate using a separate (from the code-behind of the containing page) class. The way I want to do this is:

```<code><asp:TextBox ID="myTB" runat="server" Enabled="<% ToggleControl(this, "someBusinessValue") %>" ... />
</code>```

The reason I need to pass a reference to the calling control is to see if there are other properties I may need to consider before disabling it. The 'this' keyword, however, refers to the page as a whole. And since my TextBox can be within a FormView, or GridView, I can't easily just get the control by examining 'page.myTB'. I don't want to have to start ploughing through GridViews on the receiving class file just to retrieve a reference to the TextBox.

Does anyone know how to refer to the control inline in this way?

EDIT 1: This will need to be done to several different types of server control, such as ListBox, CheckBox, RadioButtonList, etc.

EDIT 2: The best I've come up with so far is:

```<code><asp:TextBox ID="myTB" runat="server" Enabled="<% ToggleControl(myGridView.FindControl("myTB") as WebControl, "someBusinessValue") %>"
</code>```

which isn't too elegant, but it does give me that auto-reference that I need.

答:
You can derive any control, add a new property like "AuthExpression", and use a data-binding expression which you can eval with DataBinder.Eval method.

Or you can create an ASP.NET AJAX extender control which does this job for any control you like: any control extended by the extender evals a data-binding expression which determines that the control should be enabled or disabled.

I hope this is answering your question!

Body:
I have an Asp.Net TextBox control whose enabled property I need to evaluate using a separate (from the code-behind of the containing page) class. The way I want to do this is:

<asp:TextBox ID="myTB" runat="server" Enabled="<% ToggleControl(this, "someBusinessValue") %>" ... />

The reason I need to pass a reference to the calling control is to see if there are other properties I may need to consider before disabling it. The 'this' keyword, however, refers to the page as a whole. And since my TextBox can be within a FormView, or GridView, I can't easily just get the control by examining 'page.myTB'. I don't want to have to start ploughing through GridViews on the receiving class file just to retrieve a reference to the TextBox.

Does anyone know how to refer to the control inline in this way?

EDIT 1: This will need to be done to several different types of server control, such as ListBox, CheckBox, RadioButtonList, etc.

EDIT 2: The best I've come up with so far is:

<asp:TextBox ID="myTB" runat="server" Enabled="<% ToggleControl(myGridView.FindControl("myTB") as WebControl, "someBusinessValue") %>"

which isn't too elegant, but it does give me that auto-reference that I need.


问:
Cast from List to List when B extends A
I have two clases:

```<code>public class A {
   //attibutes and methods
}

public class B extends A {
   //atributes and methods
}
</code>```

Now I have a service that returns a List with elements of type A. Lets call it generateAElements();

I want to call that method, filter the List obtained to only keep the elements of type B, which also are of type A.

```<code>List<A> listA = generateAElements();
List<A> listAA = listA.filter( p -> p instanceof B).collect(Collectors.toList());
List<B> listB = new ArrayList<>();
// need to create a new list, iterate overListA and add elements of type B?
for (A itemA : listA) {
    listB.add((B) itemA);
}
</code>```

Is there an efficient way to do this?

Important: The list may contain a large number of elements.

答:
Stream free version. You just need to do a compatibility check before casting and you are good to do whatever you want.

```<code>List<A> listA = generateAElements();
List<B> listB = new LinkedList<>();
for (A item : listA) {
    // Skip non compatable items
    if(item instanceof B)
        listB.add((B) item);
}
</code>```

The key difference from the OP's code is the line if(item instanceof B), that does the filter/error-checking the OP needed, but didn't do. (This is technically the exact same thing the stream version is doing, but slightly more verbose and much less overhead)

Title: Cast from List<A> to List<B> when B extends A

Body:
I have two clases:

public class A {
   //attibutes and methods
}

public class B extends A {
   //atributes and methods
}

Now I have a service that returns a List with elements of type A. Lets call it generateAElements();

I want to call that method, filter the List obtained to only keep the elements of type B, which also are of type A.

List listA = generateAElements();
List listAA = listA.filter( p -> p instanceof B).collect(Collectors.toList());
List listB = new ArrayList<>();
// need to create a new list, iterate overListA and add elements of type B?
for (A itemA : listA) {
    listB.add((B) itemA);
}

Is there an efficient way to do this?

Important: The list may contain a large number of elements.

Body:
Stream free version. You just need to do a compatibility check before casting and you are good to do whatever you want.

List<A> listA = generateAElements();
List<B> listB = new LinkedList<>();
for (A item : listA) {
    // Skip non compatable items
    if(item instanceof B)
        listB.add((B) item);
}

The key difference from the OP's code is the line if(item instanceof B), that does the filter/error-checking the OP needed, but didn't do. (This is technically the exact same thing the stream version is doing, but slightly more verbose and much less overhead)


问:
Parse JSON using Linux bash shell and Underscore
The code below doesn't do what I need it to. I want to pass $STR to Underscore and pluck out the "name" attribute from the JSON data.

```<code>#!/bin/bash
STR='['$@']';
RESULT=`underscore pluck --data '+$STR+' name`;
echo $RESULT;
</code>```

JSON Data:

```<code>{"maxResults":1,"resultList":[{"@class":"com.sohnar.trafficlite.transfer.crm.refactor.ClientCRMEntryTO","id":331458,"version":2,"dateCreated":"2017-05-31T13:20:22.960+0000","dateModified":"2017-06-05T14:23:59.961+0000","lastUpdatedUserId":71954,"name":"ACME_CLIENT","website":null,"description":null,"billingLocation":null,"primaryLocation":null,"crmEntryType":"CLIENT","industryType":null,"accountManagerId":103049,"crmClientClassificationListItemId":{"id":12405},"companyProfile":{"id":486024,"version":1,"dateCreated":"2017-05-31T13:20:22.960+0000","dateModified":"2017-06-05T14:23:59.962+0000","sourceOfBusinessListItemId":null,"creditTermsListItemId":{"id":4215},"relationshipSince":"2017-05-30T23:00:00.000+0000","turnover":0,"employees":0,"taxNumber":null,"companyNumber":null,"nominalCode":null,"accountPackageId":null,"optOutMarketing":false,"optOutEmail":false,"optOutTelephone":false,"notes":null},"colorCode":0,"externalCode":"SAP-01","clientState":"CLIENT","defaultCustomRateSetId":null,"preferredCurrencyId":{"id":48},"freeTags":[]}],"windowSize":5,"currentPage":1}
</code>```

答:
I figured it out...</p>

```<code>#!/bin/bash
name=$(underscore select .name --outfmt text < get.crm.client.acme.json)
echo $name
</code>```

Body:
The code below doesn't do what I need it to. I want to pass $STR to Underscore and pluck out the "name" attribute from the JSON data.

#!/bin/bash
STR='['$@']';
RESULT=`underscore pluck --data '+$STR+' name`;
echo $RESULT;

JSON Data:

{"maxResults":1,"resultList":[{"@class":"com.sohnar.trafficlite.transfer.crm.refactor.ClientCRMEntryTO","id":331458,"version":2,"dateCreated":"2017-05-31T13:20:22.960+0000","dateModified":"2017-06-05T14:23:59.961+0000","lastUpdatedUserId":71954,"name":"ACME_CLIENT","website":null,"description":null,"billingLocation":null,"primaryLocation":null,"crmEntryType":"CLIENT","industryType":null,"accountManagerId":103049,"crmClientClassificationListItemId":{"id":12405},"companyProfile":{"id":486024,"version":1,"dateCreated":"2017-05-31T13:20:22.960+0000","dateModified":"2017-06-05T14:23:59.962+0000","sourceOfBusinessListItemId":null,"creditTermsListItemId":{"id":4215},"relationshipSince":"2017-05-30T23:00:00.000+0000","turnover":0,"employees":0,"taxNumber":null,"companyNumber":null,"nominalCode":null,"accountPackageId":null,"optOutMarketing":false,"optOutEmail":false,"optOutTelephone":false,"notes":null},"colorCode":0,"externalCode":"SAP-01","clientState":"CLIENT","defaultCustomRateSetId":null,"preferredCurrencyId":{"id":48},"freeTags":[]}],"windowSize":5,"currentPage":1}

Body:
I figured it out...

#!/bin/bash
name=$(underscore select .name --outfmt text < get.crm.client.acme.json)
echo $name


问:
Javascript SVG Interaction Issue
I am trying to develop an interactive SVG map and I want to do stuff when the mouse enters rectangles within the SVG image. Currently, the code logs to the console when my mouse enters the SVG image, but not when I mouse over the rectangles. Any help would be much appreciated. Thanks!

<object onload="svgOnLoad()" id="activeSVG" data="SVGNAME.svg" type="image/svg+xml">
</object>

  ```

答:
There is a short description, e.g., on https://www.tutorialspoint.com/svg/svg_interactivity.htm.

For mouseover events you need the jQuery mouseover function: https://api.jquery.com/mouseover/

Title: Javascript SVG Interaction Issue


问:
Resize SVG contents based on the result of rendering
I thought this would be obvious and I must be missing something, but take this very simple code

```<code><svg style="width:1000px;height:600px;border:1px solid red">
    <path d="M150 0 L75 200 L225 200 Z" />
    <text x="50" y="15" fill="red" text-anchor="end">A very long string A very long string A very long string</text>
</svg>
</code>```

The text goes off to the left and gets chopped because its effective coordinates go negative.

I want to rescale and rezoom my SVG contents so that, after rendering, everything is visible and the leftmost content is on the left boundary and the rightmost content is on the right boundary, same with top and bottom.

I'm using d3 so anything in there that achieves this end goal would be good also.

```<code>ensureEverythingIsVisible="1"  // would be great :--)
</code>```

<svg style="width:1000px;height:600px;border:1px solid red">
    <path d="M150 0 L75 200 L225 200 Z" />
    <text x="50" y="15" fill="red" text-anchor="end">A very long string A very long string A very long string</text>
</svg>```

答:
OK I found a way using javascript. I hadn't looked into getBBox much and that is the solution:

var svg = d3.select("svg");
var svgnode = svg.node();
var bbox = svgnode.getBBox();
svg.attr("viewBox", bbox.x + " " + bbox.y + " " + bbox.width + " " + bbox.height);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg style="width:1000px;height:600px;border:1px solid red">
    <path d="M150 0 L75 200 L225 200 Z" />
    <text x="50" y="15" fill="red" text-anchor="end">A very long string A very long string A very long string</text>
</svg></code>```

Body:
I thought this would be obvious and I must be missing something, but take this very simple code

<svg style="width:1000px;height:600px;border:1px solid red">
    <path d="M150 0 L75 200 L225 200 Z" />
    <text x="50" y="15" fill="red" text-anchor="end">A very long string A very long string A very long string</text>
</svg>

The text goes off to the left and gets chopped because its effective coordinates go negative.

I want to rescale and rezoom my SVG contents so that, after rendering, everything is visible and the leftmost content is on the left boundary and the rightmost content is on the right boundary, same with top and bottom.

I'm using d3 so anything in there that achieves this end goal would be good also.

ensureEverythingIsVisible="1"  // would be great :--)

<svg style="width:1000px;height:600px;border:1px solid red">
    <path d="M150 0 L75 200 L225 200 Z" />
    <text x="50" y="15" fill="red" text-anchor="end">A very long string A very long string A very long string</text>
</svg>

Body:
OK I found a way using javascript. I hadn't looked into getBBox much and that is the solution:

var svg = d3.select("svg");
var svgnode = svg.node();
var bbox = svgnode.getBBox();
svg.attr("viewBox", bbox.x + " " + bbox.y + " " + bbox.width + " " + bbox.height);

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg style="width:1000px;height:600px;border:1px solid red">
    <path d="M150 0 L75 200 L225 200 Z" />
    <text x="50" y="15" fill="red" text-anchor="end">A very long string A very long string A very long string</text>
</svg>


问:
Search and Replace in PHPMyAdmin database for Wordpress (absolute beginner)
I apologise in advance for I know that this question has been asked several times already, but being a complete beginner at wordpress coding and database handling, I am still not sure about what those answers really meant.
So having just coded a website and converted it into WordPress, I now find myself having to change all of the localhost strings to the accurate ones, but with hundreds to go through, I just wanted to know if any of you were able to recommend a program or technique within PHPMyAdmin (that I may not be aware of) to avoid having to change them one at a time.
Thank you all in advance for your time and attention.</p>

答:
Without any doubt I would use http://interconnectit.com/products/search-and-replace-for-wordpress-databases/

This tool is especially designed for the situation you describe.

You upload the code to your server and then enter the "find" and "replace"

You can then do a dry run and the system will show you all the replaces that will be made across every single table in your Wordpress database.

Once you're happy then you can do a live run and the changes are made.

I have used this on probably one hundred Wordpress sites and it works a charm.


问:
React Recursion
Im trying to let a function call itself to do some recursion. But I cant seem to find out how to access the function from within itself. Probably a syntax problem - can anyone help?. It throws
TypeError: Cannot read property 'recursiveRenderChildren' of undefined

```<code>import React, { Component } from 'react';

export default class ComposeDom extends Component {

    render() {
        return <div>
            {this.recursiveRenderChildren(this.props.cdom.treeData)}
        </div>
    }
    recursiveRenderChildren(children) {
        return children.map(function(child){
            console.log(child);
            return <child.slug key={child.title}>{child.title} {this.recursiveRenderChildren(child.children)}</child.slug>
        })
}
</code>```

答:
The function should be like this:-</p>

```<code>recursiveRenderChildren(children) {
        let that = this;
        return children.map(function(child){
          console.log(child);
            return <child.slug key={child.title}>{child.title} {that.recursiveRenderChildren(child.children)}</child.slug>
        })
  }
</code>```

Title: React Recursion

Body:
Im trying to let a function call itself to do some recursion. But I cant seem to find out how to access the function from within itself. Probably a syntax problem - can anyone help?. It throws
TypeError: Cannot read property 'recursiveRenderChildren' of undefined

import React, { Component } from 'react';

export default class ComposeDom extends Component {

    render() {
        return

            {this.recursiveRenderChildren(this.props.cdom.treeData)}

    }
    recursiveRenderChildren(children) {
        return children.map(function(child){
            console.log(child);
            return <child.slug key={child.title}>{child.title} {this.recursiveRenderChildren(child.children)}</child.slug>
        })
}

Body:
The function should be like this:-

recursiveRenderChildren(children) {
        let that = this;
        return children.map(function(child){
          console.log(child);
            return <child.slug key={child.title}>{child.title} {that.recursiveRenderChildren(child.children)}</child.slug>
        })
  }


问:
Telnet not valid when opening command prompt with Ruby
When I open a command prompt manually and type the following command I get a response from the server I am pinging.

```<code>telnet <server> <port>
</code>```

When I open the command prompt with Ruby, using the following command, and run the same telnet command above, I get ''telnet' is not recognized as an internal or external command, operable program or batch file.'

Ruby command:

```<code>system('start cmd.exe)
</code>```

It opens the prompt fine, but the command itself is not working, and I am not sure to why that is.

答:
Some good next steps are:

Locate telnet.exe using WHERE, then invoke system with the path to telnet.exe.

Instead of system, I recommend using Open3.popen3() so that you can interact with the actual telnet program via STDIN, STDOUT, and STDERR.

Lastly, instead of any of the above options I would suggest that you use net-telnet as it exposes an easier API to use versus wrapping the Windows Telnet client.

Body:
When I open a command prompt manually and type the following command I get a response from the server I am pinging.

telnet <server> <port>

When I open the command prompt with Ruby, using the following command, and run the same telnet command above, I get ''telnet' is not recognized as an internal or external command, operable program or batch file.'

Ruby command:

system('start cmd.exe)

It opens the prompt fine, but the command itself is not working, and I am not sure to why that is.