问:
How to upload a .mp3 file in HTML / Javascript and send to Java backend
We're trying to upload a song (.mp3) file from a JSP frontend written in HTML / Javascript. We need to upload to our Java backend using websockets. Does anyone have any suggestions on how we would could go about doing this?

Currently we are doing something like this on our JSP file:

```<code>    <h1>Please Choose a Song file</h1>
    <form name = "JSONUploadForm">
        <input type = "file" name="file" accept = ".mp3"/> <br/>
        <input type = "button" value = "Click to upload!" name = "button" onClick = "submitSong();"/>
    </form>
</code>```

Then we have our javascript function submitSong()

```<code>function submitSong(){
    var songStuffs = document.getElementById("file");
    console.log(songStuffs); --> we get "null" here
    sendMessage(songStuffs);
    alert("song sent");
}

function sendMessage(val, string) {
    socket.send(string);
    return false;
}
</code>```

Also, here is our connect to server function. However, this functions correctly.

```<code>function connectToServer() {
    socket = new
    WebSocket("ws://localhost:8080/Project/socket");
    socket.onopen = function(event) {
    console.log("connected!");
}
</code>```

You can also see our server side (.java file):

```<code>@OnMessage
public void onMessage(String message, Session session) throws IOException, EncodeException {
        FileWriter fw = new FileWriter(new File(songName + ".mp3"));
        fw.write(song);

        BufferedReader fr = new BufferedReader(new FileReader(songName + ".mp3"));
        String data = fr.readLine();

        System.out.println("Song: " + data); --> Here we get "song: null"
}
</code>```

Any suggestions would be greatly appreciated!

答:
In your code you have an error

"var songStuffs = document.getElementById("file");"

Your file input without id.
this will work "var songStuffs = document.querySelector("[name=file]");"

I prefer using querySelector, because it mo flexeble and works exactly like jquery query selectors)))

You do not need any form, for upload files.
Please read this article https://www.html5rocks.com/en/tutorials/websockets/basics/,
it will be useful for you (search words "blob" at the page)

Html

```<code><input id="file" type = "file" name="file" accept = ".mp3"/>
</code>```

Code

```<code>var fileInput = document.querySelector("#file");
fileInput.addEventListener("change",function(){
   connection.send(fileInput.files[0]);
});
</code>```

If you need to send file and fields, you have 3 variants

create JSON {"field1":"value1","field2":"value1",
"file":"base64"}

manualy create formdata and parse form data at the
server with some webform stuff (example
https://stackoverflow.com/a/47279216/5138198)

Firstly send JSON
data, secondly send a file

Body:
We're trying to upload a song (.mp3) file from a JSP frontend written in HTML / Javascript. We need to upload to our Java backend using websockets. Does anyone have any suggestions on how we would could go about doing this?

Currently we are doing something like this on our JSP file:

Please Choose a Song file

    <form name = "JSONUploadForm">
        <input type = "file" name="file" accept = ".mp3"/>

        <input type = "button" value = "Click to upload!" name = "button" onClick = "submitSong();"/>
    </form>

Then we have our javascript function submitSong()

function submitSong(){
    var songStuffs = document.getElementById("file");
    console.log(songStuffs); --> we get "null" here
    sendMessage(songStuffs);
    alert("song sent");
}

function sendMessage(val, string) {
    socket.send(string);
    return false;
}

Also, here is our connect to server function. However, this functions correctly.

function connectToServer() {
    socket = new
    WebSocket("ws://localhost:8080/Project/socket");
    socket.onopen = function(event) {
    console.log("connected!");
}

You can also see our server side (.java file):

@OnMessage
public void onMessage(String message, Session session) throws IOException, EncodeException {
        FileWriter fw = new FileWriter(new File(songName + ".mp3"));
        fw.write(song);

        BufferedReader fr = new BufferedReader(new FileReader(songName + ".mp3"));
        String data = fr.readLine();

        System.out.println("Song: " + data); --> Here we get "song: null"
}

Any suggestions would be greatly appreciated!

Body:
In your code you have an error

"var songStuffs = document.getElementById("file");"

Your file input without id.
this will work "var songStuffs = document.querySelector("[name=file]");"

I prefer using querySelector, because it mo flexeble and works exactly like jquery query selectors)))

You do not need any form, for upload files.
Please read this article https://www.html5rocks.com/en/tutorials/websockets/basics/,
it will be useful for you (search words "blob" at the page)

Html

<input id="file" type = "file" name="file" accept = ".mp3"/>

Code

var fileInput = document.querySelector("#file");
fileInput.addEventListener("change",function(){
   connection.send(fileInput.files[0]);
});

If you need to send file and fields, you have 3 variants

create JSON {"field1":"value1","field2":"value1",
"file":"base64"}

manualy create formdata and parse form data at the
server with some webform stuff (example
https://stackoverflow.com/a/47279216/5138198)

Firstly send JSON
data, secondly send a file


来源: stackexchange

问:
How to get images field from a Group Feed - Facebook Graph API
I have been using Graph API for a while, but I am not able to figure this one out.
I have a group id, from whose feed I want to get the image urls for all available resolutions.

I know I can do that using the 'images' field of a photo id.
Here is a sample code which gets the id

```<code><group-id>/feed?fields=attachments{target{id}}
</code>```

I tried

```<code><group-id>/feed?fields=attachments{target{id{images}}}
</code>```

and also this

```<code><group-id>/feed?fields=attachments.fields(target.fields(id{images}))
</code>```

and this

```<code><group-id>/feed?fields=attachments.fields(target.fields(id.fields(images)))
</code>```

All of them return the JSON having the id, but not the images details I need.

I hope I have provided enough information.

答:
You can use the below format while calling the API and it will return you with the images URL included in the post

```<code><group-id>/feed?fields=created_time,attachments,message
</code>```

You  will get the response in the below format.

```<code>{
      "created_time": "2017-11-16T06:21:37+0000",
      "id": "543993212434753_1004360179731385",
      "attachments": {
        "data": [
          {
            "description": "Best #ethnic wear store for #women.
Shop Now>> sairandhri.com",
            "media": {
              "image": {
                "height": 720,
                "src": "https://scontent.xx.fbcdn.net/v/t1.0-9/s720x720/23519069_887109751445971_6170575397465061641_n.jpg?oh=170436ae447ec615f547d700017c67b4&oe=5AA4F844",
                "width": 537
              }
            },
            "target": {
              "id": "887109751445971",
              "url": "https://www.facebook.com/SairandhriShowroom/photos/a.302015823288703.1073741828.300462640110688/887109751445971/?type=3"
            },
            "type": "photo",
            "url": "https://www.facebook.com/SairandhriShowroom/photos/a.302015823288703.1073741828.300462640110688/887109751445971/?type=3"
          }
        ]
      }
    }
</code>```

Its working and tested on Graph API Explorer

ContentLicense: CC BY-SA 3.0

Body:
I have been using Graph API for a while, but I am not able to figure this one out.
I have a group id, from whose feed I want to get the image urls for all available resolutions.

I know I can do that using the 'images' field of a photo id.
Here is a sample code which gets the id

<group-id>/feed?fields=attachments{target{id}}

I tried

<group-id>/feed?fields=attachments{target{id{images}}}

and also this

<group-id>/feed?fields=attachments.fields(target.fields(id{images}))

and this

<group-id>/feed?fields=attachments.fields(target.fields(id.fields(images)))

All of them return the JSON having the id, but not the images details I need.

I hope I have provided enough information.

Body:
You can use the below format while calling the API and it will return you with the images URL included in the post

<group-id>/feed?fields=created_time,attachments,message

You  will get the response in the below format.

{
      "created_time": "2017-11-16T06:21:37+0000",
      "id": "543993212434753_1004360179731385",
      "attachments": {
        "data": [
          {
            "description": "Best #ethnic wear store for #women.
Shop Now>> sairandhri.com",
            "media": {
              "image": {
                "height": 720,
                "src": "https://scontent.xx.fbcdn.net/v/t1.0-9/s720x720/23519069_887109751445971_6170575397465061641_n.jpg?oh=170436ae447ec615f547d700017c67b4&oe=5AA4F844",
                "width": 537
              }
            },
            "target": {
              "id": "887109751445971",
              "url": "https://www.facebook.com/SairandhriShowroom/photos/a.302015823288703.1073741828.300462640110688/887109751445971/?type=3"
            },
            "type": "photo",
            "url": "https://www.facebook.com/SairandhriShowroom/photos/a.302015823288703.1073741828.300462640110688/887109751445971/?type=3"
          }
        ]
      }
    }

Its working and tested on Graph API Explorer


问:
How can i prevent duplicate Record in Array
I need to prevent inserting duplicate Rec in $scope.EmployeeList Array   For that i wrote if ($scope.EmployeeList.indexOf(EmpDetails) == -1)  but its not filtering my rec

```<code> $scope.EmployeeList = [];
        var amtArray = [];
        $scope.G_Total = "Total Amount is";
        $scope.SaveDb = function (Isvalid) {
            var EmpDetails = {
                'EmpName': $scope.EmpName,
                'Email': $scope.Email,
                'Cost': $scope.cost

            }
            if ($scope.EmployeeList.indexOf(EmpDetails) == -1) {
                $scope.EmployeeList.push(EmpDetails);
                console.log($scope.EmployeeList);
            }
            else
                alert('Duplicate Value....');
</code>```

答:
Don't use indexOf (it checks for strict equality), try findIndex:

```<code>if ($scope.EmployeeList.findIndex(function(e) { return e.EmpName === EmpDetails.EmpName; }) === -1) {
    $scope.EmployeeList.push(EmpDetails);
    console.log($scope.EmployeeList);
}
</code>```

Body:
I need to prevent inserting duplicate Rec in $scope.EmployeeList Array   For that i wrote if ($scope.EmployeeList.indexOf(EmpDetails) == -1)  but its not filtering my rec

 $scope.EmployeeList = [];
        var amtArray = [];
        $scope.G_Total = "Total Amount is";
        $scope.SaveDb = function (Isvalid) {
            var EmpDetails = {
                'EmpName': $scope.EmpName,
                'Email': $scope.Email,
                'Cost': $scope.cost

            }
            if ($scope.EmployeeList.indexOf(EmpDetails) == -1) {
                $scope.EmployeeList.push(EmpDetails);
                console.log($scope.EmployeeList);
            }
            else
                alert('Duplicate Value....');

Body:
Don't use indexOf (it checks for strict equality), try findIndex:

if ($scope.EmployeeList.findIndex(function(e) { return e.EmpName === EmpDetails.EmpName; }) === -1) {
    $scope.EmployeeList.push(EmpDetails);
    console.log($scope.EmployeeList);
}


问:
What's the best way to run a python script daily?
I have a python script that connects to Redshift, executes a series of SQL commands, and generates a new derived table.

But for the life of me, I can't figure out a way to have it automatically run every day.

I've tried AWS Data Pipeline but my shell script won't run the first copy statement.
I can't get Lambda or Glue to work because my company's IAM policies are restrictive.
Airflow seems like overkill to just run a single python script daily.

Any suggestions for services to look into?

答: I use a scheduled task on Windows. Either enter it using the GUI or the at command.</p>


问:
What is the meaning of this regular expression? ['`?!\"-/]
What is the meaning of this regular expression?

```<code>    ['`?!\"-/]
</code>```

Why it matches parenthesis?

I used Java for development

答:
In your regex

```<code>['`?!\"-/]
</code>```

The quantity "-/ is being interpreted as a range of values, just as A-Z would mean taking every letter between A and Z.  It turns out, by reading the basic ASCII table, that parentheses lie within this range, so your pattern is including them.

One trick you can use here with dash is to place it at the end:

```<code>['`?!\"/-]
        ^^^^ this will not be interpreted as a range
</code>```

Body:
What is the meaning of this regular expression?

    ['`?!\"-/]

Why it matches parenthesis?

I used Java for development

Body:
In your regex

['`?!\"-/]

The quantity "-/ is being interpreted as a range of values, just as A-Z would mean taking every letter between A and Z.  It turns out, by reading the basic ASCII table, that parentheses lie within this range, so your pattern is including them.

One trick you can use here with dash is to place it at the end:

['`?!\"/-]
        ^^^^ this will not be interpreted as a range


问:
Merge the two different JSON using node JS
I have two requests that return their data as JSON using NodeJS Seriate.

The first response is:

```<code>{
    "status": true,
    "message": "Data Found",
    "data": [
        {
            "statusCode": 200,
            "body": {
                "expand": "renderedFields,names,schem,operations,editmeta,changelog,versionedRepresentations",
                "id": "64672",
                "self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
                "key": "CKS-2016",
                "fields": {
                    "parent": {
                        "id": "64670",
                        "key": "CKS-2014"
                    }
                }
            }
        }
    ]
}
</code>```

The second response is:

```<code>{
    "statusCode": 200,
    "body": {
        "errors": [],
        "detail": [
            {
                "repositories": [
                    {
                        "name": "registry",
                        "avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
                        "avatarDescription": "services"
                    }
                ]
            }
        ]
    }
}
</code>```

I want to merge the two responses, that would have the following structure:

```<code>{
    "status": true,
    "message": "Data Found",
    "data": [
        {
            "statusCode": 200,
            "body": {
                "expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
                "id": "64672",
                "self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
                "key": "CKS-2016",
                "fields": {
                    "parent": {
                        "id": "64670",
                        "key": "CKS-2014",
                        "detail": [
                            {
                                "repositories": [
                                    {
                                        "name": "registry",
                                        "avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
                                        "avatarDescription": "services"
                                    }
                                ]
                            }
                        ]
                    }
                }
            }
        }
    ]
}
</code>```

I searched and found several methods of joining or extending two JSON objects but nothing similar to that.

How can I achieve this?

My Actual Code is,

```<code>exports.getIssues = function(req, res) {
    console.log(filename + '>>get Issues>>');
    var response = {
        status : Boolean,
        message : String,
        data : String
    };
    var request = require('request');
    var username = const.username ;
    var password = const.password ;
    var options = {
        url : 'https://computenext.atlassian.net/rest/api/2/search?jql=status+%3D+Resolved+ORDER+BY+updated',
        auth : {
            username : username,
            password : password
        }
    };

    request( options, function(error, obj) {
                if (error) {
                    response.message = appmsg.DATA_NT_FOUND;
                    response.status = false;
                    response.data = obj;
                    res.send(response);
                } else {
                     response.message = appmsg.DATA_FOUND;
                     response.status = true;
                     response.data = JSON.parse(obj.body);
                     //res.send(response);
                    var issueKey = response.data.issues;

                    // var keyData = issueKey[0].key;
                    // console.log(response.data.issues);
                    // console.log(keyData);
                    var output = [];
                    for(var i = 0; i < issueKey.length; i++) {
                        var issue = issueKey[i].key;
                        //var key = [];
                        //key.push(issue);
                        console.log(issue);

                        var respon = {
                            status : Boolean,
                            message : String,
                            data : String
                        };
                            var request = require('request'),
                                username = const.username ,
                                password = const.username ,
                                url = "https://computenext.atlassian.net/rest/api/2/issue/" + issue,
                                auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

                            //console.log(url);
                            request({url : url,headers : {"Authorization" : auth}}, function(err, object){
                                if (object) {

                                        var info = object;
                                        output.push(info); // this is not working as ouput is undefined at this    point
                                        //var pout = JSON.parse(output);
                                        //console.log(info);
                                        console.log("==============================================================================");
                                        //console.log(output);
                                        console.log("******************************************************************************");
                                            if(issueKey.length === output.length){
                                                respon.message = appmsg.DATA_FOUND;
                                                respon.status = true;
                                                respon.data = output;
                                                //console.log(output);
                                                //res.send(respon);

                                                  var id = issueKey[0].id;
                                                  console.log(id);

                                                   var commitout = [];
                                                    for(var i = 0; i < issueKey.length; i++) {
                                                        var commits = issueKey[i].id;
                                                        console.log(commits);

                                                      var request = require('request'),
                                                      username = const.username ,
                                                      password = const.password ,
                                                      url = "https://computenext.atlassian.net/rest/dev-status/1.0/issue/detail?issueId=" + commits + "&applicationType=stash&dataType=repository",
                                                      auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

                                                    //console.log(url);
                                                    var test = [];
                                                    request({url : url,headers : {"Authorization" : auth}}, function(err, obj1){
                                                      if (obj1) {

                                                              var info1 = obj1.body;
                                                              commitout.push(info1);
                                                              if(issueKey.length === commitout.length){
                                                                respon.message = appmsg.DATA_FOUND;
                                                                respon.status = true;
                                                                respon.data = commitout;
                                                                // console.log(commitout);
                                                                  //var test = merge(output, commitout);

                                                                  var text = output.body;
                                                                  var resultdone = output;

                                                                  resultdone.data = resultdone + commitout.body;

                                                                  console.log(resultdone.data);

                                                                res.send(resultdone.data);
                                                              }
                                                            }
                                                   });
                                                  }

                                    }
                                }

                        });

                }
            }

        });
</code>```

};

How can i merge the two arrays? in one response. That is my question..

答:
```<code>var obj1  = {
"status": true,
"message": "Data Found",
"data": [
    {
        "statusCode": 200,
        "body": {
            "expand": "renderedFields,names,schem,operations,editmeta,changelog,versionedRepresentations",
            "id": "64672",
            "self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
            "key": "CKS-2016",
            "fields": {
                "parent": {
                    "id": "64670",
                    "key": "CKS-2014"
                }
            }
        }
    }
]};

var obj2 = {
"statusCode": 200,
"body": {
    "errors": [],
    "detail": [
        {
            "repositories": [
                {
                    "name": "registry",
                    "avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
                    "avatarDescription": "services"
                }
            ]
        }
    ]}
   }

  obj1.data.forEach(function(item, index){
      item.body.fields.parent.detail = r.body.detail[index];
  });

  console.log(obj1);
</code>```

Body:
I have two requests that return their data as JSON using NodeJS Seriate.

The first response is:

{
    "status": true,
    "message": "Data Found",
    "data": [
        {
            "statusCode": 200,
            "body": {
                "expand": "renderedFields,names,schem,operations,editmeta,changelog,versionedRepresentations",
                "id": "64672",
                "self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
                "key": "CKS-2016",
                "fields": {
                    "parent": {
                        "id": "64670",
                        "key": "CKS-2014"
                    }
                }
            }
        }
    ]
}

The second response is:

{
    "statusCode": 200,
    "body": {
        "errors": [],
        "detail": [
            {
                "repositories": [
                    {
                        "name": "registry",
                        "avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
                        "avatarDescription": "services"
                    }
                ]
            }
        ]
    }
}

I want to merge the two responses, that would have the following structure:

{
    "status": true,
    "message": "Data Found",
    "data": [
        {
            "statusCode": 200,
            "body": {
                "expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
                "id": "64672",
                "self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
                "key": "CKS-2016",
                "fields": {
                    "parent": {
                        "id": "64670",
                        "key": "CKS-2014",
                        "detail": [
                            {
                                "repositories": [
                                    {
                                        "name": "registry",
                                        "avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
                                        "avatarDescription": "services"
                                    }
                                ]
                            }
                        ]
                    }
                }
            }
        }
    ]
}

I searched and found several methods of joining or extending two JSON objects but nothing similar to that.

How can I achieve this?

My Actual Code is,

exports.getIssues = function(req, res) {
    console.log(filename + '>>get Issues>>');
    var response = {
        status : Boolean,
        message : String,
        data : String
    };
    var request = require('request');
    var username = const.username ;
    var password = const.password ;
    var options = {
        url : 'https://computenext.atlassian.net/rest/api/2/search?jql=status+%3D+Resolved+ORDER+BY+updated',
        auth : {
            username : username,
            password : password
        }
    };

    request( options, function(error, obj) {
                if (error) {
                    response.message = appmsg.DATA_NT_FOUND;
                    response.status = false;
                    response.data = obj;
                    res.send(response);
                } else {
                     response.message = appmsg.DATA_FOUND;
                     response.status = true;
                     response.data = JSON.parse(obj.body);
                     //res.send(response);
                    var issueKey = response.data.issues;

                    // var keyData = issueKey[0].key;
                    // console.log(response.data.issues);
                    // console.log(keyData);
                    var output = [];
                    for(var i = 0; i < issueKey.length; i++) {
                        var issue = issueKey[i].key;
                        //var key = [];
                        //key.push(issue);
                        console.log(issue);

                        var respon = {
                            status : Boolean,
                            message : String,
                            data : String
                        };
                            var request = require('request'),
                                username = const.username ,
                                password = const.username ,
                                url = "https://computenext.atlassian.net/rest/api/2/issue/" + issue,
                                auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

                            //console.log(url);
                            request({url : url,headers : {"Authorization" : auth}}, function(err, object){
                                if (object) {

                                        var info = object;
                                        output.push(info); // this is not working as ouput is undefined at this    point
                                        //var pout = JSON.parse(output);
                                        //console.log(info);
                                        console.log("==============================================================================");
                                        //console.log(output);
                                        console.log("******************************************************************************");
                                            if(issueKey.length === output.length){
                                                respon.message = appmsg.DATA_FOUND;
                                                respon.status = true;
                                                respon.data = output;
                                                //console.log(output);
                                                //res.send(respon);

                                                  var id = issueKey[0].id;
                                                  console.log(id);

                                                   var commitout = [];
                                                    for(var i = 0; i < issueKey.length; i++) {
                                                        var commits = issueKey[i].id;
                                                        console.log(commits);

                                                      var request = require('request'),
                                                      username = const.username ,
                                                      password = const.password ,
                                                      url = "https://computenext.atlassian.net/rest/dev-status/1.0/issue/detail?issueId=" + commits + "&applicationType=stash&dataType=repository",
                                                      auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

                                                    //console.log(url);
                                                    var test = [];
                                                    request({url : url,headers : {"Authorization" : auth}}, function(err, obj1){
                                                      if (obj1) {

                                                              var info1 = obj1.body;
                                                              commitout.push(info1);
                                                              if(issueKey.length === commitout.length){
                                                                respon.message = appmsg.DATA_FOUND;
                                                                respon.status = true;
                                                                respon.data = commitout;
                                                                // console.log(commitout);
                                                                  //var test = merge(output, commitout);

                                                                  var text = output.body;
                                                                  var resultdone = output;

                                                                  resultdone.data = resultdone + commitout.body;

                                                                  console.log(resultdone.data);

                                                                res.send(resultdone.data);
                                                              }
                                                            }
                                                   });
                                                  }

                                    }
                                }

                        });

                }
            }

        });

};

How can i merge the two arrays? in one response. That is my question..


问:
Laravel retrieve only the email address column in database for users table
Hi I had code that stated

```<code>    $users = User::all();
</code>```

But I only want the email addresses of the users in a collection. So I tried:

```<code>    $users = User::select('id', 'email')->first();
</code>```

This does not work as I want. When I do a var_dump I only want to see the users email addresses. Any tips?

UPDATE: I inserted my blade code as well. I use a Vue component that has a dropdown and I filter the data in the Vue method and insert the filtered data under userEmail:

The component:

```<code>    <commands-component
                :entity-config="commandConfig(command.id, command.signature, command.hasUser, command.title, command.groupID, command.groupName)">
                <input style="margin-right:10px;margin-bottom:10px;" type="button" class="btn btn-primary" v-bind:value="command.title" v-on:click='disableEmailText(command.hasUser)'>
        </commands-component>
</code>```

The Vue:

```<code>    var systemadmin = new Vue({
    el: "#sysadmin",
    data: function() {
        return {
          users: <?php echo $users ?>,
          userData: [],
          commands: <?php echo $commands ?>,
        }
    },

    methods: {
      commandConfig: function(ident, signature, hasUser, title, groupId, groupName){
        var that =  this;
        var commandsGetUsers = [];

        commandsGetUsers  = _.map(that.users, function(value) {
            var newValue = {};
            newValue.value = value.id;
            newValue.text = value.email;
            return newValue;
        });

        return {
          id: { text: 'commandModal' + ident, id: null },
          modalTitle: title,
          buttons: [
              {
                  buttonTitle: 'Run Command',
                  buttonClass: 'btn btn-success pull-right',
                  submitUrl: {
                      url: '/admin/artisan/commands/run',

                  },
              }
          ],
          attributes: [
            {name: "message", displayName: "Are you sure you want to proceed with the command?", type: "action-text",  col: "12" },
            {name: "signature", displayName: "Command Signature", type:'text', col:"6"},
            {name: "userEmail", displayName: "Users", type: 'select', options: commandsGetUsers, col:'6'}
          ],
          data: {
              signature:signature,
              hasUser:hasUser
          }
        };

      },
</code>```

答: $users = User::all()->pluck('email');

Body:
Hi I had code that stated

    $users = User::all();

But I only want the email addresses of the users in a collection. So I tried:

    $users = User::select('id', 'email')->first();

This does not work as I want. When I do a var_dump I only want to see the users email addresses. Any tips?

UPDATE: I inserted my blade code as well. I use a Vue component that has a dropdown and I filter the data in the Vue method and insert the filtered data under userEmail:

The component:

    <commands-component
                :entity-config="commandConfig(command.id, command.signature, command.hasUser, command.title, command.groupID, command.groupName)">
                <input style="margin-right:10px;margin-bottom:10px;" type="button" class="btn btn-primary" v-bind:value="command.title" v-on:click='disableEmailText(command.hasUser)'>
        </commands-component>

The Vue:

    var systemadmin = new Vue({
    el: "#sysadmin",
    data: function() {
        return {
          users: <?php echo $users ?>,
          userData: [],
          commands: <?php echo $commands ?>,
        }
    },

    methods: {
      commandConfig: function(ident, signature, hasUser, title, groupId, groupName){
        var that =  this;
        var commandsGetUsers = [];

        commandsGetUsers  = _.map(that.users, function(value) {
            var newValue = {};
            newValue.value = value.id;
            newValue.text = value.email;
            return newValue;
        });

        return {
          id: { text: 'commandModal' + ident, id: null },
          modalTitle: title,
          buttons: [
              {
                  buttonTitle: 'Run Command',
                  buttonClass: 'btn btn-success pull-right',
                  submitUrl: {
                      url: '/admin/artisan/commands/run',

                  },
              }
          ],
          attributes: [
            {name: "message", displayName: "Are you sure you want to proceed with the command?", type: "action-text",  col: "12" },
            {name: "signature", displayName: "Command Signature", type:'text', col:"6"},
            {name: "userEmail", displayName: "Users", type: 'select', options: commandsGetUsers, col:'6'}
          ],
          data: {
              signature:signature,
              hasUser:hasUser
          }
        };

      },

Body: $users = User::all()->pluck('email');


问:
How to get ID of button when clicked while it is looped
[i am using this loop to select existing data from database table and assigning them to html  element. it works fine but I have no idea how to select its ID when the button is clicked.

I tried using document.GetElementByID but cannot choose particular ID when the button is clicked. Any suggestions on how to get the ID Of that button when it is clicked using javascript?

```<code><?php
include "connect.php";
$stmnt = "select * from tbl_category";
$run = $con->query($stmnt);
$num=$run->num_rows;
if($num>0)
{
while($data = $run->fetch_array()){
$btn1 = $data['id'];
echo $btn1;
?>
<button id="<?php $btn1;?>" class="btn"><?php echo $data['category']; ?>
</button>
<?php
}
}
?>`
</code>```

答:
You can do like this:

```<code>$( "button" ).click(function() {
  $( this ).attr("id");
});
</code>```

Or alternatively you can also use prop() method:

```<code>$( "button" ).click(function() {
  $( this ).prop("id");
});
</code>```

for documentation you can reff:

https://api.jquery.com/attr/

https://api.jquery.com/prop/

Body:
[i am using this loop to select existing data from database table and assigning them to html  element. it works fine but I have no idea how to select its ID when the button is clicked.

I tried using document.GetElementByID but cannot choose particular ID when the button is clicked. Any suggestions on how to get the ID Of that button when it is clicked using javascript?

<?php
include "connect.php";
$stmnt = "select * from tbl_category";
$run = $con->query($stmnt);
$num=$run->num_rows;
if($num>0)
{
while($data = $run->fetch_array()){
$btn1 = $data['id'];
echo $btn1;
?>
<button id="<?php $btn1;?>" class="btn"><?php echo $data['category']; ?>
</button>
<?php
}
}
?>`

Body:
You can do like this:

$( "button" ).click(function() {
  $( this ).attr("id");
});

Or alternatively you can also use prop() method:

$( "button" ).click(function() {
  $( this ).prop("id");
});

for documentation you can reff:

https://api.jquery.com/attr/

https://api.jquery.com/prop/


问:
STS Crash after project spring version upgrade 3 -> 4
Our application was using spring version 3.2.3.RELEASE and we decided to migrate it to 4.0.9.RELEASE.

After the upgrade we were unable to ever use STS again. When launch the workspace, STS stops responding after some time (5-30 min).

We tried downloading a STS new version, creating new workspaces, disabling all validations. Nothing worked so far but if we use a regular eclipse version we have no problems at all.

Does anyone have an idea on what could be the cause of this issue?

答:
I would suggest to open an issue at https://github.com/spring-projects/spring-ide/issues and provide more details.

Especially interesting will be to capture a thread dump while STS is being unresponsive (using jps and jstack). Would be great if you could attach a few of them to the issue.

You also said that you ran a fresh STS installation (I assume STS 3.9.x) with a fresh workspace. So what exactly did you do before STS becomes unresponsive?


问:
Convert from string(yyyyMMddHHmmss) to DateTime with SQL Server
I am migrating from Oracle's to_date function to SQL Server's convert function.

I want to know a good way to convert a string of format yyyyMMddHHmmss to DateTime type.

I could write a program, but it is too redundant, so I would like to know how to improve it.

```<code>'Get String Date (yyyyMMddHHmmss)
Dim strNowDate = Strings.Format(Now, "yyyyMMddHHmmss") 'format cannot be changed. (Because, referenced from many)

'some logics...

'Oracle script before migration.
sqlBuf.Append(" ,to_date('" & strNowDate & "', 'YYYYMMDDHH24MISS')" & vbCrLf)

'SQL Server script after migration.(too redundancy... I want to make it more cool.)
sqlBuf.Append(" ,convert(DATETIME, '" & DateTime.ParseExact(strNowDate, "yyyyMMddHHmmss", Globalization.DateTimeFormatInfo.InvariantInfo).ToString("yyyy-MM-dd HH:mm:ss") & "')" & vbCrLf)
</code>```

答:
ORACLE and SQL Server both are different, I assume its SQL Server.
try this

```<code>select
convert(datetime,stuff(stuff(stuff('20171116115733', 9, 0, ' '), 12, 0, ':'),
        15, 0, ':')) ConvertedDate
</code>```

there are many possible ways given here

https://rdineshkumar.wordpress.com/tag/how-to-convert-yyyymmddhhmmss-to-datetimedatetime-in-sql-server/

Body:
I am migrating from Oracle's to_date function to SQL Server's convert function.

I want to know a good way to convert a string of format yyyyMMddHHmmss to DateTime type.

I could write a program, but it is too redundant, so I would like to know how to improve it.

'Get String Date (yyyyMMddHHmmss)
Dim strNowDate = Strings.Format(Now, "yyyyMMddHHmmss") 'format cannot be changed. (Because, referenced from many)

'some logics...

'Oracle script before migration.
sqlBuf.Append(" ,to_date('" & strNowDate & "', 'YYYYMMDDHH24MISS')" & vbCrLf)

'SQL Server script after migration.(too redundancy... I want to make it more cool.)
sqlBuf.Append(" ,convert(DATETIME, '" & DateTime.ParseExact(strNowDate, "yyyyMMddHHmmss", Globalization.DateTimeFormatInfo.InvariantInfo).ToString("yyyy-MM-dd HH:mm:ss") & "')" & vbCrLf)

Body:
ORACLE and SQL Server both are different, I assume its SQL Server.
try this

select
convert(datetime,stuff(stuff(stuff('20171116115733', 9, 0, ' '), 12, 0, ':'),
        15, 0, ':')) ConvertedDate

there are many possible ways given here

https://rdineshkumar.wordpress.com/tag/how-to-convert-yyyymmddhhmmss-to-datetimedatetime-in-sql-server/


问:
Laravel - How to create multiple user roles and assign privilege to them?
I have to create an application in which there are 5 types of accounts

Super admin

Inventory admin

Shop owner

Shop manager

User

So How can I create these multiple accounts with Laravel, should I use different middleware group for each. also, i have to create privileges with all.

Currently, I am using it with different middleware and session for each and separate tables in DB for each, but I don't think so that's a good way to do it.

What is the way to create these multiple accounts with Laravel.

@Thanks

答:
In addition to providing authentication services, Laravel also provides a simple way to authorize user actions against a given resource. Laravel's approach to authorization is simple, and there are two primary ways of authorizing actions: gates and policies. Please refer the Laravel documentation for more details.

Authorization in Laravel 5.5


答:
You have same counter for outer and inner loop which is in this case incorrect. Use counter a and b then loop should work.

In inner loop b stays 11 after first iteration, if you want to achieve your expected result add b = 0 in your inner loop

Title: Loop program output

Body:
I got curious and experimented a little on looping and I kind of confused myself here.

Question 1:
Why does this code output 012345678910 instead of 00000000000111111111112222222222233333333333444444444445555555555566666666666777
7777777788888888888999999999991010101010101010101010 ?

for(a=0;a<=10;a++){
    for(a=0;a<=10;a++){
        printf("%d", a);
    }
}

Question 2: For the code shown below, does taking out the first statement mean that it would start on 0? If yes, then why does it output 12345678910 instead of 01234567891001234567891001234567891001234567891001234567891001234567891001234567
8910012345678910012345678910012345678910012345678910 ?

for(a=0;a<=10;a++){
    for(;b<=10;b++){
        printf("%d", b);
    }
}


问:
Surrounding specific HTML text with specific color
I have the a Status parameter for my HTML table which could take values such as :

SUCCESS

FAILURE

IN PROGRESS

I want to surround the text with a specific color depending on the value it takes. I am working with Angular 4 (HTML and TypeScript).

Any pointers to solve this problem?

答:
Try this, I did not test this but hope this helps:</p>

```<code>[ngStyle]="{'background-color':status === 'SUCCESS' ? 'green' : status === 'FAILURE' ? 'red' : 'blue'}
</code>```

Body:
Try this, I did not test this but hope this helps:

[ngStyle]="{'background-color':status === 'SUCCESS' ? 'green' : status === 'FAILURE' ? 'red' : 'blue'}


答:
You can use the only on collection.</p>

```<code>$emails = User::all()->map(function($user) {
    return $user->only(['email']);
});
</code>```

Title: Laravel retrieve only the email address column in database for users table

Body:
You can use the only on collection.

$emails = User::all()->map(function($user) {
    return $user->only(['email']);
});


问:
NodeJs construct Excel file and export in PDF
As the title said, I'm searching for a NodeJS library to construct Excel (xlsx), with cell format (color, font size, images...). Importantly, it must has the capability of exporting the resulted .xlsx file to .pdf format.

I know some libs that call Excel API but I'm running a linux server and that's impossible for me.

答:
Thanks to jcaron comment I finally found out that I can build a PDF file directly without passing through xls.
I used pdfmaker for nodejs that support creating PDF file pretty well.</p>

ContentLicense: CC BY-SA 4.0


问:
Is it possible to define array as constant in with Symfony Framework?
Constants are defined in YAML format in the config/app.yaml file. However, when I try to define an array as

const_arr: ['one', 'two', 'three', 'four', 'five']

and use sfConfig::get('app_const_arr'), I don't getting anything back. What am I doing wrong?

答:
Try:</p>

```<code>app:
   my_array:
       values: [foo, bar]

sfConfig::get('app_my_array_values');
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Try:

app:
   my_array:
       values: [foo, bar]

sfConfig::get('app_my_array_values');


问:
Magento 1.9 - Multi Store Product URL Issue
I had Magento 1.9 website which runs with default store only.

Now I have created 1 more store for USA customers with currency $.

Now issue is why every product have 2 urls, different URL for both stores. There is an issue and duplicate content issue with SEO, So I want only 1 URL for both stores.

Ex:

Product: XYZ

Store India URL: xyz.html with price in INR

Store USA URL: xyz.html with price in $

I have used one extension which redirect me on specific store based on user IP.

Thank you.

答:
If you want only currency changed than used Magento currency converter in top template file.

Disable store and used only single store.

Thanks


问:
Issue in copying rows based on certain conditions in Vba
```<code>Set ws4 = Workbooks("A.xlsx").Worksheets(1)
Lastrowto = ws4.Cells(Rows.Count, "B").End(xlUp).Row

For y = Lastrowto To 1 Step -1
    If ws4.Cells(y, "B").Value = "Not found" Then
        ws4.Rows(y).EntireRow.Copy
    End If
Next y
</code>```

The above piece of vba code copies only 1 (the first one) row but I want to copy all those rows for which the given condition is met, kindly suggest me the correct version of code.

答:
Instead of using Copy>>Paste one row at a time, which will take a long time to process, you can use a Range object named CopyRng.

Every time the criteria is met (If .Range("B" & y).Value = "Not found"), it will add the current row to CopyRng.

After finishing looping through all your rows, you can just copy the entire rows at once using CopyRng.Copy.

Code

```<code>Option Explicit

Sub CopyMultipleRows()

Dim ws4 As Worksheet
Dim Lastrowto As Long, y As Long
Dim CopyRng As Range

Set ws4 = Workbooks("A.xlsx").Worksheets(1)

With ws4
    Lastrowto = .Cells(.Rows.Count, "B").End(xlUp).Row

    For y = Lastrowto To 1 Step -1

        If .Range("B" & y).Value = "Not found" Then
            If Not CopyRng Is Nothing Then
                Set CopyRng = Application.Union(CopyRng, .Rows(y))
            Else
                Set CopyRng = .Rows(y)
            End If
        End If

    Next y
End With

' copy the entire rows of the Merged Range at once
If Not CopyRng is Nothing Then CopyRng.Copy

End Sub
</code>```

Body:
Set ws4 = Workbooks("A.xlsx").Worksheets(1)
Lastrowto = ws4.Cells(Rows.Count, "B").End(xlUp).Row

For y = Lastrowto To 1 Step -1
    If ws4.Cells(y, "B").Value = "Not found" Then
        ws4.Rows(y).EntireRow.Copy
    End If
Next y

The above piece of vba code copies only 1 (the first one) row but I want to copy all those rows for which the given condition is met, kindly suggest me the correct version of code.

Body:
Instead of using Copy>>Paste one row at a time, which will take a long time to process, you can use a Range object named CopyRng.

Every time the criteria is met (If .Range("B" & y).Value = "Not found"), it will add the current row to CopyRng.

After finishing looping through all your rows, you can just copy the entire rows at once using CopyRng.Copy.

Code

Option Explicit

Sub CopyMultipleRows()

Dim ws4 As Worksheet
Dim Lastrowto As Long, y As Long
Dim CopyRng As Range

Set ws4 = Workbooks("A.xlsx").Worksheets(1)

With ws4
    Lastrowto = .Cells(.Rows.Count, "B").End(xlUp).Row

    For y = Lastrowto To 1 Step -1

        If .Range("B" & y).Value = "Not found" Then
            If Not CopyRng Is Nothing Then
                Set CopyRng = Application.Union(CopyRng, .Rows(y))
            Else
                Set CopyRng = .Rows(y)
            End If
        End If

    Next y
End With

' copy the entire rows of the Merged Range at once
If Not CopyRng is Nothing Then CopyRng.Copy

End Sub


问:
Remove array from multidimentional array using id in php
I want to remove array from multidimentional array using base of ID. I tried using foreach loop. But, It is not working.

Any one help me how to remove this?

Thanks.

=> Array :

```<code>Array
(
    [0] => Array
        (
            [id] => 11109
            [value] => Yes
            [field_id] => 234
        )

    [1] => Array
        (
            [id] => 11109
            [value] => Yes
            [field_id] => 237
        )

    [2] => Array
        (
            [id] => 11110
            [value] => No
            [field_id] => 234
        )

    [3] => Array
        (
            [id] => 11110
            [value] => No
            [field_id] => 237
        )

    [4] => Array
        (
            [id] => 11111
            [value] => No
            [field_id] => 237
        )

)
</code>```

From this array, I want to remove array which

field_id is 234 and value is "No" && field_id is 237 and value is
"No".

field_id is 234 and value is "Yes" && field_id is 237 and value is

"Yes".

So, From this array only ID 11111 array is display otherwise all array remove from current array.

Here is my code using I tried to remove array.

```<code>foreach ($collection->getData() as $key => $value) {
                        if(($value['field_id'] == $ids[0] && $value['value'] == "No")){
                            echo $value['id'];
                            // exit;
                            break;
                        }
                        echo $value['field_id'];
                        echo $value['value'];
                        if(($value['field_id'] == $ids[1] && $value['value'] == "No")){
                            print_r($collection->getData()[$key]);
                            unset($collection->getData()[$key]);
                            unset($collection->getData()[$key-1]);
                        }
                    }
</code>```

答:
You can create a new Multidimensional array , and copy only the values you want to it .

also , when you use break , you get out of the foreach loop completely , i don't think this is the intended behavior , use continue to skip current iteration and test the next element

Body:
I want to remove array from multidimentional array using base of ID. I tried using foreach loop. But, It is not working.

Any one help me how to remove this?

Thanks.

=> Array :

Array
(
    [0] => Array
        (
            [id] => 11109
            [value] => Yes
            [field_id] => 234
        )

    [1] => Array
        (
            [id] => 11109
            [value] => Yes
            [field_id] => 237
        )

    [2] => Array
        (
            [id] => 11110
            [value] => No
            [field_id] => 234
        )

    [3] => Array
        (
            [id] => 11110
            [value] => No
            [field_id] => 237
        )

    [4] => Array
        (
            [id] => 11111
            [value] => No
            [field_id] => 237
        )

)

From this array, I want to remove array which

field_id is 234 and value is "No" && field_id is 237 and value is
"No".

field_id is 234 and value is "Yes" && field_id is 237 and value is

"Yes".

So, From this array only ID 11111 array is display otherwise all array remove from current array.

Here is my code using I tried to remove array.

foreach ($collection->getData() as $key => $value) {
                        if(($value['field_id'] == $ids[0] && $value['value'] == "No")){
                            echo $value['id'];
                            // exit;
                            break;
                        }
                        echo $value['field_id'];
                        echo $value['value'];
                        if(($value['field_id'] == $ids[1] && $value['value'] == "No")){
                            print_r($collection->getData()[$key]);
                            unset($collection->getData()[$key]);
                            unset($collection->getData()[$key-1]);
                        }
                    }


问:
Is it OK to force the user to start a subscription + trial?
By Apple's rules, is it considered OK to force a subscription + trial when the user first uses an app?</p>

答:
Yes, this is ok. Your mileage may vary with the particular reviewer you get but in general Apple is very liberal with what content you choose to put behind a paywall. After all, you could charge users to even install your app if it were a paid application.

Apple does list some additional do's and don't's on the IAP section  of the app review guidelines. These are worth reading over, especially if you are considering using renewable subscriptions.


问:
How to pass value to module from controller in angularjs

Module:

```<code>(function () {
    "use strict";
    angular.module("myModule", []);
})();

(function (module) {
    "use strict";
    module.config(['$httpProvider', function ($httpProvider) {
 }]);

})(angular.module("myModule"));
</code>```

Controller:

```<code>myModule.controller("MyController", function($scope) {
      $scope.testvalue = "testvalue";
}
</code>```

Now I want $scope.testvalue inside module.config,

```<code>(function (module) {
    "use strict";
    module.config(['$httpProvider', function ($httpProvider) {
        var controllerdata = $scope.testvalue;
 }]);
</code>```

How can I do this? how to pass value from controller to module.config (both are in same module scope)

答:
Not every variable has the privilege to appear in the config blocks. In your case, you cannot access the scope variable in your module's config block.

But there are alternatives:

Use a constant: Constants are available in config blocks, and are useful for static values that don't change.

Use a provider: If you need a custom configurable service available in your app, you can create an angular provider to make it customizable in the config blocks.

Body:
Module:

(function () {
    "use strict";
    angular.module("myModule", []);
})();

(function (module) {
    "use strict";
    module.config(['$httpProvider', function ($httpProvider) {
 }]);

})(angular.module("myModule"));

Controller:

myModule.controller("MyController", function($scope) {
      $scope.testvalue = "testvalue";
}

Now I want $scope.testvalue inside module.config,

(function (module) {
    "use strict";
    module.config(['$httpProvider', function ($httpProvider) {
        var controllerdata = $scope.testvalue;
 }]);

How can I do this? how to pass value from controller to module.config (both are in same module scope)


问:
Pandas: Convert a DataFrame into a Series when index is Year-Month and columns are Day
I have a dataframe that looks similar to the following:

```<code>df = pd.DataFrame({'Y_M':['201710','201711','201712'],'1':[1,5,9],'2':[2,6,10],'3':[3,7,11],'4':[4,8,12]})
df = df.set_index('Y_M')
</code>```

Which creates a dataframe looking like this:

```<code>        1  2  3   4
Y_M
201711  1  2  3  4
201712  5  6  7  8
201713  9  10 11 12
</code>```

The columns are the day of the month. They stretch on to the right, going all the way up to 31.  (February will have columns 29, 30, and 31 filled with NaN).
The index contains the year and the month (e.g. 201711 referring to Nov 2017)

My question is: How can I make this a single series, with the year/month/day combined? My output would be the following:

```<code>Y_M
20171001    1
20171002    2
20171003    3
20171004    4
20171101    5
20171102    6
20171103    7
20171104    8
20171201    9
20171202   10
20171203   11
20171204   12
</code>```

The index can be converted to a datetime. In fact I think it would make it easier.

Body:
I have a dataframe that looks similar to the following:

df = pd.DataFrame({'Y_M':['201710','201711','201712'],'1':[1,5,9],'2':[2,6,10],'3':[3,7,11],'4':[4,8,12]})
df = df.set_index('Y_M')

Which creates a dataframe looking like this:

        1  2  3   4
Y_M
201711  1  2  3  4
201712  5  6  7  8
201713  9  10 11 12

The columns are the day of the month. They stretch on to the right, going all the way up to 31.  (February will have columns 29, 30, and 31 filled with NaN).
The index contains the year and the month (e.g. 201711 referring to Nov 2017)

My question is: How can I make this a single series, with the year/month/day combined? My output would be the following:

Y_M
20171001    1
20171002    2
20171003    3
20171004    4
20171101    5
20171102    6
20171103    7
20171104    8
20171201    9
20171202   10
20171203   11
20171204   12

The index can be converted to a datetime. In fact I think it would make it easier.

Body:
Use stack for Series and then combine datetimes by to_datetime with timedeltas by
to_timedelta:

df = df.stack()
df.index = pd.to_datetime(df.index.get_level_values(0), format='%Y%m') + \
           pd.to_timedelta(df.index.get_level_values(1).astype(int) - 1, unit='D')
print (df)
2017-10-01     1
2017-10-02     2
2017-10-03     3
2017-10-04     4
2017-11-01     5
2017-11-02     6
2017-11-03     7
2017-11-04     8
2017-12-01     9
2017-12-02    10
2017-12-03    11
2017-12-04    12
dtype: int64

print (df.index)
DatetimeIndex(['2017-10-01', '2017-10-02', '2017-10-03', '2017-10-04',
               '2017-11-01', '2017-11-02', '2017-11-03', '2017-11-04',
               '2017-12-01', '2017-12-02', '2017-12-03', '2017-12-04'],
              dtype='datetime64[ns]', freq=None)

Last if necessary strings in index (not DatetimeIndex) add DatetimeIndex.strftime:

df.index = df.index.strftime('%Y%m%d')
print (df)
20171001     1
20171002     2
20171003     3
20171004     4
20171101     5
20171102     6
20171103     7
20171104     8
20171201     9
20171202    10
20171203    11
20171204    12
dtype: int64

print (df.index)
Index(['20171001', '20171002', '20171003', '20171004', '20171101', '20171102',
       '20171103', '20171104', '20171201', '20171202', '20171203', '20171204'],
      dtype='object')


问:
two questions on Java multiple threads use notify() method
the code:

```<code>public class NotifyAndWaitTest2 implements Runnable {
    public int i = 0;
    public Object lock;
    public SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");

    public NotifyAndWaitTest2(Object o) {
        this.lock = o;
    }

    @Override
    public void run() {
        synchronized (lock) {
            System.out.println(Thread.currentThread().getName() + " enter the SYNCHRONIZED block --- "+ sdf.format(new Date()));
            try {
                while (i < 9) {
                    Thread.sleep(500);
                    lock.notify();
                    lock.wait();
                    System.out.println(Thread.currentThread().getName() + " say：" + i++ + " --- " + sdf.format(new Date()));
                }
                lock.notify();
                return;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Object lock = new Object();
        NotifyAndWaitTest2 test = new NotifyAndWaitTest2(lock);
        Thread t1 = new Thread(test,"Thread A");
        Thread t2 = new Thread(test,"Thread B");
        Thread t3 = new Thread(test,"Thread C");
        Thread t4 = new Thread(test,"Thread D");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}
</code>```

the result:

```<code>Thread A enter the SYNCHRONIZED block --- 10:47:07.242
Thread B enter the SYNCHRONIZED block --- 10:47:07.743
Thread C enter the SYNCHRONIZED block --- 10:47:08.243
Thread D enter the SYNCHRONIZED block --- 10:47:08.743
Thread C say：0 --- 10:47:09.243
Thread D say：1 --- 10:47:09.744
Thread C say：2 --- 10:47:10.244
Thread D say：3 --- 10:47:10.744
Thread C say：4 --- 10:47:11.245
Thread D say：5 --- 10:47:11.745
Thread C say：6 --- 10:47:12.246
Thread D say：7 --- 10:47:12.746
Thread C say：8 --- 10:47:13.247
Thread D say：9 --- 10:47:13.247
Thread B say：10 --- 10:47:13.247
Thread A say：11 --- 10:47:13.247
</code>```

The code executes the same result in both jdk1.7 and jdk1.8.

my problem:

After thread A and thread B enter SYNCHRONIZED block and call the wait() method, why is thread C and thread D entering instead of thread A say i and then thread B say i? Is the priority of entering the sync block higher than the thread that just called wait() method?

Why called notify() method just wake up the lastest thread that called wait() method? just like the thread C and thread D, notify each other and wait for each other, why not any other waiting thread? like thread A and thread B.

I think it should be random, like

```<code>Thread A enter the SYNCHRONIZED block
Thread B enter the SYNCHRONIZED block
Thread A say：0
Thread C enter the SYNCHRONIZED block
Thread B say：1
Thread A say：2
Thread D enter the SYNCHRONIZED block
Thread B say：3
Thread C say：4
</code>```

答:
Question 1:

After thread A and thread B enter SYNCHRONIZED block and call the
  wait() method, why is thread C and thread D entering instead of thread
  A say i and then thread B say i? Is the priority of entering the sync
  block higher than the thread that just called wait() method?

Here is what Javadoc says about wait/notify:

The awakened thread will not be able to proceed until the current
  thread relinquishes the lock on this object. The awakened thread will
  compete in the usual manner with any other threads that might be
  actively competing to synchronize on this object; for example, the
  awakened thread enjoys no reliable privilege or disadvantage in being
  the next thread to lock this object.

What this means is that Thread A will not be guaranteed to proceed when Thread B calls notify and Thread A will need to compete with Thread C and D that are waiting at the start of synchronization block. The implementation just gives priority to Thread C and D in your case. That's why you see this output:

```<code>Thread A enter the SYNCHRONIZED block --- 10:47:07.242
Thread B enter the SYNCHRONIZED block --- 10:47:07.743
Thread C enter the SYNCHRONIZED block --- 10:47:08.243
Thread D enter the SYNCHRONIZED block --- 10:47:08.743
</code>```

Question 2:

Why called notify() method just wake up the lastest thread that called
  wait() method? just like the thread C and thread D, notify each other
  and wait for each other, why not any other waiting thread? like thread
  A and thread B.

Again the Java spec does not guarantee the priority. It just happens that the call to notify from Thread D wakes up Thread C (which is waiting for lock, along with Thread A and B) and call from Thread C after it prints "say" statement and sleeps for 500ms wakes up Thread D (which is again waiting for lock, along with Thread A and B) until they exit while loop and synchronization block and thus releasing the lock first to Thread B and then to thread A.

Sample output from my run:

```<code>Thread A enter the SYNCHRONIZED block --- 09:35:59.836
Thread D enter the SYNCHRONIZED block --- 09:36:00.336
Thread C enter the SYNCHRONIZED block --- 09:36:00.836
Thread B enter the SYNCHRONIZED block --- 09:36:01.336
Thread C say：0 --- 09:36:01.836
Thread B say：1 --- 09:36:02.337
Thread C say：2 --- 09:36:02.837
Thread B say：3 --- 09:36:03.337
Thread C say：4 --- 09:36:03.837
Thread B say：5 --- 09:36:04.337
Thread C say：6 --- 09:36:04.837
Thread B say：7 --- 09:36:05.337
Thread C say：8 --- 09:36:05.837
Thread B say：9 --- 09:36:05.837
Thread D say：10 --- 09:36:05.837
Thread A say：11 --- 09:36:05.838
</code>```

Body:
the code:

public class NotifyAndWaitTest2 implements Runnable {
    public int i = 0;
    public Object lock;
    public SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");

    public NotifyAndWaitTest2(Object o) {
        this.lock = o;
    }

    @Override
    public void run() {
        synchronized (lock) {
            System.out.println(Thread.currentThread().getName() + " enter the SYNCHRONIZED block --- "+ sdf.format(new Date()));
            try {
                while (i < 9) {
                    Thread.sleep(500);
                    lock.notify();
                    lock.wait();
                    System.out.println(Thread.currentThread().getName() + " say：" + i++ + " --- " + sdf.format(new Date()));
                }
                lock.notify();
                return;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Object lock = new Object();
        NotifyAndWaitTest2 test = new NotifyAndWaitTest2(lock);
        Thread t1 = new Thread(test,"Thread A");
        Thread t2 = new Thread(test,"Thread B");
        Thread t3 = new Thread(test,"Thread C");
        Thread t4 = new Thread(test,"Thread D");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

the result:

Thread A enter the SYNCHRONIZED block --- 10:47:07.242
Thread B enter the SYNCHRONIZED block --- 10:47:07.743
Thread C enter the SYNCHRONIZED block --- 10:47:08.243
Thread D enter the SYNCHRONIZED block --- 10:47:08.743
Thread C say：0 --- 10:47:09.243
Thread D say：1 --- 10:47:09.744
Thread C say：2 --- 10:47:10.244
Thread D say：3 --- 10:47:10.744
Thread C say：4 --- 10:47:11.245
Thread D say：5 --- 10:47:11.745
Thread C say：6 --- 10:47:12.246
Thread D say：7 --- 10:47:12.746
Thread C say：8 --- 10:47:13.247
Thread D say：9 --- 10:47:13.247
Thread B say：10 --- 10:47:13.247
Thread A say：11 --- 10:47:13.247

The code executes the same result in both jdk1.7 and jdk1.8.

my problem:

After thread A and thread B enter SYNCHRONIZED block and call the wait() method, why is thread C and thread D entering instead of thread A say i and then thread B say i? Is the priority of entering the sync block higher than the thread that just called wait() method?

Why called notify() method just wake up the lastest thread that called wait() method? just like the thread C and thread D, notify each other and wait for each other, why not any other waiting thread? like thread A and thread B.

I think it should be random, like

Thread A enter the SYNCHRONIZED block
Thread B enter the SYNCHRONIZED block
Thread A say：0
Thread C enter the SYNCHRONIZED block
Thread B say：1
Thread A say：2
Thread D enter the SYNCHRONIZED block
Thread B say：3
Thread C say：4

Body:
Question 1:

After thread A and thread B enter SYNCHRONIZED block and call the
  wait() method, why is thread C and thread D entering instead of thread
  A say i and then thread B say i? Is the priority of entering the sync
  block higher than the thread that just called wait() method?

Here is what Javadoc says about wait/notify:

The awakened thread will not be able to proceed until the current
  thread relinquishes the lock on this object. The awakened thread will
  compete in the usual manner with any other threads that might be
  actively competing to synchronize on this object; for example, the
  awakened thread enjoys no reliable privilege or disadvantage in being
  the next thread to lock this object.

What this means is that Thread A will not be guaranteed to proceed when Thread B calls notify and Thread A will need to compete with Thread C and D that are waiting at the start of synchronization block. The implementation just gives priority to Thread C and D in your case. That's why you see this output:

Thread A enter the SYNCHRONIZED block --- 10:47:07.242
Thread B enter the SYNCHRONIZED block --- 10:47:07.743
Thread C enter the SYNCHRONIZED block --- 10:47:08.243
Thread D enter the SYNCHRONIZED block --- 10:47:08.743

Question 2:

Why called notify() method just wake up the lastest thread that called
  wait() method? just like the thread C and thread D, notify each other
  and wait for each other, why not any other waiting thread? like thread
  A and thread B.

Again the Java spec does not guarantee the priority. It just happens that the call to notify from Thread D wakes up Thread C (which is waiting for lock, along with Thread A and B) and call from Thread C after it prints "say" statement and sleeps for 500ms wakes up Thread D (which is again waiting for lock, along with Thread A and B) until they exit while loop and synchronization block and thus releasing the lock first to Thread B and then to thread A.

Sample output from my run:

Thread A enter the SYNCHRONIZED block --- 09:35:59.836
Thread D enter the SYNCHRONIZED block --- 09:36:00.336
Thread C enter the SYNCHRONIZED block --- 09:36:00.836
Thread B enter the SYNCHRONIZED block --- 09:36:01.336
Thread C say：0 --- 09:36:01.836
Thread B say：1 --- 09:36:02.337
Thread C say：2 --- 09:36:02.837
Thread B say：3 --- 09:36:03.337
Thread C say：4 --- 09:36:03.837
Thread B say：5 --- 09:36:04.337
Thread C say：6 --- 09:36:04.837
Thread B say：7 --- 09:36:05.337
Thread C say：8 --- 09:36:05.837
Thread B say：9 --- 09:36:05.837
Thread D say：10 --- 09:36:05.837
Thread A say：11 --- 09:36:05.838


问:
Send html file as email body content using android intent
I have an ecommerce app that shares the product as html document. Using this code I can send the product.html as attachment. I want to send the html document as the body of email instead of attachment.

Here is my code :

```<code>private void sendEmail(Context context, String emailTo, String emailCC,
                       String subject, String emailText, List<String> filePaths) {

    final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
    emailIntent.setType(TEXT_HTML);
    emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{emailTo});
    emailIntent.putExtra(android.content.Intent.EXTRA_CC, new String[]{emailCC});
    emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);

    ArrayList<Uri> fileUris = new ArrayList<Uri>();
    for (String file : filePaths) {
        File fileIn = new File(file);
        Uri uri = Uri.fromFile(fileIn);
        fileUris.add(uri);
    }

    emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, fileUris);
    context.startActivity(Intent.createChooser(emailIntent, context.getString(R.string.send_by_email))); }
</code>```

答:
Anything that needs to go into the body can be set into your intent this way e.g. puts your builds version name as the body of the email. You can replace that with your html content. Have never tried that personally, You might need some conversion.</p>

```<code>emailIntent.putExtra(Intent.EXTRA_TEXT, BuildConfig.VERSION_NAME);
</code>```

Body:
I have an ecommerce app that shares the product as html document. Using this code I can send the product.html as attachment. I want to send the html document as the body of email instead of attachment.

Here is my code :

private void sendEmail(Context context, String emailTo, String emailCC,
                       String subject, String emailText, List<String> filePaths) {

    final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
    emailIntent.setType(TEXT_HTML);
    emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{emailTo});
    emailIntent.putExtra(android.content.Intent.EXTRA_CC, new String[]{emailCC});
    emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);

    ArrayList<Uri> fileUris = new ArrayList<Uri>();
    for (String file : filePaths) {
        File fileIn = new File(file);
        Uri uri = Uri.fromFile(fileIn);
        fileUris.add(uri);
    }

    emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, fileUris);
    context.startActivity(Intent.createChooser(emailIntent, context.getString(R.string.send_by_email))); }

Body:
Anything that needs to go into the body can be set into your intent this way e.g. puts your builds version name as the body of the email. You can replace that with your html content. Have never tried that personally, You might need some conversion.

emailIntent.putExtra(Intent.EXTRA_TEXT, BuildConfig.VERSION_NAME);


问:
Why is Android Studio reporting "URI is not registered"?
So I've given Android Studio a try, because I really like Resharper and noticed that the IDE had some of their functionality built into it. Having now created a default new project, I added a new layout file and wanted to change the existing default 'hello world' example layout, and I got an "URI is not registered" error on the following lines:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
```

I've done nothing else to the default generated project yet. I've come across another question that seems to be related (Intellij Android project schema URI not registered?), but just ignoring something feels odd to me. I actually tried it, but that causes RelativeLayout (and probably all other Android related stuff) to be not recognised any more (error message: "Cannot find the declaration of element 'RelativeLayout'").

Any ideas on how to solve this problem?

答:
For me Plugin Android Support get Disabled somehow. Enabling Plugins again worked for me.

```<code>Settings > Plugins > Android Support
</code>```

Body:
So I've given Android Studio a try, because I really like Resharper and noticed that the IDE had some of their functionality built into it. Having now created a default new project, I added a new layout file and wanted to change the existing default 'hello world' example layout, and I got an "URI is not registered" error on the following lines:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"

I've done nothing else to the default generated project yet. I've come across another question that seems to be related (Intellij Android project schema URI not registered?), but just ignoring something feels odd to me. I actually tried it, but that causes RelativeLayout (and probably all other Android related stuff) to be not recognised any more (error message: "Cannot find the declaration of element 'RelativeLayout'").

Any ideas on how to solve this problem?

Body:
For me Plugin Android Support get Disabled somehow. Enabling Plugins again worked for me.

Settings > Plugins > Android Support


问:
Is this a bug? : I get " The type ... is not a complex type or an entity type" in my WCF data service using the Reflection provider
When invoking a query on the data service I get this error message inside the XML feed:

```<code>  <m:error>
    <m:code></m:code>
    <m:message xml:lang="nl-NL">Internal Server Error. The type 'MyType' is not a complex type or an entity type.</m:message>
  </m:error>
</code>```

When I use the example described here in the article "How to: Create a Data Service Using the Reflection Provider (WCF Data Services)" http://msdn.microsoft.com/en-us/library/dd728281(v=VS.100).aspx it works as expected.

I have created the service in a .NET 4.0 web project. My data context class returns
a query object that is derived from the LINQExtender (http://linqextender.codeplex.com/). When I execute the query object in a unit test, it works as expected.

My entity type is defined as:

```<code>[DataServiceKey("Id")]
public class Accommodation
{
    [UniqueIdentifier]
    [OriginalFieldName("EntityId")]
    public string Id { get; set; }

    [OriginalFieldName("AccoName")]
    public string Name { get; set; }
}
</code>```

(the UniqueIdentifier and OriginalFieldName attributes are used by LINQExtender)

Does anybody know if this is a bug in WCF data services or am I doing something wrong?

答:
There is a solution for this:

http://www.sellsbrothers.com/posts/details/12665

Body:
When invoking a query on the data service I get this error message inside the XML feed:

  <m:error>
    <m:code></m:code>
    <m:message xml:lang="nl-NL">Internal Server Error. The type 'MyType' is not a complex type or an entity type.</m:message>
  </m:error>

When I use the example described here in the article "How to: Create a Data Service Using the Reflection Provider (WCF Data Services)" http://msdn.microsoft.com/en-us/library/dd728281(v=VS.100).aspx it works as expected.

I have created the service in a .NET 4.0 web project. My data context class returns
a query object that is derived from the LINQExtender (http://linqextender.codeplex.com/). When I execute the query object in a unit test, it works as expected.

My entity type is defined as:

[DataServiceKey("Id")]
public class Accommodation
{
    [UniqueIdentifier]
    [OriginalFieldName("EntityId")]
    public string Id { get; set; }

    [OriginalFieldName("AccoName")]
    public string Name { get; set; }
}

(the UniqueIdentifier and OriginalFieldName attributes are used by LINQExtender)

Does anybody know if this is a bug in WCF data services or am I doing something wrong?


问:
How to Load WebView in Fragment class? How to load Webview in android?
I am trying to create a WebView in a Fragment which should be loaded. I added it already to my xml File. However, the findViewById method only works if I extend an Activity class. Is there anyway of which I can use it in Fragment as well?

I already tested the Solution from another Question, but it doesn't work.

```<code>public class OneFragment extends Fragment{

public WebView PlanWebView;

public OneFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    PlanWebView WebView = (PlanWebView) getView().findViewById(R.id.PlanWebView);
    // Unknown class: "PlanWebView";
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_one, container, false);
}

}
</code>```

答:
You should use  code below in onCreateView method:

```<code>View view = inflater.inflate(layout,container,false);

WebView webview = (WebView) view.findViewById(R.id.webView);

return view;
</code>```

Body:
I am trying to create a WebView in a Fragment which should be loaded. I added it already to my xml File. However, the findViewById method only works if I extend an Activity class. Is there anyway of which I can use it in Fragment as well?

I already tested the Solution from another Question, but it doesn't work.

public class OneFragment extends Fragment{

public WebView PlanWebView;

public OneFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    PlanWebView WebView = (PlanWebView) getView().findViewById(R.id.PlanWebView);
    // Unknown class: "PlanWebView";
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_one, container, false);
}

}

Body:
You should use  code below in onCreateView method:

View view = inflater.inflate(layout,container,false);

WebView webview = (WebView) view.findViewById(R.id.webView);

return view;


问:
better end on keypress
I am writing a console app and found this method to end a loop on a keypress:

while (!Console.KeyAvailable){//do stuff}

It works, but it echos the key that was pressed back to the prompt.  Is there a better method?

edit:

To clarify more, the loop runs and if hit the letter j the loop ends and the program exits.  However, I get the following output at the prompt:

C:\>j

答:
If you want to exit from a loop after a particular key is pressed, then instead of Console.KeyAvailable you can use the Console.ReadKey() function and check the return type of this function as an exit condition.

Here is the implementation.

while (true) {
    var keyPressed = Console.ReadKey(true);
    if (keyPressed.KeyChar == 'j') break;
    //do something
    Console.WriteLine("Key pressed: " + keyPressed.KeyChar);
}
```

For more details: C# Console - hide the input from console window while typing

Title: better end on keypress

Body:
If you want to exit from a loop after a particular key is pressed, then instead of Console.KeyAvailable you can use the Console.ReadKey() function and check the return type of this function as an exit condition.

Here is the implementation.

while (true) {
    var keyPressed = Console.ReadKey(true);
    if (keyPressed.KeyChar == 'j') break;
    //do something
    Console.WriteLine("Key pressed: " + keyPressed.KeyChar);
}

For more details: C# Console - hide the input from console window while typing


问:
How to reference subquery in the WHERE clause
I have a SQL query (T-SQL) in which I have a subquery in the SELECT statement.

Here is a reduced version:

```<code>SELECT
    p.id AS id,
    (SELECT
        jobs_without_price.id
    FROM
        st_job jobs_without_price
    WHERE
        jobs_without_price.person_id = p.id
    AND
        jobs_without_price.price IS NULL
    FOR XML AUTO, ROOT('jobs')) AS JobsWithoutPrice
FROM
    st_person p
WHERE
    JobsWithoutPrice IS NOT NULL
GROUP BY
    p.id
</code>```

The problem is that SSMS tells me

Invalid column name 'JobsWithoutPrice'.

This is almost certainly because SQL doesn't allow aliases in WHERE clauses, but how else can I use the result of this subquery to filter the results?

[The full query has more table joins and much more in the SELECT statement, all of which pertains to a single person record, whereas the subquery reports back multiple records, which is why it's in a subquery.]

答:
You should be able to to that by simply moving the sub-query in CROSS APPLY operator. Something like this:

```<code>SELECT
    p.id AS id
   ,newXML
FROM
    st_person p
CROSS APPLY
(
    SELECT
        jobs_without_price.id AS JobsWithoutPrice
    FROM
        st_job jobs_without_price
    WHERE
        jobs_without_price.person_id = p.id
    AND
        jobs_without_price.price IS NULL
    FOR XML AUTO, ROOT('jobs')
) AS DS (newXML)
--WHERE
--    newXML IS NOT NULL
GROUP BY
    p.id;
</code>```

Note, that I have commented the last WHERE clause. We should in need of it, as CROSS APPLY will return the rows from the left part who a match of a row(s) in the right part (like INNER JOIN). You can try OUTER APPLY for getting all rows from the left part of the operator (like LEFT JOIN).

You are allowed to use the columns returned by the APPLY operator in every clause (SELECT, JOIN, WHERE, ORDER BY, HAVING, GROUP BY).

Body:
I have a SQL query (T-SQL) in which I have a subquery in the SELECT statement.

Here is a reduced version:

SELECT
    p.id AS id,
    (SELECT
        jobs_without_price.id
    FROM
        st_job jobs_without_price
    WHERE
        jobs_without_price.person_id = p.id
    AND
        jobs_without_price.price IS NULL
    FOR XML AUTO, ROOT('jobs')) AS JobsWithoutPrice
FROM
    st_person p
WHERE
    JobsWithoutPrice IS NOT NULL
GROUP BY
    p.id

The problem is that SSMS tells me

Invalid column name 'JobsWithoutPrice'.

This is almost certainly because SQL doesn't allow aliases in WHERE clauses, but how else can I use the result of this subquery to filter the results?

[The full query has more table joins and much more in the SELECT statement, all of which pertains to a single person record, whereas the subquery reports back multiple records, which is why it's in a subquery.]

Body:
You should be able to to that by simply moving the sub-query in CROSS APPLY operator. Something like this:

SELECT
    p.id AS id
   ,newXML
FROM
    st_person p
CROSS APPLY
(
    SELECT
        jobs_without_price.id AS JobsWithoutPrice
    FROM
        st_job jobs_without_price
    WHERE
        jobs_without_price.person_id = p.id
    AND
        jobs_without_price.price IS NULL
    FOR XML AUTO, ROOT('jobs')
) AS DS (newXML)
--WHERE
--    newXML IS NOT NULL
GROUP BY
    p.id;

Note, that I have commented the last WHERE clause. We should in need of it, as CROSS APPLY will return the rows from the left part who a match of a row(s) in the right part (like INNER JOIN). You can try OUTER APPLY for getting all rows from the left part of the operator (like LEFT JOIN).

You are allowed to use the columns returned by the APPLY operator in every clause (SELECT, JOIN, WHERE, ORDER BY, HAVING, GROUP BY).


问:
how to scrape data using dt tags
I am scraping data from a url, mostly I have experienced ul li and so on.

This time I have found dl tags, and when I use scrape_between function it doesn't show me anything my code is :

```<code><div id='gallery-1' class='gallery galleryid-273 gallery-columns-2 gallery-size-full'><dl class='gallery-item'>
        <dt class='gallery-icon portrait'>
            <a href='https://example.com/wp-content/uploads/2013/11/gf-1.jpg?fit=650%2C976' data-rel="lightbox-gallery-1"><img  width="650" height="976"  src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="https://example.com/wp-content/uploads/2013/11/gf-1.jpg?fit=650%2C976"  class="attachment-full size-full" alt="" aria-describedby="gallery-1-16311" data-srcset="https://example.com/wp-content/uploads/2013/11/gf-1.jpg?w=650 650w, https://example.com/wp-content/uploads/2013/11/gf-1.jpg?resize=200%2C300 200w" data-sizes="(max-width: 650px) 100vw, 650px" /></a>
        </dt>
            <dd class='wp-caption-text gallery-caption' id='gallery-1-16311'>
            Ground Floor Plan
            </dd></dl><dl class='gallery-item'>
        <dt class='gallery-icon portrait'>
            <a href='https://example.com/wp-content/uploads/2013/11/ff.jpg?fit=649%2C1024' data-rel="lightbox-gallery-1"><img  width="649" height="1024"  src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="https://example.com/wp-content/uploads/2013/11/ff.jpg?fit=649%2C1024"  class="attachment-full size-full" alt="" aria-describedby="gallery-1-16312" data-srcset="https://example.com/wp-content/uploads/2013/11/ff.jpg?w=649 649w, https://example.com/wp-content/uploads/2013/11/ff.jpg?resize=190%2C300 190w" data-sizes="(max-width: 649px) 100vw, 649px" /></a>
        </dt>
            <dd class='wp-caption-text gallery-caption' id='gallery-1-16312'>
            First Floor pLan
            </dd></dl><br style="clear: both" />
    </div>
</code>```

Can anybody help me out ?

scrap_between function is

```<code>function scrape_between($data, $start, $end){
    $data = stristr($data, $start);
    $data = substr($data, strlen($start));
    $stop = stripos($data, $end);
    $data = substr($data, 0, $stop);
    return $data;
}
</code>```

I need to scrape images that are place in dt tags

I am trying this code

```<code>$project_images = scrape_between($data, '<dl class="gallery-item', '<br style="clear: both">');
</code>```

Please suggest

答:
Finally I got the solution myself I didn't find any answer of my question here so I decided to answer this to help others

I solved the problem to get dl images using this code

```<code>$data = 'your html content';

        if (preg_match("/<div id='gallery-1' class='gallery galleryid-273 gallery-columns-2 gallery-size-full'><dl class='gallery-item'>/",$data)){
            $data0 = explode("<dl class='gallery-item'>",$data);
            $proj_img = array();
            foreach($data0 as $key=> $imgArray)
            {
                $proj_img[$key] = scrape_between($imgArray, 'data-srcset="', '?w');
            }
            $proj_img = array_filter($proj_img);
            echo "```"; print_r($proj_img);
        }
```

Title: how to scrape data using dt tags

Body:
I am scraping data from a url, mostly I have experienced ul li and so on.

This time I have found dl tags, and when I use scrape_between function it doesn't show me anything my code is :

            Ground Floor Plan

            First Floor pLan

Can anybody help me out ?

scrap_between function is

function scrape_between($data, $start, $end){
    $data = stristr($data, $start);
    $data = substr($data, strlen($start));
    $stop = stripos($data, $end);
    $data = substr($data, 0, $stop);
    return $data;
}

I need to scrape images that are place in dt tags

I am trying this code

$project_images = scrape_between($data, '<dl class="gallery-item', '
');

Please suggest

Body:
Finally I got the solution myself I didn't find any answer of my question here so I decided to answer this to help others

I solved the problem to get dl images using this code

$data = 'your html content';

        if (preg_match("/<div id='gallery-1' class='gallery galleryid-273 gallery-columns-2 gallery-size-full'><dl class='gallery-item'>/",$data)){
            $data0 = explode("<dl class='gallery-item'>",$data);
            $proj_img = array();
            foreach($data0 as $key=> $imgArray)
            {
                $proj_img[$key] = scrape_between($imgArray, 'data-srcset="', '?w');
            }
            $proj_img = array_filter($proj_img);
            echo "<pre>"; print_r($proj_img);
        }