问:
How can I efficiently join data of 2 json files?
I have 2 json files that I import with jquery and basically want to join the 2 arrays into 1 array. This is what the json files look like:

players.json

```<code>{
    "players": [
        {
            "id": 109191123,
            "surname": "Farah",
            "full_name": "Robbie Farah",
            "short_name": "R. Farah",
            "other_names": "Robert",
            "jumper_number": 9,
            "position_code": "CEN1",
            "position_order": 9,
            "position_description": "Hooker",
            "is_captain": false,
            "is_interchange": false
        },
        {
            "id": 109509,
            "surname": "Rapana",
            "full_name": "Jordan Rapana",
            "short_name": "J. Rapana",
            "other_names": "Jordan",
            "jumper_number": 1,
            "position_code": "FBCK",
            "position_order": 1,
            "position_description": "Full Back",
            "is_captain": false,
            "is_interchange": false
        },
        {
            "id": 111285,
            "surname": "Waqa",
            "full_name": "Sisa Waqa",
            "short_name": "S. Waqa",
            "other_names": "Sisa",
            "jumper_number": 2,
            "position_code": "WING1",
            "position_order": 2,
            "position_description": "Wing",
            "is_captain": false,
            "is_interchange": false
        },
        {
            "id": 109861,
            "surname": "Croker",
            "full_name": "Jarrod Croker",
            "short_name": "J. Croker",
            "other_names": "Jarrod",
            "jumper_number": 3,
            "position_code": "CEN1",
            "position_order": 3,
            "position_description": "Centre",
            "is_captain": true,
            "is_interchange": false
        },
        {
            "id": 112814,
            "surname": "Lee",
            "full_name": "Edrick Lee",
            "short_name": "E. Lee",
            "other_names": "Edrick",
            "jumper_number": 5,
            "position_code": "CEN2",
            "position_order": 4,
            "position_description": "Centre",
            "is_captain": false,
            "is_interchange": false
        }
    ]
}
</code>```

stats.json

```<code>  {
    "player_stats": [
        {
            "id": 112814,
            "matches": "123",
            "tries": "11"
        },
        {
            "id": 111285,
            "matches": "234",
            "tries": "22"
        },
        {
            "id": 109861,
            "matches": "345",
            "tries": "33"
        },
        {
            "id": 109509,
            "matches": "456",
            "tries": "44"
        },
        {
            "id": 109510,
            "matches": "567",
            "tries": "55"
        }
    ]
}
</code>```

I am currently looking to join the data into a new array so one of the items would look like:

```<code>{
   player:'Lee',
   matches:123,
   tried:11
}
</code>```

Basically 'joining' two data from the json files.

Currently there is an import for the 2 json files and then looping over both arrays trying to find a match on the id-property.
Is there a more efficient way of doing this preferably using vanilla js/jquery?

```<code>var players, stats, items = [];
    $.getJSON("data/players.json", function (data) {
        $.each(data, function (key, players) {
            $.getJSON("data/stats.json", function (data) {
                $.each(data, function (key, stats) {
                    //check stats available for players:
                    for (var i = 0; i < players.length; i++) {
                        for (var j = 0; j < stats.length; j++) {
                            var exists = items.some(function (item) {
                                return (item.player === players[i].full_name)
                            })
                            if (players[i].id === stats[j].id && !exists) {
                                items.push({
                                    player: players[i].full_name,
                                    matches: stats[j].matches,
                                    tries: stats[j].tries,
                                })
                            }
                        }
                    }

                });

            });
        });

    });
</code>```

答:
You can use a combination of .map and .find

var players = {
  "players": [{
      "id": 109191123,
      "surname": "Farah",
      "full_name": "Robbie Farah",
      "short_name": "R. Farah",
      "other_names": "Robert",
      "jumper_number": 9,
      "position_code": "CEN1",
      "position_order": 9,
      "position_description": "Hooker",
      "is_captain": false,
      "is_interchange": false
    },
    {
      "id": 109509,
      "surname": "Rapana",
      "full_name": "Jordan Rapana",
      "short_name": "J. Rapana",
      "other_names": "Jordan",
      "jumper_number": 1,
      "position_code": "FBCK",
      "position_order": 1,
      "position_description": "Full Back",
      "is_captain": false,
      "is_interchange": false
    },
    {
      "id": 111285,
      "surname": "Waqa",
      "full_name": "Sisa Waqa",
      "short_name": "S. Waqa",
      "other_names": "Sisa",
      "jumper_number": 2,
      "position_code": "WING1",
      "position_order": 2,
      "position_description": "Wing",
      "is_captain": false,
      "is_interchange": false
    },
    {
      "id": 109861,
      "surname": "Croker",
      "full_name": "Jarrod Croker",
      "short_name": "J. Croker",
      "other_names": "Jarrod",
      "jumper_number": 3,
      "position_code": "CEN1",
      "position_order": 3,
      "position_description": "Centre",
      "is_captain": true,
      "is_interchange": false
    },
    {
      "id": 112814,
      "surname": "Lee",
      "full_name": "Edrick Lee",
      "short_name": "E. Lee",
      "other_names": "Edrick",
      "jumper_number": 5,
      "position_code": "CEN2",
      "position_order": 4,
      "position_description": "Centre",
      "is_captain": false,
      "is_interchange": false
    }
  ]
}

var stats = {
  "player_stats": [{
      "id": 112814,
      "matches": "123",
      "tries": "11"
    },
    {
      "id": 111285,
      "matches": "234",
      "tries": "22"
    },
    {
      "id": 109861,
      "matches": "345",
      "tries": "33"
    },
    {
      "id": 109509,
      "matches": "456",
      "tries": "44"
    },
    {
      "id": 109510,
      "matches": "567",
      "tries": "55"
    }
  ]
}

var result = stats.player_stats.map(s => {
  var match = players.players.find(p => p.id == s.id);
  var name = "";

  if (match) {
    name = match.full_name;
  }

  return {
    player: name,
    matches: s.matches,
    tries: s.tries
  }
});

console.log(result)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}</code>```

If you want it so that if there is no match it's not included you can change the .map to .reduce

var players = {
  "players": [{
      "id": 109191123,
      "surname": "Farah",
      "full_name": "Robbie Farah",
      "short_name": "R. Farah",
      "other_names": "Robert",
      "jumper_number": 9,
      "position_code": "CEN1",
      "position_order": 9,
      "position_description": "Hooker",
      "is_captain": false,
      "is_interchange": false
    },
    {
      "id": 109509,
      "surname": "Rapana",
      "full_name": "Jordan Rapana",
      "short_name": "J. Rapana",
      "other_names": "Jordan",
      "jumper_number": 1,
      "position_code": "FBCK",
      "position_order": 1,
      "position_description": "Full Back",
      "is_captain": false,
      "is_interchange": false
    },
    {
      "id": 111285,
      "surname": "Waqa",
      "full_name": "Sisa Waqa",
      "short_name": "S. Waqa",
      "other_names": "Sisa",
      "jumper_number": 2,
      "position_code": "WING1",
      "position_order": 2,
      "position_description": "Wing",
      "is_captain": false,
      "is_interchange": false
    },
    {
      "id": 109861,
      "surname": "Croker",
      "full_name": "Jarrod Croker",
      "short_name": "J. Croker",
      "other_names": "Jarrod",
      "jumper_number": 3,
      "position_code": "CEN1",
      "position_order": 3,
      "position_description": "Centre",
      "is_captain": true,
      "is_interchange": false
    },
    {
      "id": 112814,
      "surname": "Lee",
      "full_name": "Edrick Lee",
      "short_name": "E. Lee",
      "other_names": "Edrick",
      "jumper_number": 5,
      "position_code": "CEN2",
      "position_order": 4,
      "position_description": "Centre",
      "is_captain": false,
      "is_interchange": false
    }
  ]
}

var stats = {
  "player_stats": [{
      "id": 112814,
      "matches": "123",
      "tries": "11"
    },
    {
      "id": 111285,
      "matches": "234",
      "tries": "22"
    },
    {
      "id": 109861,
      "matches": "345",
      "tries": "33"
    },
    {
      "id": 109509,
      "matches": "456",
      "tries": "44"
    },
    {
      "id": 109510,
      "matches": "567",
      "tries": "55"
    }
  ]
}

var result = stats.player_stats.reduce((a, s) => {
  var match = players.players.find(p => p.id == s.id);

  if (match) {
    a.push({
      player: match.full_name,
      matches: s.matches,
      tries: s.tries
    })
  }

  return a;
}, []);

console.log(result)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}</code>```

Body:
I have 2 json files that I import with jquery and basically want to join the 2 arrays into 1 array. This is what the json files look like:

players.json

{
    "players": [
        {
            "id": 109191123,
            "surname": "Farah",
            "full_name": "Robbie Farah",
            "short_name": "R. Farah",
            "other_names": "Robert",
            "jumper_number": 9,
            "position_code": "CEN1",
            "position_order": 9,
            "position_description": "Hooker",
            "is_captain": false,
            "is_interchange": false
        },
        {
            "id": 109509,
            "surname": "Rapana",
            "full_name": "Jordan Rapana",
            "short_name": "J. Rapana",
            "other_names": "Jordan",
            "jumper_number": 1,
            "position_code": "FBCK",
            "position_order": 1,
            "position_description": "Full Back",
            "is_captain": false,
            "is_interchange": false
        },
        {
            "id": 111285,
            "surname": "Waqa",
            "full_name": "Sisa Waqa",
            "short_name": "S. Waqa",
            "other_names": "Sisa",
            "jumper_number": 2,
            "position_code": "WING1",
            "position_order": 2,
            "position_description": "Wing",
            "is_captain": false,
            "is_interchange": false
        },
        {
            "id": 109861,
            "surname": "Croker",
            "full_name": "Jarrod Croker",
            "short_name": "J. Croker",
            "other_names": "Jarrod",
            "jumper_number": 3,
            "position_code": "CEN1",
            "position_order": 3,
            "position_description": "Centre",
            "is_captain": true,
            "is_interchange": false
        },
        {
            "id": 112814,
            "surname": "Lee",
            "full_name": "Edrick Lee",
            "short_name": "E. Lee",
            "other_names": "Edrick",
            "jumper_number": 5,
            "position_code": "CEN2",
            "position_order": 4,
            "position_description": "Centre",
            "is_captain": false,
            "is_interchange": false
        }
    ]
}

stats.json

  {
    "player_stats": [
        {
            "id": 112814,
            "matches": "123",
            "tries": "11"
        },
        {
            "id": 111285,
            "matches": "234",
            "tries": "22"
        },
        {
            "id": 109861,
            "matches": "345",
            "tries": "33"
        },
        {
            "id": 109509,
            "matches": "456",
            "tries": "44"
        },
        {
            "id": 109510,
            "matches": "567",
            "tries": "55"
        }
    ]
}

I am currently looking to join the data into a new array so one of the items would look like:

{
   player:'Lee',
   matches:123,
   tried:11
}

Basically 'joining' two data from the json files.

Currently there is an import for the 2 json files and then looping over both arrays trying to find a match on the id-property.
Is there a more efficient way of doing this preferably using vanilla js/jquery?

var players, stats, items = [];
    $.getJSON("data/players.json", function (data) {
        $.each(data, function (key, players) {
            $.getJSON("data/stats.json", function (data) {
                $.each(data, function (key, stats) {
                    //check stats available for players:
                    for (var i = 0; i < players.length; i++) {
                        for (var j = 0; j < stats.length; j++) {
                            var exists = items.some(function (item) {
                                return (item.player === players[i].full_name)
                            })
                            if (players[i].id === stats[j].id && !exists) {
                                items.push({
                                    player: players[i].full_name,
                                    matches: stats[j].matches,
                                    tries: stats[j].tries,
                                })
                            }
                        }
                    }

                });

            });
        });

    });

Body:
You can use a combination of .map and .find

var players = {
  "players": [{
      "id": 109191123,
      "surname": "Farah",
      "full_name": "Robbie Farah",
      "short_name": "R. Farah",
      "other_names": "Robert",
      "jumper_number": 9,
      "position_code": "CEN1",
      "position_order": 9,
      "position_description": "Hooker",
      "is_captain": false,
      "is_interchange": false
    },
    {
      "id": 109509,
      "surname": "Rapana",
      "full_name": "Jordan Rapana",
      "short_name": "J. Rapana",
      "other_names": "Jordan",
      "jumper_number": 1,
      "position_code": "FBCK",
      "position_order": 1,
      "position_description": "Full Back",
      "is_captain": false,
      "is_interchange": false
    },
    {
      "id": 111285,
      "surname": "Waqa",
      "full_name": "Sisa Waqa",
      "short_name": "S. Waqa",
      "other_names": "Sisa",
      "jumper_number": 2,
      "position_code": "WING1",
      "position_order": 2,
      "position_description": "Wing",
      "is_captain": false,
      "is_interchange": false
    },
    {
      "id": 109861,
      "surname": "Croker",
      "full_name": "Jarrod Croker",
      "short_name": "J. Croker",
      "other_names": "Jarrod",
      "jumper_number": 3,
      "position_code": "CEN1",
      "position_order": 3,
      "position_description": "Centre",
      "is_captain": true,
      "is_interchange": false
    },
    {
      "id": 112814,
      "surname": "Lee",
      "full_name": "Edrick Lee",
      "short_name": "E. Lee",
      "other_names": "Edrick",
      "jumper_number": 5,
      "position_code": "CEN2",
      "position_order": 4,
      "position_description": "Centre",
      "is_captain": false,
      "is_interchange": false
    }
  ]
}

var stats = {
  "player_stats": [{
      "id": 112814,
      "matches": "123",
      "tries": "11"
    },
    {
      "id": 111285,
      "matches": "234",
      "tries": "22"
    },
    {
      "id": 109861,
      "matches": "345",
      "tries": "33"
    },
    {
      "id": 109509,
      "matches": "456",
      "tries": "44"
    },
    {
      "id": 109510,
      "matches": "567",
      "tries": "55"
    }
  ]
}

var result = stats.player_stats.map(s => {
  var match = players.players.find(p => p.id == s.id);
  var name = "";

  if (match) {
    name = match.full_name;
  }

  return {
    player: name,
    matches: s.matches,
    tries: s.tries
  }
});

console.log(result)

.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

If you want it so that if there is no match it's not included you can change the .map to .reduce

var players = {
  "players": [{
      "id": 109191123,
      "surname": "Farah",
      "full_name": "Robbie Farah",
      "short_name": "R. Farah",
      "other_names": "Robert",
      "jumper_number": 9,
      "position_code": "CEN1",
      "position_order": 9,
      "position_description": "Hooker",
      "is_captain": false,
      "is_interchange": false
    },
    {
      "id": 109509,
      "surname": "Rapana",
      "full_name": "Jordan Rapana",
      "short_name": "J. Rapana",
      "other_names": "Jordan",
      "jumper_number": 1,
      "position_code": "FBCK",
      "position_order": 1,
      "position_description": "Full Back",
      "is_captain": false,
      "is_interchange": false
    },
    {
      "id": 111285,
      "surname": "Waqa",
      "full_name": "Sisa Waqa",
      "short_name": "S. Waqa",
      "other_names": "Sisa",
      "jumper_number": 2,
      "position_code": "WING1",
      "position_order": 2,
      "position_description": "Wing",
      "is_captain": false,
      "is_interchange": false
    },
    {
      "id": 109861,
      "surname": "Croker",
      "full_name": "Jarrod Croker",
      "short_name": "J. Croker",
      "other_names": "Jarrod",
      "jumper_number": 3,
      "position_code": "CEN1",
      "position_order": 3,
      "position_description": "Centre",
      "is_captain": true,
      "is_interchange": false
    },
    {
      "id": 112814,
      "surname": "Lee",
      "full_name": "Edrick Lee",
      "short_name": "E. Lee",
      "other_names": "Edrick",
      "jumper_number": 5,
      "position_code": "CEN2",
      "position_order": 4,
      "position_description": "Centre",
      "is_captain": false,
      "is_interchange": false
    }
  ]
}

var stats = {
  "player_stats": [{
      "id": 112814,
      "matches": "123",
      "tries": "11"
    },
    {
      "id": 111285,
      "matches": "234",
      "tries": "22"
    },
    {
      "id": 109861,
      "matches": "345",
      "tries": "33"
    },
    {
      "id": 109509,
      "matches": "456",
      "tries": "44"
    },
    {
      "id": 109510,
      "matches": "567",
      "tries": "55"
    }
  ]
}

var result = stats.player_stats.reduce((a, s) => {
  var match = players.players.find(p => p.id == s.id);

  if (match) {
    a.push({
      player: match.full_name,
      matches: s.matches,
      tries: s.tries
    })
  }

  return a;
}, []);

console.log(result)

.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}


来源: stackexchange

问:
how would i remove term parameter from jquery autocomplete ajax URL
When going to search customer name, jQuery automatically appends cstmr-prfsnl-ajax-search.php?term=[search value] but I want to replace term with customer. please help me.

```<code>$("#ccpd_name").autocomplete({
  source: "cstmr-prfsnl-ajax-search.php",
  minLength: 1
});
</code>```

答:
You can use like this :

```<code>$("#ccpd_name").autocomplete({
     source: function (request, response) {
        $.ajax({
             url: "cstmr-prfsnl-ajax-search.php",
             data: { customer: request.term },
             dataType: "json",
             success: response,
             error: function () {
                 response([]);
             }
         });
     });
});
</code>```

cstmr-prfsnl-ajax-search.php?customer=[search value]

ContentLicense: CC BY-SA 3.0

Body:
When going to search customer name, jQuery automatically appends cstmr-prfsnl-ajax-search.php?term=[search value] but I want to replace term with customer. please help me.

$("#ccpd_name").autocomplete({
  source: "cstmr-prfsnl-ajax-search.php",
  minLength: 1
});

Body:
You can use like this :

$("#ccpd_name").autocomplete({
     source: function (request, response) {
        $.ajax({
             url: "cstmr-prfsnl-ajax-search.php",
             data: { customer: request.term },
             dataType: "json",
             success: response,
             error: function () {
                 response([]);
             }
         });
     });
});

cstmr-prfsnl-ajax-search.php?customer=[search value]


问:
Selecting non-nested subnodes with JQuery
I have a HTML structure that contains nested divs with the container class:

```<code><div class="container" id="0">
  <div id="1">
    <div class="container" id="2">
      <div class="container" id="3"></div>
    </div>
    <div id="4">
      <div class="container" id="5"></div>
    </div>
  </div>
</div>
</code>```

This could include more divs and deeper/different nesting.

Starting from some point in the tree I'd like to find all containers in that subtree that are not nested within other containers. So for example from div #1 I'd like to find the divs #2 and #5, but not #3 (since it is nested in container #2 already found).

What would be the best way to accomplish this?

答:
Try using jQuery's filter() method:

```<code>$items = $('#0').find('.container').filter(function(index) {
    return !$(this).parents(':not(#0)').hasClass('container');
});
</code>```

Basically, it finds all items with class .container below your top .container and filters the set based on whether or not the direct parent has the class .container.

See here for a working example: http://jsfiddle.net/TzL8Z/1

ContentLicense: CC BY-SA 2.5

Body:
I have a HTML structure that contains nested divs with the container class:

This could include more divs and deeper/different nesting.

Starting from some point in the tree I'd like to find all containers in that subtree that are not nested within other containers. So for example from div #1 I'd like to find the divs #2 and #5, but not #3 (since it is nested in container #2 already found).

What would be the best way to accomplish this?

Body:
Try using jQuery's filter() method:

$items = $('#0').find('.container').filter(function(index) {
    return !$(this).parents(':not(#0)').hasClass('container');
});

Basically, it finds all items with class .container below your top .container and filters the set based on whether or not the direct parent has the class .container.

See here for a working example: http://jsfiddle.net/TzL8Z/1


答:
You can use array.prototype.map and array.prototype.find :

var players = {
    "players": [
        {
            "id": 109191123,
            "surname": "Farah",
            "full_name": "Robbie Farah",
            "short_name": "R. Farah",
            "other_names": "Robert",
            "jumper_number": 9,
            "position_code": "CEN1",
            "position_order": 9,
            "position_description": "Hooker",
            "is_captain": false,
            "is_interchange": false
        },
        {
            "id": 109509,
            "surname": "Rapana",
            "full_name": "Jordan Rapana",
            "short_name": "J. Rapana",
            "other_names": "Jordan",
            "jumper_number": 1,
            "position_code": "FBCK",
            "position_order": 1,
            "position_description": "Full Back",
            "is_captain": false,
            "is_interchange": false
        },
        {
            "id": 111285,
            "surname": "Waqa",
            "full_name": "Sisa Waqa",
            "short_name": "S. Waqa",
            "other_names": "Sisa",
            "jumper_number": 2,
            "position_code": "WING1",
            "position_order": 2,
            "position_description": "Wing",
            "is_captain": false,
            "is_interchange": false
        },
        {
            "id": 109861,
            "surname": "Croker",
            "full_name": "Jarrod Croker",
            "short_name": "J. Croker",
            "other_names": "Jarrod",
            "jumper_number": 3,
            "position_code": "CEN1",
            "position_order": 3,
            "position_description": "Centre",
            "is_captain": true,
            "is_interchange": false
        },
        {
            "id": 112814,
            "surname": "Lee",
            "full_name": "Edrick Lee",
            "short_name": "E. Lee",
            "other_names": "Edrick",
            "jumper_number": 5,
            "position_code": "CEN2",
            "position_order": 4,
            "position_description": "Centre",
            "is_captain": false,
            "is_interchange": false
        }
    ]
};

var stats =   {
    "player_stats": [
        {
            "id": 112814,
            "matches": "123",
            "tries": "11"
        },
        {
            "id": 111285,
            "matches": "234",
            "tries": "22"
        },
        {
            "id": 109861,
            "matches": "345",
            "tries": "33"
        },
        {
            "id": 109509,
            "matches": "456",
            "tries": "44"
        },
        {
            "id": 109510,
            "matches": "567",
            "tries": "55"
        }
    ]
};

var joined = stats.player_stats.map(stat => {
  var player = players.players.find(p => p.id === stat.id);
  return { player:  player ? player.surname : "", matches: stat.matches, tried: stat.tries };
});

console.log(joined);```

Title: How can I efficiently join data of 2 json files?


问:
How to create a messagebox as an argument to powershell.exe?
How can I provide arguments to powershell.exe in order to spawn a message box? The key phrase here is arguments to powershell.exe, not from within a .ps1 script and also not from within the Powershell prompt itself. I currently have this but it is producing errors:

```<code>powershell.exe -Command "[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms"); [System.Windows.Forms.MessageBox]::Show("Test!!!")"
</code>```

I have also tried without -Command and with Invoke-Expression, with and without double quotes surrounding.

Errors created:

```<code>At line:1 char:51
+ [System.Reflection.Assembly]::LoadWithPartialName(System.Windows.Form ...
+                                                   ~
Missing ')' in method call.
At line:1 char:51
+ ... eflection.Assembly]::LoadWithPartialName(System.Windows.Forms); [Syst ...
+                                              ~~~~~~~~~~~~~~~~~~~~
Unexpected token 'System.Windows.Forms' in expression or statement.
At line:1 char:71
+ ... flection.Assembly]::LoadWithPartialName(System.Windows.Forms); [Syste ...
+                                                                 ~
Unexpected token ')' in expression or statement.
At line:1 char:114
+ ... stem.Windows.Forms); [System.Windows.Forms.MessageBox]::Show(Test!!!)
+                                                                  ~
Missing ')' in method call.
At line:1 char:114
+ ... stem.Windows.Forms); [System.Windows.Forms.MessageBox]::Show(Test!!!)
+                                                                  ~~~~~~~
Unexpected token 'Test!!!' in expression or statement.
At line:1 char:121
+ ... stem.Windows.Forms); [System.Windows.Forms.MessageBox]::Show(Test!!!)
+                                                                         ~
Unexpected token ')' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingEndParenthesisInMethodCall
</code>```

答:
This is a quotation problem. Using the same double quote " in both argument and its contents messes up the content. As a work-around, use single quotes within the Powershell command and double quotes around the whole -Command parameter. Like so,

```<code>powershell.exe -Command "[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Test!!!')"
</code>```

That being said, Add-Type -AssemblyName is IMAO prettier way to load assemblies. Like so,

```<code>powershell.exe -Command "add-type -assemblyname System.Windows.Forms; [System.Windows.Forms.MessageBox]::Show('Test!!!')"
</code>```

Body:
How can I provide arguments to powershell.exe in order to spawn a message box? The key phrase here is arguments to powershell.exe, not from within a .ps1 script and also not from within the Powershell prompt itself. I currently have this but it is producing errors:

powershell.exe -Command "[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms"); [System.Windows.Forms.MessageBox]::Show("Test!!!")"

I have also tried without -Command and with Invoke-Expression, with and without double quotes surrounding.

Errors created:

At line:1 char:51
+ [System.Reflection.Assembly]::LoadWithPartialName(System.Windows.Form ...
+                                                   ~
Missing ')' in method call.
At line:1 char:51
+ ... eflection.Assembly]::LoadWithPartialName(System.Windows.Forms); [Syst ...
+                                              ~~~~~~~~~~~~~~~~~~~~
Unexpected token 'System.Windows.Forms' in expression or statement.
At line:1 char:71
+ ... flection.Assembly]::LoadWithPartialName(System.Windows.Forms); [Syste ...
+                                                                 ~
Unexpected token ')' in expression or statement.
At line:1 char:114
+ ... stem.Windows.Forms); [System.Windows.Forms.MessageBox]::Show(Test!!!)
+                                                                  ~
Missing ')' in method call.
At line:1 char:114
+ ... stem.Windows.Forms); [System.Windows.Forms.MessageBox]::Show(Test!!!)
+                                                                  ~~~~~~~
Unexpected token 'Test!!!' in expression or statement.
At line:1 char:121
+ ... stem.Windows.Forms); [System.Windows.Forms.MessageBox]::Show(Test!!!)
+                                                                         ~
Unexpected token ')' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingEndParenthesisInMethodCall

Body:
This is a quotation problem. Using the same double quote " in both argument and its contents messes up the content. As a work-around, use single quotes within the Powershell command and double quotes around the whole -Command parameter. Like so,

powershell.exe -Command "[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Test!!!')"

That being said, Add-Type -AssemblyName is IMAO prettier way to load assemblies. Like so,

powershell.exe -Command "add-type -assemblyname System.Windows.Forms; [System.Windows.Forms.MessageBox]::Show('Test!!!')"


Title: adding new column to pandas dataframe to indicate duplicates in specific columns

Body:
I'm a newbie to pandas and I'm having issues with writing a function to add a new column based on custom conditions:
Following is my dataframe :

    c1      c2     c3           c4              c5
0   1234    888    36.12733265  -115.1710473    7048929337
1   2341    70     33.62503113  -111.928576     7048929337
2   8910    419    40.734631    -73.8700321     9192939495
3   8910    910    40.734631    -73.8700321     9192939495
4   5678    1295   40.719729    -73.84412       5109400188
5   3345    4976   33.5350596   -112.2670918    9192939495
6   233345  2364   33.5350596   -112.2670918    4806391796
7   3010    1155   42.8254528   -71.5012724     2393900772
8   3010    6800   41.0488534   -75.313324      8434975913
9   4534    1791   42.955875    -76.92238325    9048190206
10  7658    4711   40.7635948   -73.3066489     6312542029
11  7658    9120   34.8465348   -117.0854289    6312542029

I want to add new column called dup, which contains flags to indicate whether that row is duplicate(duplicate in terms of specific columns) or not.
Priority is in the following order :

1.) if row is duplicate in terms of both c3 and c4, flag should be dup_c3c4

2.)else if row is duplicate in terms of c5, flag should be dup_c5

3.) else if row is duplicate in terms of c1 , then flag should be dup_c1

4.)else flag should be NaD(Not a Duplicate).

Expected output :

    c1      c2      c3            c4            c5          DUP
0   1234    888     36.12733265  -115.1710473   7048929337  dup_c5
1   2341    70      33.62503113  -111.928576    7048929337  dup_c5
2   8910    419     40.734631    -73.8700321    9192939495  dup_c4c5
3   8910    910     40.734631    -73.8700321    9192939495  dup_c4c5
4   5678    1295    40.719729    -73.84412      5109400188  NaD
5   3345    4976    33.5350596   -112.2670918   9192939495  dup_c4c5
6   233345  2364    33.5350596   -112.2670918   4806391796  dup_c4c5
7   3010    1155    42.8254528   -71.5012724    2393900772  dup_c1
8   3010    6800    41.0488534   -75.313324     8434975913  dup_c1
9   4534    1791    42.955875    -76.92238325   9048190206  NaD
10  7658    4711    40.7635948   -73.3066489    6312542029  dup_c5
11  7658    9120    34.8465348   -117.0854289   6312542029  dup_c5

Can any one suggest me how to write a custom function for this scenario using if else or in any other efficient manner.

Body:
Use numpy.select with duplicated for 3 different conditions:

m1 = df.duplicated(['c3','c4'], keep=False)
m2 = df.duplicated(['c5'], keep=False)
m3 = df.duplicated(['c1'], keep=False)

df['DUP'] = np.select([m1,m2,m3],['dup_c3c4','dup_c5','dup_c1'], default='NaD')
print (df)
        c1    c2         c3          c4          c5       DUP
0     1234   888  36.127333 -115.171047  7048929337    dup_c5
1     2341    70  33.625031 -111.928576  7048929337    dup_c5
2     8910   419  40.734631  -73.870032  9192939495  dup_c3c4
3     8910   910  40.734631  -73.870032  9192939495  dup_c3c4
4     5678  1295  40.719729  -73.844120  5109400188       NaD
5     3345  4976  33.535060 -112.267092  9192939495  dup_c3c4
6   233345  2364  33.535060 -112.267092  4806391796  dup_c3c4
7     3010  1155  42.825453  -71.501272  2393900772    dup_c1
8     3010  6800  41.048853  -75.313324  8434975913    dup_c1
9     4534  1791  42.955875  -76.922383  9048190206       NaD
10    7658  4711  40.763595  -73.306649  6312542029    dup_c5
11    7658  9120  34.846535 -117.085429  6312542029    dup_c5

If need function:

def f(df):
    m1 = df.duplicated(['c3','c4'], keep=False)
    m2 = df.duplicated(['c5'], keep=False)
    m3 = df.duplicated(['c1'], keep=False)

    df['DUP'] = np.select([m1,m2,m3],['dup_c3c4','dup_c5','dup_c1'], default='NaD')
    return df

df1 = f(df)


问:
Hive joining on between condition
I am having trouble with joining 2 tables based on 'between' condition in Hive. Basically because Hive doesn't support these joins I don't know how to work around it. Basically, I want to join two tables based on date column where t1.date<=t2.date and t1.date>=t2.tdate2. No other columns match in the tables. How can i achieve that?h</p>

答:
In my opinion first apply filtering and modify on one of the table and then apply join.

```<code>select t.id, new.id from (select t1.id from temp t1, new_temp t2 where t1.id > t2.id)t join new_temp new on (t.id = new.id);
</code>```

This should work. I have tested with test cases that came to my mind.

Following are other approaches you may think of but wont work.

1. Apply where with join

```<code>select t1.id, t2.id from temp t1 join new_temp t2 on (t1.id = t2.id) where t1.id < t2.id
</code>```

=> this query will execute join first and then condition so there will no row in output.
You can check execution flow by executing :

```<code> explain select t1.id, t2.id from temp t1 join new_temp t2 on (t1.id = t2.id) where t1.id < t2.id;
</code>```

2. Apply where after join

```<code>select * from (select t1.id as t1id, t2.id as t2id from temp t1 join new_temp t2 on (t1.id = t2.id))new_table where t1id < t2id;
</code>```

Here as join is already applied, every time t1id and t2id will be equal.

Title: Hive joining on between condition

Body:
In my opinion first apply filtering and modify on one of the table and then apply join.

select t.id, new.id from (select t1.id from temp t1, new_temp t2 where t1.id > t2.id)t join new_temp new on (t.id = new.id);

This should work. I have tested with test cases that came to my mind.

Following are other approaches you may think of but wont work.

1. Apply where with join

select t1.id, t2.id from temp t1 join new_temp t2 on (t1.id = t2.id) where t1.id < t2.id

=> this query will execute join first and then condition so there will no row in output.
You can check execution flow by executing :

 explain select t1.id, t2.id from temp t1 join new_temp t2 on (t1.id = t2.id) where t1.id < t2.id;

2. Apply where after join

select * from (select t1.id as t1id, t2.id as t2id from temp t1 join new_temp t2 on (t1.id = t2.id))new_table where t1id < t2id;

Here as join is already applied, every time t1id and t2id will be equal.


问:
Multiple markers with specific infotemplate content
When I'm looping through a list of addresses, I'm able to plot the markers for all the addresses fine. But when I click on any marker, the infowindow content shows data of only the last marker. How do I solve this?

Javscript

```<code>var map ={};
map.markers = [];
map.addresses = [
    {
        'line': '2101 K St',
        'ref_no': '160621-000005'
    },
    {
        'line': '2131 K St',
        'ref_no': '170708-000015'
    },
    {
        'line': '2321 K St',
        'ref_no': '170707-000028'
    }
];

.
.
.
map.map_object = new Map("esri_map", {
   basemap: "topo",
   center: [<lat>, <lng>],
   zoom: 12
});

var locator = new Locator("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");
for(var i = 0; i < map.addresses.length; i++)
{
    var addr = map.addresses[i];
    var params = {
        countryCode: "US",
        maxLocations: 1,
        address: {"SingleLine": addr.line}
    };
    locator.addressToLocations(params, function(candidates){
        locatorDone(candidates, addr);
    });
}

function locatorDone(candidates, addr)
{
    .
    .
    .
    var html = "<h5>"+addr.line+"</h5>";
    html += "<p>Ref#: "+addr.ref_no+"</p>";
    var infoTemplate = new esri.InfoTemplate(addr.ref_no, html); // <--- Problem lies here
    var graphic = new esri.Graphic(pt, symbol,'',infoTemplate);
    map.map_object.graphics.add(graphic);
    map.markers.push(graphic);
}
</code>```

P.S: I've solved similar problems (in case of Google Maps API) by using closures. But I'm not sure how to use that in this case.

答:
You can wrap the inside of the for loop in a self invoking function which will provide the closure. Something like this:

```<code>for(var i = 0; i < map.addresses.length; i++)
    (function (i) {
        var addr = map.addresses[i];
        var params = {
            countryCode: "US",
            maxLocations: 1,
            address: {"SingleLine": addr.line}
        };
        locator.addressToLocations(params, function(candidates){
            locatorDone(candidates, addr);
        });
    })(i)
</code>```

This will make i local to this code block. As it is now in your code all addr are referencing the last address because the for loop has finished running when you call locatorDone asynchronously. Alternatively you can use let like so: for (let i = 0; ... if you don't need this code to run on Internet Explorer below version 11.

Body:
When I'm looping through a list of addresses, I'm able to plot the markers for all the addresses fine. But when I click on any marker, the infowindow content shows data of only the last marker. How do I solve this?

Javscript

var map ={};
map.markers = [];
map.addresses = [
    {
        'line': '2101 K St',
        'ref_no': '160621-000005'
    },
    {
        'line': '2131 K St',
        'ref_no': '170708-000015'
    },
    {
        'line': '2321 K St',
        'ref_no': '170707-000028'
    }
];

.
.
.
map.map_object = new Map("esri_map", {
   basemap: "topo",
   center: [<lat>, <lng>],
   zoom: 12
});

var locator = new Locator("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");
for(var i = 0; i < map.addresses.length; i++)
{
    var addr = map.addresses[i];
    var params = {
        countryCode: "US",
        maxLocations: 1,
        address: {"SingleLine": addr.line}
    };
    locator.addressToLocations(params, function(candidates){
        locatorDone(candidates, addr);
    });
}

function locatorDone(candidates, addr)
{
    .
    .
    .
    var html = "
"+addr.line+"
";
    html += "
Ref#: "+addr.ref_no+"
";
    var infoTemplate = new esri.InfoTemplate(addr.ref_no, html); // <--- Problem lies here
    var graphic = new esri.Graphic(pt, symbol,'',infoTemplate);
    map.map_object.graphics.add(graphic);
    map.markers.push(graphic);
}

P.S: I've solved similar problems (in case of Google Maps API) by using closures. But I'm not sure how to use that in this case.

Body:
You can wrap the inside of the for loop in a self invoking function which will provide the closure. Something like this:

for(var i = 0; i < map.addresses.length; i++)
    (function (i) {
        var addr = map.addresses[i];
        var params = {
            countryCode: "US",
            maxLocations: 1,
            address: {"SingleLine": addr.line}
        };
        locator.addressToLocations(params, function(candidates){
            locatorDone(candidates, addr);
        });
    })(i)

This will make i local to this code block. As it is now in your code all addr are referencing the last address because the for loop has finished running when you call locatorDone asynchronously. Alternatively you can use let like so: for (let i = 0; ... if you don't need this code to run on Internet Explorer below version 11.


ContentLicense: CC BY-SA 4.0

Title: How can I organise and move row of data based on label matches?

Body:
I have raw data shown below. I'm trying to move a row of data that corresponds to a label it matches to a new location in the dataframe.

dat<-read.table(text='RowLabels col1    col2    col3    col4    col5    col6
L   24363.7 25944.9 25646.1 25335.4 23564.2 25411.5
             610    411.4   439 437.3   436.9   420.7   516.9
             1  86.4    113.9   103.5   113.5   80.3    129
             2  102.1   99.5    96.3    100.4   99.5    86
             3  109.7   102.2   100.2   112.9   92.3    123.8
             4  88.9    87.1    103.6   102.5   93.6    134.1
             5  -50.3   -40.2   -72.3   -61.4   -27 -22.7
             6  -35.3   -9.3    25.3    -0.3    15.6    -27.3
             7  109.9   85.8    80.7    69.3    66.4    94
             181920 652.9   729.2   652.1   689.1   612.5   738.4
             1  104.3   107.3   103.5   104.2   98.3    110.1
             2  103.6   102.6   100.1   103.2   88.8    117.7
             3  53.5    99.1    46.7    70.3    53.9    32.5
             4  93.5    107.2   98.3    99.3    97.3    121.1
             5  96.8    109.3   104 102.2   98.7    112.9
             6  103.6   96.9    104.7   104.4   91.5    137.7
             7  97.6    106.8   94.8    105.5   84  106.4
             181930 732.1   709.6   725.8   729.5   554.5   873.1
             1  118.4   98.8    102.3   102 101.9   115.8
             2  96.7    103.3   104.6   105.2   81.9    128.7
             3  96  98.2    99.4    97.9    69.8    120.6
             4  100.7   101 103.6   106.6   59.6    136.2
             5  106.1   103.4   104.7   104.8   76.1    131.8
             6  105 102.1   103 108.3   81  124.7
             7  109.2   102.8   108.2   104.7   84.2    115.3
             N  3836.4  4395.8  4227.3  4567.4  4009.9  4434.6
             610    88.1    96.3    99.6    92  90  137.6
             1  88.1    96.3    99.6    92  90  137.6
             181920 113.1   100.6   106.5   104.2   87.3    108.2
             1  113.1   100.6   106.5   104.2   87.3    108.2
             181930 111.3   99.1    104.5   115.5   103.6   118.8
             1  111.3   99.1    104.5   115.5   103.6   118.8
             ',header=TRUE)

I want to match the values of the three N-prefix labels: 610, 181920 and 181930 with its corresponding L-prefix labels. Basically move that row of data into the L-prefix as a new row, labeled 0 or 8 for example. So, the result for label, 610 would look like:

RowLabels col1    col2    col3    col4    col5    col6
610    411.4   439 437.3   436.9   420.7   516.9
         1  86.4    113.9   103.5   113.5   80.3    129
         2  102.1   99.5    96.3    100.4   99.5    86
         3  109.7   102.2   100.2   112.9   92.3    123.8
         4  88.9    87.1    103.6   102.5   93.6    134.1
         5  -50.3   -40.2   -72.3   -61.4   -27 -22.7
         6  -35.3   -9.3    25.3    -0.3    15.6    -27.3
         7  109.9   85.8    80.7    69.3    66.4    94
         8  88.1    96.3    99.6    92  90  137.6

Is this possible? I tried searching and I found some resources pointing toward dplyr or tidyr  or aggregate. But I can't find a good example that matches my case. How to combine rows based on unique values in R? and
Aggregate rows by shared values in a variable

Body:
library(dplyr)
library(zoo)

df <- dat %>%
  filter(grepl("^\\d+$",RowLabels)) %>%
  mutate(RowLabels_temp = ifelse(grepl("^\\d{3,}$",RowLabels), as.numeric(as.character(RowLabels)), NA)) %>%
  na.locf() %>%
  select(-RowLabels) %>%
  distinct() %>%
  group_by(RowLabels_temp) %>%
  mutate(RowLabels_indexed = row_number()-1) %>%
  arrange(RowLabels_temp, RowLabels_indexed) %>%
  mutate(RowLabels_indexed = ifelse(RowLabels_indexed==0, RowLabels_temp, RowLabels_indexed)) %>%
  rename(RowLabels=RowLabels_indexed) %>%
  data.frame()
df <- df %>% select(-RowLabels_temp)
df

Output is

    col1  col2  col3  col4  col5  col6 RowLabels
1  411.4 439.0 437.3 436.9 420.7 516.9       610
2   86.4 113.9 103.5 113.5  80.3 129.0         1
3  102.1  99.5  96.3 100.4  99.5  86.0         2
4  109.7 102.2 100.2 112.9  92.3 123.8         3
5   88.9  87.1 103.6 102.5  93.6 134.1         4
6  -50.3 -40.2 -72.3 -61.4 -27.0 -22.7         5
7  -35.3  -9.3  25.3  -0.3  15.6 -27.3         6
8  109.9  85.8  80.7  69.3  66.4  94.0         7
9   88.1  96.3  99.6  92.0  90.0 137.6         8
...


问:
private initialized variable not initializing
I have a datacontract on an inherited, partial class like this:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;

namespace Domain
{
  [DataContract]
  public partial class IdCard : DomainObject<System.Int64>
  {
    private Group _grp;

    [DataMember]
    public virtual Group Grp
    {
        get { return _grp; }
        set { _grp = value; }
    }

    private bool _unproxized = true;
    public override object UnProxy()
    {
        if (this._unproxized)  // this prevents stackoverflow with cyclical references
        {
            this.Grp = (Group)this.Grp.UnProxy();
            this._unproxized = false;
        }

        return this;
    }
  }
}
</code>```

For some reason, the _unproxized is never set to true;  Any ideas why?

I know I can simply switch the logic around, but I'm curious why the member variable is not being initialized.

答:
try to assign varibles in a constructor like this:</p>

```<code>public IdCard()
{
    _unproxized = true;
}
</code>```

Body:
I have a datacontract on an inherited, partial class like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;

namespace Domain
{
  [DataContract]
  public partial class IdCard : DomainObject<System.Int64>
  {
    private Group _grp;

    [DataMember]
    public virtual Group Grp
    {
        get { return _grp; }
        set { _grp = value; }
    }

    private bool _unproxized = true;
    public override object UnProxy()
    {
        if (this._unproxized)  // this prevents stackoverflow with cyclical references
        {
            this.Grp = (Group)this.Grp.UnProxy();
            this._unproxized = false;
        }

        return this;
    }
  }
}

For some reason, the _unproxized is never set to true;  Any ideas why?

I know I can simply switch the logic around, but I'm curious why the member variable is not being initialized.

Body:
try to assign varibles in a constructor like this:

public IdCard()
{
    _unproxized = true;
}


问:
SiteMap definition in new UI for 2017 R2
Is there documentation available as to how to configure the menu for new pages/modules in the new UI?
The Sitemap definition from page SM200520 works correctly only when the classic UI is used.

Thanks

答:
Acumatica Online Help has several how-to articles on customizing the New UI (aka Modern User Interface) here:

https://help.acumatica.com/(W(1))/Main?ScreenId=ShowWiki&pageid=774107f8-a149-4676-9c78-0c884edd19cb

If you need something more it'd be handy if you explained your goals more specifically.


问:
Opencv Extract largest region of interest
I have couple of images that look like the following:
The images are mostly on a  white background.

There are multiple pieces of clothing laid out on a white (mostly) background.

I tried detecting the two pieces of clothing using opencv connected components.
Tried to take the largest two connected components,Unfortunately , i am failing.

I believe that this is possible but since i am a newbie to opencv ,could somebody throw some light on what can be done to detect the multiple pieces of clothing in the following images?

Any help is appreciated

Code that that i tried in python:

```<code>#Read the image and conver to grayscale
img = cv2.imread('t.jpg' , 0)
#Applt the median filter on the image
#med = cv2.medianBlur(image,5)    # 5 is a fairly small kernel size
#Apply an edge detection filter

laplacian = cv2.Laplacian(img,cv2.CV_64F)

laplacian = laplacian.astype(np.uint8)
ret,thresh1 = cv2.threshold(laplacian,127,255,cv2.THRESH_BINARY)
src = thresh1
src  = np.array(src, np.uint8)
ret, thresh = cv2.threshold(src,10,255,cv2.THRESH_BINARY)
# You need to choose 4 or 8 for connectivity type
connectivity =8
# Perform the operation
output = cv2.connectedComponentsWithStats(thresh, connectivity, cv2.CV_32S)
# Get the results
# The first cell is the number of labels
num_labels = output[0]
# The second cell is the label matrix
labels = output[1]
# The third cell is the stat matrix
stats = output[2]
# The fourth cell is the centroid matrix
centroids = output[3]
src = cv2.cvtColor(src,cv2.COLOR_GRAY2RGB)
for stat in stats:
    x , y ,w , h ,a = stat
    cv2.rectangle(src,(x,y),(x+w,y+h),(0,0,255),2)
    # write original image with added contours to disk
    #cv2.imwrite('contoured.jpg', image)
cv2.imshow("Image", src)
#cv2.waitKey(0)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

My output for the above code

NB : Its fine even if i can extract the largest object in the given image.

答:
Here is a pretty simple approach just using image thresholding and finding contours to extracting just the biggest item of clothing in the second pic. To get the other item you would just have to adjust the thresholding so that it is not wiped out, then you would search through the contours. Not the best solution, but it's a start.

```<code>img = cv2.imread('t.jpg' , 0) # import image as grayscale array

# threshold image
img_b = cv2.GaussianBlur(img, (13, 13), 2)
ret, img_th = cv2.threshold(img_b, 40, 255, cv2.THRESH_BINARY_INV)
# find contours
(_,cnts,_) = cv2.findContours(img_th.copy(), cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
print(str(len(cnts))+' contours detected')

# find maximum area contour
area = np.array([cv2.contourArea(cnts[i]) for i in range(len(cnts))]) #
list of all areas
maxa_ind = np.argmax(area) # index of maximum area contour

plt.figure(figsize=(10,4))
plt.subplot(1,3,1)
plt.imshow(img_b)
plt.title('GaussianBlurr')
plt.subplot(1,3,2)
plt.imshow(img_th)
plt.title('threshold')
plt.subplot(1,3,3)
xx = [cnts[maxa_ind][i][0][0] for i in range(len(cnts[maxa_ind]))]
yy = [cnts[maxa_ind][i][0][1] for i in range(len(cnts[maxa_ind]))]
ROI.append([min(xx),max(xx),min(yy),max(yy)])
plt.imshow(img)
plt.plot(xx,yy,'r',linewidth=3)
plt.title('largest contour')
</code>```

This code produces the following image:

Body:
I have couple of images that look like the following:
The images are mostly on a  white background.

There are multiple pieces of clothing laid out on a white (mostly) background.

I tried detecting the two pieces of clothing using opencv connected components.
Tried to take the largest two connected components,Unfortunately , i am failing.

I believe that this is possible but since i am a newbie to opencv ,could somebody throw some light on what can be done to detect the multiple pieces of clothing in the following images?

Any help is appreciated

Code that that i tried in python:

#Read the image and conver to grayscale
img = cv2.imread('t.jpg' , 0)
#Applt the median filter on the image
#med = cv2.medianBlur(image,5)    # 5 is a fairly small kernel size
#Apply an edge detection filter

laplacian = cv2.Laplacian(img,cv2.CV_64F)

laplacian = laplacian.astype(np.uint8)
ret,thresh1 = cv2.threshold(laplacian,127,255,cv2.THRESH_BINARY)
src = thresh1
src  = np.array(src, np.uint8)
ret, thresh = cv2.threshold(src,10,255,cv2.THRESH_BINARY)
# You need to choose 4 or 8 for connectivity type
connectivity =8
# Perform the operation
output = cv2.connectedComponentsWithStats(thresh, connectivity, cv2.CV_32S)
# Get the results
# The first cell is the number of labels
num_labels = output[0]
# The second cell is the label matrix
labels = output[1]
# The third cell is the stat matrix
stats = output[2]
# The fourth cell is the centroid matrix
centroids = output[3]
src = cv2.cvtColor(src,cv2.COLOR_GRAY2RGB)
for stat in stats:
    x , y ,w , h ,a = stat
    cv2.rectangle(src,(x,y),(x+w,y+h),(0,0,255),2)
    # write original image with added contours to disk
    #cv2.imwrite('contoured.jpg', image)
cv2.imshow("Image", src)
#cv2.waitKey(0)
cv2.waitKey(0)
cv2.destroyAllWindows()

My output for the above code

NB : Its fine even if i can extract the largest object in the given image.

Body:
Here is a pretty simple approach just using image thresholding and finding contours to extracting just the biggest item of clothing in the second pic. To get the other item you would just have to adjust the thresholding so that it is not wiped out, then you would search through the contours. Not the best solution, but it's a start.

img = cv2.imread('t.jpg' , 0) # import image as grayscale array

# threshold image
img_b = cv2.GaussianBlur(img, (13, 13), 2)
ret, img_th = cv2.threshold(img_b, 40, 255, cv2.THRESH_BINARY_INV)
# find contours
(_,cnts,_) = cv2.findContours(img_th.copy(), cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
print(str(len(cnts))+' contours detected')

# find maximum area contour
area = np.array([cv2.contourArea(cnts[i]) for i in range(len(cnts))]) #
list of all areas
maxa_ind = np.argmax(area) # index of maximum area contour

plt.figure(figsize=(10,4))
plt.subplot(1,3,1)
plt.imshow(img_b)
plt.title('GaussianBlurr')
plt.subplot(1,3,2)
plt.imshow(img_th)
plt.title('threshold')
plt.subplot(1,3,3)
xx = [cnts[maxa_ind][i][0][0] for i in range(len(cnts[maxa_ind]))]
yy = [cnts[maxa_ind][i][0][1] for i in range(len(cnts[maxa_ind]))]
ROI.append([min(xx),max(xx),min(yy),max(yy)])
plt.imshow(img)
plt.plot(xx,yy,'r',linewidth=3)
plt.title('largest contour')

This code produces the following image:


问:
how to set footer at the bottom when there is no content

Designed by Wiredelta

```

not getting footer at bottom of the page when there is no content is present in the body.so i need to fix footer at the bottom only, when i run the code the code.plzz give suggestion how to fix footer at the bottom exactly.

答:
You have three options from which I would suggest using flex-box.

1. position: fixed

```<code>footer {
    position: fixed;
    left: 0;
    bottom: 0;
    right: 0;
}
</code>```

2. Flex-box

HTML

```<code><html>
    <body>
        <main></main>
        <footer></footer>
    </body>
</html>
</code>```

CSS

```<code>html {
    height: 100%;
}

body {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
}

main {
    flex-grow: 1;
}
</code>```

Demo: https://codepen.io/marcobiedermann/pen/XpoarE

3. Table

HTML

```<code><html>
    <body>
        <main></main>
        <footer></footer>
    </body>
</html>
</code>```

CSS

```<code>html {
    height: 100%;
}

body {
    display: table;
    min-height: 100vh;
}

main: {
    height: 100%;
}

footer {
    display: table-row;
    height: 1px;
}
</code>```

Demo: https://codepen.io/marcobiedermann/pen/jImsc

Body:
Designed by Wiredelta

not getting footer at bottom of the page when there is no content is present in the body.so i need to fix footer at the bottom only, when i run the code the code.plzz give suggestion how to fix footer at the bottom exactly.

Body:
You have three options from which I would suggest using flex-box.

1. position: fixed

footer {
    position: fixed;
    left: 0;
    bottom: 0;
    right: 0;
}

2. Flex-box

HTML

<html>
    <body>
        <main></main>
        <footer></footer>
    </body>
</html>

CSS

html {
    height: 100%;
}

body {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
}

main {
    flex-grow: 1;
}

Demo: https://codepen.io/marcobiedermann/pen/XpoarE

3. Table

HTML

<html>
    <body>
        <main></main>
        <footer></footer>
    </body>
</html>

CSS

html {
    height: 100%;
}

body {
    display: table;
    min-height: 100vh;
}

main: {
    height: 100%;
}

footer {
    display: table-row;
    height: 1px;
}

Demo: https://codepen.io/marcobiedermann/pen/jImsc


问:
The name does not exist in current context - How to access it?
In my code i have defined string repeatnumber and assigned it into for loop. However, i need it to be accesible when im creating a button click event. Not sure how to do it. </p>

<p>Can anyone give me some tips? </p>

```<code>   public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        string[] assignments = new string[] { "A", "b", "c", "d", "e", "f" };
        Random rnd = new Random();

        string[] randomingArray = assignments.OrderBy(x => rnd.Next()).ToArray();
        string repeatNumber = "";

        List<ImageSource> animals = new List<ImageSource>();

        for (int i = 1; i < 100; i++)
        {
            if (i == 9)
            {
                repeatNumber = randomingArray[i % randomingArray.Length];
                animals.Add(new ImageSource() { Source = repeatNumber, Number = i });
            }
            else if ((i % 9) == 0)
            {
                animals.Add(new ImageSource() { Source = repeatNumber, Number = i });
            }
            else
            {
                animals.Add(new ImageSource() { Source = randomingArray[i % rnd.Next(1,5)], Number = i });
            }
            ItemsControl1.ItemsSource = animals;
        }
    }

    private void btn1_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("test");
    }
    private void btn2_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show((new ImageSource() { Source = repeatNumber })); <-- the name repeatNumber does not exist in current context
    }
}

class ImageSource
{
    public int Number { get; set; }
    public string Source { get; set; }
}
</code>```

答:
You need to define repeatnumber as a class property

```<code>public partial class MainWindow : Window
{

   private string repeatNumber;

   public MainWindow()
   {
   ...
</code>```

Otherwise it is limited to the scope (<= you want to look that up) of the MainWindow constructor.

Body:
In my code i have defined string repeatnumber and assigned it into for loop. However, i need it to be accesible when im creating a button click event. Not sure how to do it.

Can anyone give me some tips?

   public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        string[] assignments = new string[] { "A", "b", "c", "d", "e", "f" };
        Random rnd = new Random();

        string[] randomingArray = assignments.OrderBy(x => rnd.Next()).ToArray();
        string repeatNumber = "";

        List<ImageSource> animals = new List<ImageSource>();

        for (int i = 1; i < 100; i++)
        {
            if (i == 9)
            {
                repeatNumber = randomingArray[i % randomingArray.Length];
                animals.Add(new ImageSource() { Source = repeatNumber, Number = i });
            }
            else if ((i % 9) == 0)
            {
                animals.Add(new ImageSource() { Source = repeatNumber, Number = i });
            }
            else
            {
                animals.Add(new ImageSource() { Source = randomingArray[i % rnd.Next(1,5)], Number = i });
            }
            ItemsControl1.ItemsSource = animals;
        }
    }

    private void btn1_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("test");
    }
    private void btn2_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show((new ImageSource() { Source = repeatNumber })); <-- the name repeatNumber does not exist in current context
    }
}

class ImageSource
{
    public int Number { get; set; }
    public string Source { get; set; }
}

Body:
You need to define repeatnumber as a class property

public partial class MainWindow : Window
{

   private string repeatNumber;

   public MainWindow()
   {
   ...

Otherwise it is limited to the scope (<= you want to look that up) of the MainWindow constructor.


问:
Using case in a aggregate sql query without splitting rows
In ms-sql i am using an aggregate group to filter results by user, i would also like to use case to filter by a row not contained in the aggregate so all the user results are on 1 line. I'm not sure this is possible.

Here is the query below which splits the results into two lines.

```<code>select case  when col_A='1' then sum(col b) End as Sum1_results,
case  when col_A='2' then sum(col_b) End as Sum2_Results, Username from tbl1
group by Username, col_A
</code>```

example of results is.

```<code>Sum1_results | Sum2_results | Username

 5499          null           John
 null          3400           John
</code>```

Ideally, i would like to just have these results merged into one line for each username if possible.
Any help would be appreciated

答:
You could use:</p>

```<code>select Username ,
     SUM(case when col_A='1' then col_b End) as Sum1_results,
     SUM(case when col_A='2' then col_b End) as Sum2_Results,
from tbl1
group by Username
</code>```

Body:
In ms-sql i am using an aggregate group to filter results by user, i would also like to use case to filter by a row not contained in the aggregate so all the user results are on 1 line. I'm not sure this is possible.

Here is the query below which splits the results into two lines.

select case  when col_A='1' then sum(col b) End as Sum1_results,
case  when col_A='2' then sum(col_b) End as Sum2_Results, Username from tbl1
group by Username, col_A

example of results is.

Sum1_results | Sum2_results | Username

 5499          null           John
 null          3400           John

Ideally, i would like to just have these results merged into one line for each username if possible.
Any help would be appreciated

Body:
You could use:

select Username ,
     SUM(case when col_A='1' then col_b End) as Sum1_results,
     SUM(case when col_A='2' then col_b End) as Sum2_Results,
from tbl1
group by Username


问:
Where Does JQuery/Client-Side Programming Fit Into MVP and DDD
I'm working on an a pretty big project right now and am trying to implement an MVP architecture.  I'm starting to run across a instances where I think JQuery or Javascript might be better suited than server-side code.  I'm looking for feedback on how others are implementing client-side programming into their enterprise applications.  How are you structuring the client-side code and how do you determine when to use it?</p>

答: I guess this question is a little too subjective.  Looks like I'm just going to grab a view books on advanced javascript and study up on the JQuery library.</p>


问:
convert array into proper JSON format for android using PHP
I am using Codeigniter to fetch rows. Please go through the below code.

```<code>//Model

public function selectData() {
    $query = $this->db->query('SELECT * FROM tbl_favourites WHERE favourites_status = 1');
    $count = $query->num_rows();

    if($count > 0)
        return $result = $query->result_array();
    else
        return 0;
}

//Controller

$all_favourites = $this->select->selectData();

if(!empty($all_favourites)) {
    foreach($all_favourites as $favourites)
        echo json_encode($favourites);
}
</code>```

From the above code, the output is

```<code>{"favourite_online_id":"3","favourite_online_url":"ddd","favourite_online_status":"0"}
{"favourite_online_id":"2","favourite_online_url":"http:\/\/www.google.com","favourite_online_status":"0"}
</code>```

But I want the output to be formatted properly to satisfy the android JSON.

The required output is,

```<code>[
  {
    "favourite_online_id": "3",
    "favourite_online_url": "ddd",
    "favourite_online_status": "0"
  },
  {
    "favourite_online_id": "2",
    "favourite_online_url": "http://www.google.com",
    "favourite_online_status": "0"
  }
]
</code>```

答:
You can do in 2 way

1st way

```<code>if(!empty($all_favourites)) {
  echo json_encode($all_favourites);
}
</code>```

2nd way

if you want to add something in that object then

```<code>$favouriteArray=[];
if(!empty($all_favourites)) {
    foreach($all_favourites as $favourites){
      array_push($favouriteArray, $favourites);
    }
}
echo json_encode($favouriteArray);
</code>```

Body:
I am using Codeigniter to fetch rows. Please go through the below code.

//Model

public function selectData() {
    $query = $this->db->query('SELECT * FROM tbl_favourites WHERE favourites_status = 1');
    $count = $query->num_rows();

    if($count > 0)
        return $result = $query->result_array();
    else
        return 0;
}

//Controller

$all_favourites = $this->select->selectData();

if(!empty($all_favourites)) {
    foreach($all_favourites as $favourites)
        echo json_encode($favourites);
}

From the above code, the output is

{"favourite_online_id":"3","favourite_online_url":"ddd","favourite_online_status":"0"}
{"favourite_online_id":"2","favourite_online_url":"http:\/\/www.google.com","favourite_online_status":"0"}

But I want the output to be formatted properly to satisfy the android JSON.

The required output is,

[
  {
    "favourite_online_id": "3",
    "favourite_online_url": "ddd",
    "favourite_online_status": "0"
  },
  {
    "favourite_online_id": "2",
    "favourite_online_url": "http://www.google.com",
    "favourite_online_status": "0"
  }
]

Body:
You can do in 2 way

1st way

if(!empty($all_favourites)) {
  echo json_encode($all_favourites);
}

2nd way

if you want to add something in that object then

$favouriteArray=[];
if(!empty($all_favourites)) {
    foreach($all_favourites as $favourites){
      array_push($favouriteArray, $favourites);
    }
}
echo json_encode($favouriteArray);


问:
Indenting parameters in SSRS
Does anyone know how to indent a parameter name in SSRS 2016?  It looks like it works when I run the report locally, but it doesn't on the server.  I indented it with the space bar.

Local:

Server:

答:
Is this to show it as a sub-parameter of Corporate Entity?  If so, you could use Box Drawing Characters to show your hierarchies:

```<code>Corporate Entity
├─Coordinator
├─Location
└─Practitioners
</code>```

Title: Indenting parameters in SSRS

Body:
Is this to show it as a sub-parameter of Corporate Entity?  If so, you could use Box Drawing Characters to show your hierarchies:

Corporate Entity
├─Coordinator
├─Location
└─Practitioners


问:
Use of Boolean? in if expression
If I have a nullable Boolean b, I can do the following comparison in Java:

```<code>Boolean b = ...;
if (b != null && b) {
   /* Do something */
} else {
   /* Do something else */
}
</code>```

In Kotlin, I can achieve the same by using the !! operator:

```<code>val b: Boolean? = ...
if (b != null && b!!) {
   /* Do something */
} else {
   /* Do something else */
}
</code>```

However, the use of !! feels a bit sketchy to me, circumventing the null safety system.

Is there a more elegant approach for this?

Edit It seems I oversimplicated a bit. For local variables, as Banthar shows, it does work. However, my Boolean b is actually a "property with a backing field" (I'm not really up to speed yet what this imposes). This is the result:

答:
first, add the custom inline function below:

```<code>inline fun Boolean?.ifTrue(block: Boolean.() -> Unit): Boolean? {
    if (this == true) {
        block()
    }
    return this
}

inline fun Boolean?.ifFalse(block: Boolean?.() -> Unit): Boolean? {
    if (null == this || !this) {
        block()
    }

    return this
}
</code>```

then you can write code like this:

```<code>val b: Boolean? = ...
b.ifTrue {
   /* Do something in true case */
}

//or

b.ifFalse {
   /* Do something else in false case */
}
</code>```

Title: Use of Boolean? in if expression

Body:
If I have a nullable Boolean b, I can do the following comparison in Java:

Boolean b = ...;
if (b != null && b) {
   /* Do something */
} else {
   /* Do something else */
}

In Kotlin, I can achieve the same by using the !! operator:

val b: Boolean? = ...
if (b != null && b!!) {
   /* Do something */
} else {
   /* Do something else */
}

However, the use of !! feels a bit sketchy to me, circumventing the null safety system.

Is there a more elegant approach for this?

Edit It seems I oversimplicated a bit. For local variables, as Banthar shows, it does work. However, my Boolean b is actually a "property with a backing field" (I'm not really up to speed yet what this imposes). This is the result:

Body:
first, add the custom inline function below:

inline fun Boolean?.ifTrue(block: Boolean.() -> Unit): Boolean? {
    if (this == true) {
        block()
    }
    return this
}

inline fun Boolean?.ifFalse(block: Boolean?.() -> Unit): Boolean? {
    if (null == this || !this) {
        block()
    }

    return this
}

then you can write code like this:

val b: Boolean? = ...
b.ifTrue {
   /* Do something in true case */
}

//or

b.ifFalse {
   /* Do something else in false case */
}


问:
/cs/software/anaconda3/compiler_compat/ld: cannot find -lm cannot find -lpthread cannot find -lc
How should I fix this error in CentOS 7?</p>

```<code>[jalal@goku HW4]$ git clone https://github.com/pathak22/pyflow.git
Cloning into 'pyflow'...
remote: Counting objects: 96, done.
remote: Total 96 (delta 0), reused 0 (delta 0), pack-reused 96
Unpacking objects: 100% (96/96), done.
[jalal@goku HW4]$ ls
pyflow
[jalal@goku HW4]$ cd pyflow/
[jalal@goku pyflow]$ ls
LICENSE  README.md  demo.py  examples  pyflow.pyx  setup.py  src
[jalal@goku pyflow]$ python demo.py
Traceback (most recent call last):
  File "demo.py", line 11, in <module>
    import pyflow
ImportError: No module named 'pyflow'
[jalal@goku pyflow]$ python setup.py build_ext -i
Compiling pyflow.pyx because it changed.
[1/1] Cythonizing pyflow.pyx
running build_ext
building 'pyflow' extension
creating build
creating build/temp.linux-x86_64-3.5
creating build/temp.linux-x86_64-3.5/src
gcc -pthread -B /cs/software/anaconda3/compiler_compat -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include -I/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include -I/usr/local/anaconda3/include/python3.5m -c pyflow.cpp -o build/temp.linux-x86_64-3.5/pyflow.o
cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++ [enabled by default]
In file included from /usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include/numpy/ndarraytypes.h:1809:0,
                 from /usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include/numpy/ndarrayobject.h:18,
                 from /usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include/numpy/arrayobject.h:4,
                 from pyflow.cpp:564:
/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:15:2: warning: #warning "Using deprecated NumPy API, disable it by " "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-Wcpp]
 #warning "Using deprecated NumPy API, disable it by " \
  ^
gcc -pthread -B /cs/software/anaconda3/compiler_compat -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include -I/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include -I/usr/local/anaconda3/include/python3.5m -c src/Coarse2FineFlowWrapper.cpp -o build/temp.linux-x86_64-3.5/src/Coarse2FineFlowWrapper.o
cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++ [enabled by default]
gcc -pthread -B /cs/software/anaconda3/compiler_compat -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include -I/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include -I/usr/local/anaconda3/include/python3.5m -c src/GaussianPyramid.cpp -o build/temp.linux-x86_64-3.5/src/GaussianPyramid.o
cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++ [enabled by default]
In file included from src/Image.h:9:0,
                 from src/GaussianPyramid.h:7,
                 from src/GaussianPyramid.cpp:4:
src/ImageProcessing.h: In instantiation of ‘static void ImageProcessing::vfiltering(const T1*, T2*, int, int, int, const double*, int) [with T1 = double; T2 = double]’:
src/Image.h:1331:96:   required from ‘void Image<T>::imfilter_hv(Image<T1>&, const double*, int, const double*, int) const [with T1 = double; T = double]’
src/Image.h:1199:47:   required from ‘void Image<T>::GaussianSmoothing(Image<T1>&, double, int) const [with T1 = double; T = double]’
src/GaussianPyramid.cpp:67:45:   required from here
src/ImageProcessing.h:344:14: warning: unused variable ‘offset’ [-Wunused-variable]
  int i,j,l,k,offset,ii;
              ^
gcc -pthread -B /cs/software/anaconda3/compiler_compat -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include -I/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include -I/usr/local/anaconda3/include/python3.5m -c src/OpticalFlow.cpp -o build/temp.linux-x86_64-3.5/src/OpticalFlow.o
cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++ [enabled by default]
src/OpticalFlow.cpp: In static member function ‘static void OpticalFlow::SmoothFlowSOR(const DImage&, const DImage&, DImage&, DImage&, DImage&, double, int, int, int)’:
src/OpticalFlow.cpp:267:11: warning: unused variable ‘power_alpha’ [-Wunused-variable]
    double power_alpha = 0.5;
           ^
src/OpticalFlow.cpp:287:11: warning: unused variable ‘_a’ [-Wunused-variable]
    double _a  = 10000, _b = 0.1;
           ^
src/OpticalFlow.cpp:287:24: warning: unused variable ‘_b’ [-Wunused-variable]
    double _a  = 10000, _b = 0.1;
                        ^
src/OpticalFlow.cpp: In static member function ‘static void OpticalFlow::SmoothFlowPDE(const DImage&, const DImage&, DImage&, DImage&, DImage&, double, int, int, int)’:
src/OpticalFlow.cpp:545:11: warning: unused variable ‘power_alpha’ [-Wunused-variable]
    double power_alpha = 0.5;
           ^
src/OpticalFlow.cpp:565:11: warning: unused variable ‘_a’ [-Wunused-variable]
    double _a  = 10000, _b = 0.1;
           ^
src/OpticalFlow.cpp:565:24: warning: unused variable ‘_b’ [-Wunused-variable]
    double _a  = 10000, _b = 0.1;
                        ^
In file included from src/Image.h:9:0,
                 from src/OpticalFlow.h:6,
                 from src/OpticalFlow.cpp:4:
src/ImageProcessing.h: In instantiation of ‘static void ImageProcessing::vfiltering(const T1*, T2*, int, int, int, const double*, int) [with T1 = double; T2 = double]’:
src/Image.h:1331:96:   required from ‘void Image<T>::imfilter_hv(Image<T1>&, const double*, int, const double*, int) const [with T1 = double; T = double]’
src/OpticalFlow.cpp:52:42:   required from here
src/ImageProcessing.h:344:14: warning: unused variable ‘offset’ [-Wunused-variable]
  int i,j,l,k,offset,ii;
              ^
In file included from src/OpticalFlow.h:6:0,
                 from src/OpticalFlow.cpp:4:
src/Image.h: In instantiation of ‘void Image<T>::warpImageBicubicRef(const Image<T>&, Image<T>&, const Image<T1>&, const Image<T1>&, const Image<T1>&, const Image<T2>&, const Image<T2>&) const [with T1 = double; T2 = double; T = double]’:
src/Image.h:2482:55:   required from ‘void Image<T>::warpImageBicubicRef(const Image<T>&, Image<T>&, const Image<T1>&, const Image<T1>&) const [with T1 = double; T = double]’
src/OpticalFlow.cpp:437:43:   required from here
src/Image.h:2525:4: warning: variable ‘ImgMax’ set but not used [-Wunused-but-set-variable]
  T ImgMax;
    ^
gcc -pthread -B /cs/software/anaconda3/compiler_compat -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include -I/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include -I/usr/local/anaconda3/include/python3.5m -c src/Stochastic.cpp -o build/temp.linux-x86_64-3.5/src/Stochastic.o
cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++ [enabled by default]
g++ -pthread -shared -L/cs/software/anaconda3/lib -B /cs/software/anaconda3/compiler_compat -Wl,-rpath=/cs/software/anaconda3/lib,--no-as-needed build/temp.linux-x86_64-3.5/pyflow.o build/temp.linux-x86_64-3.5/src/Coarse2FineFlowWrapper.o build/temp.linux-x86_64-3.5/src/GaussianPyramid.o build/temp.linux-x86_64-3.5/src/OpticalFlow.o build/temp.linux-x86_64-3.5/src/Stochastic.o -L/cs/software/anaconda3/lib -lpython3.5m -o /home/grad3/jalal/CS585/HW4/pyflow/pyflow.cpython-35m-x86_64-linux-gnu.so
/cs/software/anaconda3/compiler_compat/ld: cannot find -lm
/cs/software/anaconda3/compiler_compat/ld: cannot find -lpthread
/cs/software/anaconda3/compiler_compat/ld: cannot find -lc
collect2: error: ld returned 1 exit status
error: command 'g++' failed with exit status 1
[jalal@goku pyflow]$ uname -a
Linux goku.bu.edu 3.10.0-693.5.2.el7.x86_64 #1 SMP Fri Oct 20 20:32:50 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

[jalal@goku pyflow]$ lsb_release -a
LSB Version:    :core-4.1-amd64:core-4.1-noarch
Distributor ID: CentOS
Description:    CentOS Linux release 7.4.1708 (Core)
Release:    7.4.1708
Codename:   Core
</code>```

答:
You need to install a library. I can't test right now, but running the following command in a terminal should solve the "cannot find -lm /-lc /-lpthread" error:</p>

```<code> sudo yum install glibc-static
</code>```

Body:
How should I fix this error in CentOS 7?

[jalal@goku HW4]$ git clone https://github.com/pathak22/pyflow.git
Cloning into 'pyflow'...
remote: Counting objects: 96, done.
remote: Total 96 (delta 0), reused 0 (delta 0), pack-reused 96
Unpacking objects: 100% (96/96), done.
[jalal@goku HW4]$ ls
pyflow
[jalal@goku HW4]$ cd pyflow/
[jalal@goku pyflow]$ ls
LICENSE  README.md  demo.py  examples  pyflow.pyx  setup.py  src
[jalal@goku pyflow]$ python demo.py
Traceback (most recent call last):
  File "demo.py", line 11, in <module>
    import pyflow
ImportError: No module named 'pyflow'
[jalal@goku pyflow]$ python setup.py build_ext -i
Compiling pyflow.pyx because it changed.
[1/1] Cythonizing pyflow.pyx
running build_ext
building 'pyflow' extension
creating build
creating build/temp.linux-x86_64-3.5
creating build/temp.linux-x86_64-3.5/src
gcc -pthread -B /cs/software/anaconda3/compiler_compat -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include -I/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include -I/usr/local/anaconda3/include/python3.5m -c pyflow.cpp -o build/temp.linux-x86_64-3.5/pyflow.o
cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++ [enabled by default]
In file included from /usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include/numpy/ndarraytypes.h:1809:0,
                 from /usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include/numpy/ndarrayobject.h:18,
                 from /usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include/numpy/arrayobject.h:4,
                 from pyflow.cpp:564:
/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:15:2: warning: #warning "Using deprecated NumPy API, disable it by " "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-Wcpp]
 #warning "Using deprecated NumPy API, disable it by " \
  ^
gcc -pthread -B /cs/software/anaconda3/compiler_compat -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include -I/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include -I/usr/local/anaconda3/include/python3.5m -c src/Coarse2FineFlowWrapper.cpp -o build/temp.linux-x86_64-3.5/src/Coarse2FineFlowWrapper.o
cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++ [enabled by default]
gcc -pthread -B /cs/software/anaconda3/compiler_compat -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include -I/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include -I/usr/local/anaconda3/include/python3.5m -c src/GaussianPyramid.cpp -o build/temp.linux-x86_64-3.5/src/GaussianPyramid.o
cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++ [enabled by default]
In file included from src/Image.h:9:0,
                 from src/GaussianPyramid.h:7,
                 from src/GaussianPyramid.cpp:4:
src/ImageProcessing.h: In instantiation of ‘static void ImageProcessing::vfiltering(const T1*, T2*, int, int, int, const double*, int) [with T1 = double; T2 = double]’:
src/Image.h:1331:96:   required from ‘void Image<T>::imfilter_hv(Image<T1>&, const double*, int, const double*, int) const [with T1 = double; T = double]’
src/Image.h:1199:47:   required from ‘void Image<T>::GaussianSmoothing(Image<T1>&, double, int) const [with T1 = double; T = double]’
src/GaussianPyramid.cpp:67:45:   required from here
src/ImageProcessing.h:344:14: warning: unused variable ‘offset’ [-Wunused-variable]
  int i,j,l,k,offset,ii;
              ^
gcc -pthread -B /cs/software/anaconda3/compiler_compat -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include -I/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include -I/usr/local/anaconda3/include/python3.5m -c src/OpticalFlow.cpp -o build/temp.linux-x86_64-3.5/src/OpticalFlow.o
cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++ [enabled by default]
src/OpticalFlow.cpp: In static member function ‘static void OpticalFlow::SmoothFlowSOR(const DImage&, const DImage&, DImage&, DImage&, DImage&, double, int, int, int)’:
src/OpticalFlow.cpp:267:11: warning: unused variable ‘power_alpha’ [-Wunused-variable]
    double power_alpha = 0.5;
           ^
src/OpticalFlow.cpp:287:11: warning: unused variable ‘_a’ [-Wunused-variable]
    double _a  = 10000, _b = 0.1;
           ^
src/OpticalFlow.cpp:287:24: warning: unused variable ‘_b’ [-Wunused-variable]
    double _a  = 10000, _b = 0.1;
                        ^
src/OpticalFlow.cpp: In static member function ‘static void OpticalFlow::SmoothFlowPDE(const DImage&, const DImage&, DImage&, DImage&, DImage&, double, int, int, int)’:
src/OpticalFlow.cpp:545:11: warning: unused variable ‘power_alpha’ [-Wunused-variable]
    double power_alpha = 0.5;
           ^
src/OpticalFlow.cpp:565:11: warning: unused variable ‘_a’ [-Wunused-variable]
    double _a  = 10000, _b = 0.1;
           ^
src/OpticalFlow.cpp:565:24: warning: unused variable ‘_b’ [-Wunused-variable]
    double _a  = 10000, _b = 0.1;
                        ^
In file included from src/Image.h:9:0,
                 from src/OpticalFlow.h:6,
                 from src/OpticalFlow.cpp:4:
src/ImageProcessing.h: In instantiation of ‘static void ImageProcessing::vfiltering(const T1*, T2*, int, int, int, const double*, int) [with T1 = double; T2 = double]’:
src/Image.h:1331:96:   required from ‘void Image<T>::imfilter_hv(Image<T1>&, const double*, int, const double*, int) const [with T1 = double; T = double]’
src/OpticalFlow.cpp:52:42:   required from here
src/ImageProcessing.h:344:14: warning: unused variable ‘offset’ [-Wunused-variable]
  int i,j,l,k,offset,ii;
              ^
In file included from src/OpticalFlow.h:6:0,
                 from src/OpticalFlow.cpp:4:
src/Image.h: In instantiation of ‘void Image<T>::warpImageBicubicRef(const Image<T>&, Image<T>&, const Image<T1>&, const Image<T1>&, const Image<T1>&, const Image<T2>&, const Image<T2>&) const [with T1 = double; T2 = double; T = double]’:
src/Image.h:2482:55:   required from ‘void Image<T>::warpImageBicubicRef(const Image<T>&, Image<T>&, const Image<T1>&, const Image<T1>&) const [with T1 = double; T = double]’
src/OpticalFlow.cpp:437:43:   required from here
src/Image.h:2525:4: warning: variable ‘ImgMax’ set but not used [-Wunused-but-set-variable]
  T ImgMax;
    ^
gcc -pthread -B /cs/software/anaconda3/compiler_compat -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include -I/usr/local/anaconda3/lib/python3.5/site-packages/numpy/core/include -I/usr/local/anaconda3/include/python3.5m -c src/Stochastic.cpp -o build/temp.linux-x86_64-3.5/src/Stochastic.o
cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++ [enabled by default]
g++ -pthread -shared -L/cs/software/anaconda3/lib -B /cs/software/anaconda3/compiler_compat -Wl,-rpath=/cs/software/anaconda3/lib,--no-as-needed build/temp.linux-x86_64-3.5/pyflow.o build/temp.linux-x86_64-3.5/src/Coarse2FineFlowWrapper.o build/temp.linux-x86_64-3.5/src/GaussianPyramid.o build/temp.linux-x86_64-3.5/src/OpticalFlow.o build/temp.linux-x86_64-3.5/src/Stochastic.o -L/cs/software/anaconda3/lib -lpython3.5m -o /home/grad3/jalal/CS585/HW4/pyflow/pyflow.cpython-35m-x86_64-linux-gnu.so
/cs/software/anaconda3/compiler_compat/ld: cannot find -lm
/cs/software/anaconda3/compiler_compat/ld: cannot find -lpthread
/cs/software/anaconda3/compiler_compat/ld: cannot find -lc
collect2: error: ld returned 1 exit status
error: command 'g++' failed with exit status 1
[jalal@goku pyflow]$ uname -a
Linux goku.bu.edu 3.10.0-693.5.2.el7.x86_64 #1 SMP Fri Oct 20 20:32:50 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

[jalal@goku pyflow]$ lsb_release -a
LSB Version:    :core-4.1-amd64:core-4.1-noarch
Distributor ID: CentOS
Description:    CentOS Linux release 7.4.1708 (Core)
Release:    7.4.1708
Codename:   Core

Body:
You need to install a library. I can't test right now, but running the following command in a terminal should solve the "cannot find -lm /-lc /-lpthread" error:

 sudo yum install glibc-static


问:
thymeleaf th:each not looping
my web is read data from database and show it on table but not working as it should be.

my controller

```<code>public String printWelcome(ModelMap model) {
    model.addAttribute("message", "Hello world!");
    List<User> users = userDAO.getAllUser();
    model.addAttribute("users", users);
    return "hello";
}
</code>```

my view

```<code><!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<body>
    <h1>${message}</h1>
    <h1>${users.get(0).username}</h1>
    <h1>${users.get(1).passw}</h1>
    <table>
        <thead>
        <tr>
            <th>name</th>
            <th>password</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="user : ${users}">
            <td th:text="${user.username}"/>
            <td th:text="${user.passw}"/>
        </tr>
        </tbody>
    </table>
</body>
</html>
</code>```

hello word is appear. also list content of username of first data and password on second data are also appear good. but the table contain loop data is not show up instead showing object on html code

```<code><tr th:each="user : [com.pckg.model.User@414e9cef, com.pckg.model.User@72d57b3c, com.pckg.model.User@2640e7f3, com.pckg.model.User@35ef8cf9, com.pckg.model.User@f3c74f, com.pckg.model.User@592640f6, com.pckg.model.User@78f84b5e, com.pckg.model.User@313998fc]">
    <td th:text=""></td>
    <td th:text=""></td>
</tr>
</code>```

答:
as asked by Sotirios Delimanolis about spring configuration. i tried to figure out and found that the file is mvc-dispatcher-servlet.xml. and it redundant with the java version.

my solution, delete on xml part.

Title: thymeleaf th:each not looping

Body:
my web is read data from database and show it on table but not working as it should be.

my controller

public String printWelcome(ModelMap model) {
    model.addAttribute("message", "Hello world!");
    List<User> users = userDAO.getAllUser();
    model.addAttribute("users", users);
    return "hello";
}

my view

<!DOCTYPE HTML>

${message}

${users.get(0).username}

${users.get(1).passw}

            name
            password

hello word is appear. also list content of username of first data and password on second data are also appear good. but the table contain loop data is not show up instead showing object on html code


问:
How to pass data from one controller to another controller in ONSEN UI angular?
i have a html like below

```<code><a class="event_detail_btn_a" ng-click="foo()"></a>
</code>```

following is my controller

```<code>    onsenApp.controller("EventDetailController", function ($scope) {
        $scope.foo = function(){
            alert("foo!");
            var options = {
                data: {
                    title: 'Another Page'
                }
            };

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

i want to pass "options" variable to another controller from this controller.
how can i do it ?

答:
Use $broadcast to pass data between controllers.

In the example add() is defined in Controller1 which is passed to Controller2 after 2 secs.

angular
  .module("app", [])
  .controller("Controller1", function($scope, $rootScope, $timeout){
    var add = function(a, b) {
      return a + b;
    }

    $timeout(function(){
      $rootScope.$broadcast("Add function", add);
    }, 2000);
  })
  .controller("Controller2", function($scope, $rootScope, $timeout){
    $scope.$on("Add function", function(event, add) {
      $scope.sum = add(3, 4);
    });
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="Controller1">
    <span>Add function defined in Controller1</span><br /><br />
  </div>
  <div ng-controller="Controller2">
    <span ng-show="sum">3 + 4 = {{ sum }}</span>
    <span ng-show="!sum">Controller2 waiting for add function...</span><br />
  </div>
</div></code>```

Body:
i have a html like below

following is my controller

    onsenApp.controller("EventDetailController", function ($scope) {
        $scope.foo = function(){
            alert("foo!");
            var options = {
                data: {
                    title: 'Another Page'
                }
            };

        };
});

i want to pass "options" variable to another controller from this controller.
how can i do it ?

Body:
Use $broadcast to pass data between controllers.

In the example add() is defined in Controller1 which is passed to Controller2 after 2 secs.

angular
  .module("app", [])
  .controller("Controller1", function($scope, $rootScope, $timeout){
    var add = function(a, b) {
      return a + b;
    }

    $timeout(function(){
      $rootScope.$broadcast("Add function", add);
    }, 2000);
  })
  .controller("Controller2", function($scope, $rootScope, $timeout){
    $scope.$on("Add function", function(event, add) {
      $scope.sum = add(3, 4);
    });
  });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="Controller1">
    <span>Add function defined in Controller1</span><br /><br />
  </div>
  <div ng-controller="Controller2">
    <span ng-show="sum">3 + 4 = {{ sum }}</span>
    <span ng-show="!sum">Controller2 waiting for add function...</span><br />
  </div>
</div>


问:
Change default decimal numbers parsing behavior
I am getting the following response of a web service call:

```<code>response = "{\"price\":39.74000000000000198951966012828052043914794921875}"
</code>```

Then I'm parsing it:

```<code>json = JSON.parse(response, {:symboize_names: true})
</code>```

The result is:

```<code>json = {price: 39.74}
</code>```

Then I tried from Rails console to check if it is happening because of JSON library, but simply I got the following result:

```<code>>> data = {:price => 39.74000000000000198951966012828052043914794921875}
{:price=>39.74}
</code>```

So it's default behavior in Rails and I need to change it (on application level) to always parse decimal numbers as BigDecimal instead of float.

Ruby = 2.3.0

Rails = 4.2.4

Can anybody help?

答:
The solution is a hack really, but I couldn't find any better

```<code>response = "{\"price\":39.74000000000000198951966012828052043914794921875}"
transformed_response = response.gsub(/\d+\.\d+/, '"\&"')
hash = JSON.parse(transformed_response , symboize_names: true})
</code>```

The resulting hash will be

```<code>{ price: "39.74000000000000198951966012828052043914794921875" }
</code>```

With which you can do something like this

```<code>hash.tap { |hash| hash[:price] = BigDecimal.new(hash[:price]) }
</code>```

Body:
I am getting the following response of a web service call:

response = "{\"price\":39.74000000000000198951966012828052043914794921875}"

Then I'm parsing it:

json = JSON.parse(response, {:symboize_names: true})

The result is:

json = {price: 39.74}

Then I tried from Rails console to check if it is happening because of JSON library, but simply I got the following result:

>> data = {:price => 39.74000000000000198951966012828052043914794921875}
{:price=>39.74}

So it's default behavior in Rails and I need to change it (on application level) to always parse decimal numbers as BigDecimal instead of float.

Ruby = 2.3.0

Rails = 4.2.4

Can anybody help?

Body:
The solution is a hack really, but I couldn't find any better

response = "{\"price\":39.74000000000000198951966012828052043914794921875}"
transformed_response = response.gsub(/\d+\.\d+/, '"\&"')
hash = JSON.parse(transformed_response , symboize_names: true})

The resulting hash will be

{ price: "39.74000000000000198951966012828052043914794921875" }

With which you can do something like this

hash.tap { |hash| hash[:price] = BigDecimal.new(hash[:price]) }


问:
how to vertical align middle to multiple position absolute child div
I am currently facing a problem to vertical align the multiple position:absolute div to middle. Although I apply width:100% and height:100%, but the elements seems overflow too. Please help me on this. Thank you.

```<code><div class="wrapper">
  <div class="wrapper-inner">
    <div class="section-1">
      <h2>Heading Here</h2>
      <p>Some text here</p>
    </div>
    <div class="section-2">
      <p>Another text here.</p>
      <p>One more time.</p>
    </div>
  </div>
</div>

html,
body {
  width: 100%;
  height: 100%;
}
.wrapper {
  width: 100%;
  height: 100%;
}
.wrapper-inner {
  width: 100%;
  height: 100%;
  position: relative;
}
.section-1 {
  position: absolute;
  left: 20vw;
  width: 40vw;
  background: #ccc;
}
.section-2 {
  position: absolute;
  left: 60vw;
  background: #375642;
  width: 40vw;
}
</code>```

demo: https://codepen.io/rae0724/pen/jamzbX

I can't find a way to make those content at the current position and middle on this full screen height, except top:50% and minus it's height, but it's bad for responsive.

答:
If you need to vertically center all classes starting with section then:

CSS:

```<code>div[class^='section-'], div[class*='section-']{
    position: absolute;
    left: 20vw;
    width: 40vw;
    background: #ccc;
    top: 50%;
    transform: translateY(-50%);
}
</code>```

Adding top and transform values in % should do the trick

Body:
I am currently facing a problem to vertical align the multiple position:absolute div to middle. Although I apply width:100% and height:100%, but the elements seems overflow too. Please help me on this. Thank you.

Heading Here

Some text here

Another text here.

One more time.

html,
body {
  width: 100%;
  height: 100%;
}
.wrapper {
  width: 100%;
  height: 100%;
}
.wrapper-inner {
  width: 100%;
  height: 100%;
  position: relative;
}
.section-1 {
  position: absolute;
  left: 20vw;
  width: 40vw;
  background: #ccc;
}
.section-2 {
  position: absolute;
  left: 60vw;
  background: #375642;
  width: 40vw;
}

demo: https://codepen.io/rae0724/pen/jamzbX

I can't find a way to make those content at the current position and middle on this full screen height, except top:50% and minus it's height, but it's bad for responsive.

Body:
If you need to vertically center all classes starting with section then:

CSS:

div[class^='section-'], div[class*='section-']{
    position: absolute;
    left: 20vw;
    width: 40vw;
    background: #ccc;
    top: 50%;
    transform: translateY(-50%);
}

Adding top and transform values in % should do the trick