问:
Background-image: not showing in CSS
I'm having a problem with getting a background-image to show within a flexbox. Whenever I enter it manually in the HTML it shows the image, however... When I try to load it as background-image: url("imagepath") it won't load.

This is the CSS:

```<code>* {
  box-sizing: border-box;
}

/*Style van overall body*/

body {
  margin: 0;
  background-color: #f3f3f3;
  color: white;
}

/*Style voor h2 tekst*/

h2 {}

/* Style the header */

.header {
  background-color: #999999;
  padding: 50px;
  text-align: center;
}

/* Container for flexboxes */

.row {
  display: -webkit-flex;
  display: flex;
}

.contentrow {
  display: -webkit-flex;
  display: flex;
}

/* 3 middelse columns (Grootte wordt bepaald in html doc (Standaard: Flex-Grow: 4;)) */

.column {
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  padding: 0px;
  text-align: center;
}
.newsboxtop{
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  border: 3px;
  background: url("images/Lightgraydient75x30.png");
  text-align: center;
  height: 30px;
}

.middlemenu {
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  padding: 0px;
  height: 50px;
  text-align: center;
  margin: 0px;
}

/* Container for newsboxes */

.newsrow {
  display: -webkit-flex;
  display: flex;
}

.newsbox {
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  margin-top: 30px;
  margin-left: 30px;
  margin-right: 30px;
  margin-bottom: 30px;
  min-width: 200px;
  height: 225px;
  text-align: center;
  background-color: #999999;

}

/* Style van de footer. */

.footer {
  background-color: #999999;
  padding: 10px;
  text-align: center;
}

/* Zorgt ervoor dat bij het krimpen de flexboxes stapelen i.p.v. naast elkaar blijven staan.*/

@media (max-width: 1280px) {
  .row {
    -webkit-flex-direction: column;
    flex-direction: column;
  }
}

  @media (max-width: 1500px){
  .newsrow {
    -webkit-flex-direction: column;
    flex-direction: column;
  }
}
</code>```

And this is the HTML:

```<code><!DOCTYPE html>
<html lang="en">
<head>
<title>CSS Template</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>

<div class="header">
  <h2>234234</h2>
</div>

<div class="row">
  <div class="column" style="background-color:#444; padding: 10px;">1337 WHEH</div>
  <div class="column" style="background-color:#555; flex-grow: 4;">
    <div class="middlemenu" style="background-color:#777">
      <!--Hier komt menu content-->
    </div>
    <div class="newsrow">
      <div class="newsbox">
        <div class="newsboxtop">
            <!--////////////////////////////////////////////////////-->
            <!-- images/Lightgraydient75x30.png This is for testing -->
            <!--////////////////////////////////////////////////////-->
            asd
        </div>
      </div>
      <div class="newsbox">
        <div class="newsboxtop">
            dfg
        </div>
      </div>
      <div class="newsbox">
        <div class="newsboxtop">
            ghj
        </div>
      </div>
    </div>
  </div>
  <div class="column" style="background-color:#666; padding: 10px;">1337 WHEEEH</div>
</div>
<div class="footer">
  <p>Footer</p>
</div>

</body>
</html>
</code>```

Please let me know if I'm overlooking something, or if I'm using CSS the wrong way, thank you so much.

答:
background-image is working fine, you have to set div height as per your image. check updated snippet below...

* {
  box-sizing: border-box;
}

/*Style van overall body*/

body {
  margin: 0;
  background-color: #f3f3f3;
  color: white;
}

/*Style voor h2 tekst*/

h2 {}

/* Style the header */

.header {
  background-color: #999999;
  padding: 50px;
  text-align: center;
}

/* Container for flexboxes */

.row {
  display: -webkit-flex;
  display: flex;
}

.contentrow {
  display: -webkit-flex;
  display: flex;
}

/* 3 middelse columns (Grootte wordt bepaald in html doc (Standaard: Flex-Grow: 4;)) */

.column {
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  padding: 0px;
  text-align: center;
}
.newsboxtop{
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  border: 3px;
  background: url(https://dummyimage.com/500x800/ff0000/000000.png&text=);
  text-align: center;
  height: 30px;
  background-size: cover;
}

.middlemenu {
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  padding: 0px;
  height: 50px;
  text-align: center;
  margin: 0px;
}

/* Container for newsboxes */

.newsrow {
  display: -webkit-flex;
  display: flex;
}

.newsbox {
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  margin-top: 30px;
  margin-left: 30px;
  margin-right: 30px;
  margin-bottom: 30px;
  min-width: 200px;
  height: 225px;
  text-align: center;
  background-color: #999999;

}

/* Style van de footer. */

.footer {
  background-color: #999999;
  padding: 10px;
  text-align: center;
}

/* Zorgt ervoor dat bij het krimpen de flexboxes stapelen i.p.v. naast elkaar blijven staan.*/

@media (max-width: 1280px) {
  .row {
    -webkit-flex-direction: column;
    flex-direction: column;
  }
}

  @media (max-width: 1500px){
  .newsrow {
    -webkit-flex-direction: column;
    flex-direction: column;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <h2>234234</h2>
</div>

<div class="row">
  <div class="column" style="background-color:#444; padding: 10px;">1337 WHEH</div>
  <div class="column" style="background-color:#555; flex-grow: 4;">
    <div class="middlemenu" style="background-color:#777">
      <!--Hier komt menu content-->
    </div>
    <div class="newsrow">
      <div class="newsbox">
        <div class="newsboxtop">
            <!--////////////////////////////////////////////////////-->
            <!-- images/Lightgraydient75x30.png This is for testing -->
            <!--////////////////////////////////////////////////////-->
            asd
        </div>
      </div>
      <div class="newsbox">
        <div class="newsboxtop">
            dfg
        </div>
      </div>
      <div class="newsbox">
        <div class="newsboxtop">
            ghj
        </div>
      </div>
    </div>
  </div>
  <div class="column" style="background-color:#666; padding: 10px;">1337 WHEEEH</div>
</div>
<div class="footer">
  <p>Footer</p>
</div></code>```

Title: Background-image: not showing in CSS

Body:
I'm having a problem with getting a background-image to show within a flexbox. Whenever I enter it manually in the HTML it shows the image, however... When I try to load it as background-image: url("imagepath") it won't load.

This is the CSS:

* {
  box-sizing: border-box;
}

/*Style van overall body*/

body {
  margin: 0;
  background-color: #f3f3f3;
  color: white;
}

/*Style voor h2 tekst*/

h2 {}

/* Style the header */

.header {
  background-color: #999999;
  padding: 50px;
  text-align: center;
}

/* Container for flexboxes */

.row {
  display: -webkit-flex;
  display: flex;
}

.contentrow {
  display: -webkit-flex;
  display: flex;
}

/* 3 middelse columns (Grootte wordt bepaald in html doc (Standaard: Flex-Grow: 4;)) */

.column {
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  padding: 0px;
  text-align: center;
}
.newsboxtop{
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  border: 3px;
  background: url("images/Lightgraydient75x30.png");
  text-align: center;
  height: 30px;
}

.middlemenu {
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  padding: 0px;
  height: 50px;
  text-align: center;
  margin: 0px;
}

/* Container for newsboxes */

.newsrow {
  display: -webkit-flex;
  display: flex;
}

.newsbox {
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  margin-top: 30px;
  margin-left: 30px;
  margin-right: 30px;
  margin-bottom: 30px;
  min-width: 200px;
  height: 225px;
  text-align: center;
  background-color: #999999;

}

/* Style van de footer. */

.footer {
  background-color: #999999;
  padding: 10px;
  text-align: center;
}

/* Zorgt ervoor dat bij het krimpen de flexboxes stapelen i.p.v. naast elkaar blijven staan.*/

@media (max-width: 1280px) {
  .row {
    -webkit-flex-direction: column;
    flex-direction: column;
  }
}

  @media (max-width: 1500px){
  .newsrow {
    -webkit-flex-direction: column;
    flex-direction: column;
  }
}

And this is the HTML:

<!DOCTYPE html>

<title>CSS Template</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css/style.css">

234234

1337 WHEH

            asd

            dfg

            ghj

1337 WHEEEH

Footer

Please let me know if I'm overlooking something, or if I'm using CSS the wrong way, thank you so much.

Body:
background-image is working fine, you have to set div height as per your image. check updated snippet below...

* {
  box-sizing: border-box;
}

/*Style van overall body*/

body {
  margin: 0;
  background-color: #f3f3f3;
  color: white;
}

/*Style voor h2 tekst*/

h2 {}

/* Style the header */

.header {
  background-color: #999999;
  padding: 50px;
  text-align: center;
}

/* Container for flexboxes */

.row {
  display: -webkit-flex;
  display: flex;
}

.contentrow {
  display: -webkit-flex;
  display: flex;
}

/* 3 middelse columns (Grootte wordt bepaald in html doc (Standaard: Flex-Grow: 4;)) */

.column {
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  padding: 0px;
  text-align: center;
}
.newsboxtop{
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  border: 3px;
  background: url(https://dummyimage.com/500x800/ff0000/000000.png&text=);
  text-align: center;
  height: 30px;
  background-size: cover;
}

.middlemenu {
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  padding: 0px;
  height: 50px;
  text-align: center;
  margin: 0px;
}

/* Container for newsboxes */

.newsrow {
  display: -webkit-flex;
  display: flex;
}

.newsbox {
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  margin-top: 30px;
  margin-left: 30px;
  margin-right: 30px;
  margin-bottom: 30px;
  min-width: 200px;
  height: 225px;
  text-align: center;
  background-color: #999999;

}

/* Style van de footer. */

.footer {
  background-color: #999999;
  padding: 10px;
  text-align: center;
}

/* Zorgt ervoor dat bij het krimpen de flexboxes stapelen i.p.v. naast elkaar blijven staan.*/

@media (max-width: 1280px) {
  .row {
    -webkit-flex-direction: column;
    flex-direction: column;
  }
}

  @media (max-width: 1500px){
  .newsrow {
    -webkit-flex-direction: column;
    flex-direction: column;
  }
}

<div class="header">
  <h2>234234</h2>
</div>

<div class="row">
  <div class="column" style="background-color:#444; padding: 10px;">1337 WHEH</div>
  <div class="column" style="background-color:#555; flex-grow: 4;">
    <div class="middlemenu" style="background-color:#777">
      <!--Hier komt menu content-->
    </div>
    <div class="newsrow">
      <div class="newsbox">
        <div class="newsboxtop">
            <!--////////////////////////////////////////////////////-->
            <!-- images/Lightgraydient75x30.png This is for testing -->
            <!--////////////////////////////////////////////////////-->
            asd
        </div>
      </div>
      <div class="newsbox">
        <div class="newsboxtop">
            dfg
        </div>
      </div>
      <div class="newsbox">
        <div class="newsboxtop">
            ghj
        </div>
      </div>
    </div>
  </div>
  <div class="column" style="background-color:#666; padding: 10px;">1337 WHEEEH</div>
</div>
<div class="footer">
  <p>Footer</p>
</div>


来源: stackexchange

问:
How can I create a string from a single character?
I have a single char value, and I need to cast/convert it to a std::string. How can I do this?

I know how to go the opposite way, to retrieve a char from a std::string object: you just need to index the string at the appropriate location. For example: str[0] will retrieve the first character in the string.

But how do I go the other way? I want something like:

```<code>char c = 34;
std::string s(c);
</code>```

…but this doesn't work (the string is always empty).

答:
std::string has a constructor that takes a number and a character.  The character will repeat for the given number of times.  Thus, you should use:

```<code>std::string str(1, ch);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a single char value, and I need to cast/convert it to a std::string. How can I do this?

I know how to go the opposite way, to retrieve a char from a std::string object: you just need to index the string at the appropriate location. For example: str[0] will retrieve the first character in the string.

But how do I go the other way? I want something like:

char c = 34;
std::string s(c);

…but this doesn't work (the string is always empty).

Body:
std::string has a constructor that takes a number and a character.  The character will repeat for the given number of times.  Thus, you should use:

std::string str(1, ch);

ContentLicense: CC BY-SA 2.5


问:
mongoose populate pass found object reference key
I have a mongoose Group schema which contains invitee (array of sub document) and currentMove, invitee also contains currentMove and I want to get document with only sub document that have same currentMove.

```<code>Group.findById("5a03fa29fafa645c8a399353")
.populate({
    path: 'invitee.user_id',
    select: 'currentMove',
    model:"User",
     match: {
         "currentMove":{
            $eq: "$currentMove"
        }
    }
})
</code>```

This generates unknown currentMove Object id for match query. I'm not sure if mongoose has this functionality. Can anyone help me, please?

答:
In modern MongoDB releases it is far more efficient to use $lookup here instead of .populate(). Also the basic concept that you want to filter based on a comparison of fields is something that MongoDB does quite well with native operators, but it's not something you can easily transpose into .populate().

In fact the only way possible to actually use with .populate() would be to first retrieve all results, and then use Model.populate() with a $where clause on query all whilst processing the result array with Array.map() in order to apply the local value of each document to the conditions to "join" on.

It's all kind of messy, and involves pulling all results from the server and filtering locally. So $lookup is our best option here, where all of the "filtering" and "matching" actually takes place on the server without needing to pull unnecessary documents over the network just to obtain a result.

Sample Schema

You don't actually include a "schema" in your question, so we can only work with an approximation based on what parts you actually do include in the question. So my example here uses:

```<code>const userSchema = new Schema({
  name: String,
  currentMove: Number
})

const groupSchema = new Schema({
  name: String,
  topic: String,
  currentMove: Number,
  invitee: [{
    user_id: { type: Schema.Types.ObjectId, ref: 'User' },
    confirmed: { type: Boolean, default: false }
  }]
});
</code>```

Unwinding $lookup and $group

From here we have different approaches to the $lookup queries. The first basically involves applying $unwind both before and after the $lookup stage. This is partly since your "reference" is an embedded field within the array, and also partly because it's actually the most efficient query form to use here with a possible "join" result that could potentially exceed the BSON limit ( 16MB for the document ) being avoided:

```<code>  Group.aggregate([
    { "$unwind": "$invitee" },
    { "$lookup": {
      "from": User.collection.name,
      "localField": "invitee.user_id",
      "foreignField": "_id",
      "as": "invitee.user_id"
    }},
    { "$unwind": "$invitee.user_id" },
    { "$redact": {
      "$cond": {
        "if": { "$eq": ["$currentMove", "$invitee.user_id.currentMove"] },
        "then": "$$KEEP",
        "else": "$$PRUNE"
      }
    }},
    { "$group": {
      "_id": "$_id",
      "name": { "$first": "$name" },
      "topic": { "$first": "$topic" },
      "currentMove": { "$first": "$currentMove" },
      "invitee": { "$push": "$invitee" }
    }}
  ]);
</code>```

The key expression here is the $redact which is processed after the $lookup result is returned. This allows a logical comparison of the "currentMove" values from both the parent document and the "joined" detail for the User objects.

Since we $unwind the array content, we use $group with $push to reconstruct the array ( if you must ) and select the other fields of the original document using $first.

There are ways to examine the schema and generate such a stage, but that's not really in the scope of the question. An example can be seen on Querying after populate in Mongoose. Point being that if you want the fields returned, then you would construct this pipeline stage around using those expressions to return a document of the original shape.

Filter $lookup result

An alternate approach where you are certain that the "unfiltered" result of the "join" will not cause the document to exceed the BSON limit is to instead make a separate target array, and then reconstruct your "joined" array content using $map and $filter, and other array operators:

```<code>  Group.aggregate([
    { "$lookup": {
      "from": User.collection.name,
      "localField": "invitee.user_id",
      "foreignField": "_id",
      "as": "inviteeT"
    }},
    { "$addFields": {
      "invitee": {
        "$map": {
          "input": {
            "$filter": {
              "input": "$inviteeT",
              "as": "i",
              "cond": { "$eq": ["$$i.currentMove","$currentMove"] }
            }
          },
          "as": "i",
          "in": {
            "_id": {
              "$arrayElemAt": [
                "$invitee._id",
                { "$indexOfArray": ["$invitee.user_id", "$$i._id"] }
              ]
            },
            "user_id": "$$i",
            "confirmed": {
              "$arrayElemAt": [
                "$invitee.confirmed",
                { "$indexOfArray": ["$invitee.user_id","$$i._id"] }
              ]
            }
          }
        }
      }
    }},
    { "$project": { "inviteeT": 0 } },
    { "$match": { "invitee.0": { "$exists": true } } }
  ]);
</code>```

Instead of the $redact which would be filtering "documents", we use $filter here with the expression to only return those members of the target array "inviteeT" which share the same "currentMove". Since this is just the "foreign" content, we "join" with the original array using $map and transposing the elements.

To do that "transposition" of values from the original array, we use the $arrayElemAt and $indexOfArray expressions. The $indexOfArray allows us to match up the target's "_id" values with the "user_id" values in the original array and get it's "index" position. We always know this returns a real match because the $lookup did that part for us.

The "index" value is then supplied to $arrayElemAt which similarly applies a "mapping" of the values as an array like "$invitee.confirmed" and returns the value matched at the same index. This is basically a "lookup" between the arrays.

Differing from the first pipeline example, we now still have the "inviteeT" array as well as our re-written "invitee" array courtesy of $addFields. So one way to get rid of that is to add an additional $project and exclude the unwanted "temporary" array. And of course since we did not $unwind and "filter", there are still possible results with no matching array entries at all. So the $match expression uses $exists to test for the 0 index being present in the array result, which means there is "at least one" result, and discards any documents with empty arrays.

MongoDB 3.6 "sub-query"

MongoDB 3.6 makes this a bit cleaner as a new syntax for $lookup allows a more expressive "pipeline" to be given in argument to select the results returned, rather than the simplistic "localField" and "foreignField" matching.

```<code>  Group.aggregate([
    { "$lookup": {
      "from": User.collection.name,
      "let": {
        "ids": "$invitee._id",
        "users": "$invitee.user_id",
        "confirmed": "$invitee.confirmed",
        "currentMove": "$currentMove"
      },
      "pipeline": [
        { "$match": {
          "$expr": {
            "$and": [
              { "$in": ["$_id", "$$users"] },
              { "$eq": ["$currentMove", "$$currentMove"] }
            ]
          }
        }},
        { "$project": {
          "_id": {
            "$arrayElemAt": [
              "$$ids",
              { "$indexOfArray": ["$$users", "$_id"] }
            ]
          },
          "user_id": "$$ROOT",
          "confirmed": {
            "$arrayElemAt": [
              "$$confirmed",
              { "$indexOfArray": ["$$users", "$_id"] }
            ]
          }
        }}
      ],
      "as": "invitee"
    }},
    { "$match": { "invitee.0": { "$exists": true } } }
  ])
</code>```

So there are some slightly "glitchy" things in there with the usage of mapping arrays of specific values for input due to how these are currently passed into the sub-pipeline via the "let" declaration. This should probably work cleaner, but on the current release candidate this is how it's actually required to be expressed in order to work.

With this new syntax the "let" allows us to declare "variables" from the current document which can then be referenced in the "pipeline" expression which will be executed in order to determine which results to return to the target array.

The $expr here essentially replaces the $redact or $filter conditions used before, as well as combining the "local" to "foreign" key matching which also requires us to declare such a variable. Here we mapped the "$invitee.user_id" values from the source document into a variable which we refer to as "$$users" in the rest of the expressions.

The $in operator here is a variant for the aggregation framework which returns a boolean condition where the first argument "value" is found in the second argument "array". So this is the "foreign key" filter part.

Since this is a "pipeline", we can add a $project stage in addition to the $match which selected the items from the foreign collection. So again we use a similar "transposition" technique to what was described before. This then gives us control of the "shape" of the documents returned in the array, so we don't manipulate the returned array "after" the $lookup like we did previously.

The same case applies though, since no matter what you do here the "sub-pipeline" can of course return no results when the filter conditions do not match. So again the same $exists test is used to discard those documents.

So it's all pretty cool, and once you get used to the power available in the server side "join" functionality of $lookup you likely will never look back. Whilst the syntax is a lot more terse than the "convenience" function that .populate() was introduced for, the reduced traffic load, far more advanced uses and general expressiveness basically make up for that.

As a complete example, I'm also including a self contained listing that demonstrates all of these. And if you run it with a MongoDB 3.6 compatible server attached, then you will even get that demonstration as well.

Needs a recent Node.js v8.x release to run with async/await ( or enable in other supported ), but since that's now the LTS release you really should be running that anyway. At least install one to test :)

```<code>const mongoose = require('mongoose'),
      Schema = mongoose.Schema;

mongoose.Promise = global.Promise;
mongoose.set('debug',true);

const uri = 'mongodb://localhost/rollgroup',
      options = { useMongoClient: true };

const userSchema = new Schema({
  name: String,
  currentMove: Number
})

const groupSchema = new Schema({
  name: String,
  topic: String,
  currentMove: Number,
  invitee: [{
    user_id: { type: Schema.Types.ObjectId, ref: 'User' },
    confirmed: { type: Boolean, default: false }
  }]
});

const User = mongoose.model('User', userSchema);
const Group = mongoose.model('Group', groupSchema);

function log(data) {
  console.log(JSON.stringify(data, undefined, 2))
}

(async function() {

  try {

    const conn = await mongoose.connect(uri,options);

    let { version } = await conn.db.admin().command({'buildInfo': 1});

    // Clean data
    await Promise.all(
      Object.entries(conn.models).map(([k,m]) => m.remove() )
    );

    // Add some users
    let users = await User.insertMany([
      { name: 'Bill', currentMove: 1 },
      { name: 'Ted', currentMove: 2 },
      { name: 'Fred', currentMove: 3 },
      { name: 'Sally', currentMove: 4 },
      { name: 'Harry', currentMove: 5 }
    ]);

    await Group.create({
      name: 'Group1',
      topic: 'This stuff',
      currentMove: 3,
      invitee: users.map( u =>
        ({ user_id: u._id, confirmed: (u.currentMove === 3) })
      )
    });

    await (async function() {
      console.log('Unwinding example');
      let result = await Group.aggregate([
        { "$unwind": "$invitee" },
        { "$lookup": {
          "from": User.collection.name,
          "localField": "invitee.user_id",
          "foreignField": "_id",
          "as": "invitee.user_id"
        }},
        { "$unwind": "$invitee.user_id" },
        { "$redact": {
          "$cond": {
            "if": { "$eq": ["$currentMove", "$invitee.user_id.currentMove"] },
            "then": "$$KEEP",
            "else": "$$PRUNE"
          }
        }},
        { "$group": {
          "_id": "$_id",
          "name": { "$first": "$name" },
          "topic": { "$first": "$topic" },
          "currentMove": { "$first": "$currentMove" },
          "invitee": { "$push": "$invitee" }
        }}
      ]);

      log(result);

    })();

    await (async function() {
      console.log('Using $filter example');
      let result = await Group.aggregate([
        { "$lookup": {
          "from": User.collection.name,
          "localField": "invitee.user_id",
          "foreignField": "_id",
          "as": "inviteeT"
        }},
        { "$addFields": {
          "invitee": {
            "$map": {
              "input": {
                "$filter": {
                  "input": "$inviteeT",
                  "as": "i",
                  "cond": { "$eq": ["$$i.currentMove","$currentMove"] }
                }
              },
              "as": "i",
              "in": {
                "_id": {
                  "$arrayElemAt": [
                    "$invitee._id",
                    { "$indexOfArray": ["$invitee.user_id", "$$i._id"] }
                  ]
                },
                "user_id": "$$i",
                "confirmed": {
                  "$arrayElemAt": [
                    "$invitee.confirmed",
                    { "$indexOfArray": ["$invitee.user_id","$$i._id"] }
                  ]
                }
              }
            }
          }
        }},
        { "$project": { "inviteeT": 0 } },
        { "$match": { "invitee.0": { "$exists": true } } }
      ]);

      log(result);

    })();

    await (async function() {
      if (parseFloat(version.match(/\d\.\d/)[0]) >= 3.6) {
        console.log('New $lookup example. Yay!');
        let result = await Group.collection.aggregate([
          { "$lookup": {
            "from": User.collection.name,
            "let": {
              "ids": "$invitee._id",
              "users": "$invitee.user_id",
              "confirmed": "$invitee.confirmed",
              "currentMove": "$currentMove"
            },
            "pipeline": [
              { "$match": {
                "$expr": {
                  "$and": [
                    { "$in": ["$_id", "$$users"] },
                    { "$eq": ["$currentMove", "$$currentMove"] }
                  ]
                }
              }},
              { "$project": {
                "_id": {
                  "$arrayElemAt": [
                    "$$ids",
                    { "$indexOfArray": ["$$users", "$_id"] }
                  ]
                },
                "user_id": "$$ROOT",
                "confirmed": {
                  "$arrayElemAt": [
                    "$$confirmed",
                    { "$indexOfArray": ["$$users", "$_id"] }
                  ]
                }
              }}
            ],
            "as": "invitee"
          }},
          { "$match": { "invitee.0": { "$exists": true } } }
        ]).toArray();

        log(result);

      }
    })();

    await (async function() {
      console.log("Horrible populate example :(");

      let results = await Group.find();

       results = await Promise.all(
        results.map( r =>
          User.populate(r,{
            path: 'invitee.user_id',
            match: { "$where": `this.currentMove === ${r.currentMove}` }
          })
        )
      );

      console.log("All members still there");
      log(results);

      // Then we clean it for null values

      results = results.map( r =>
        Object.assign(r,{
          invitee: r.invitee.filter(i => i.user_id !== null)
        })
      );

      console.log("Now they are filtered");
      log(results);

    })();

  } catch(e) {
    console.error(e);
  } finally {
    mongoose.disconnect();
  }

})()
</code>```

Gives the output for each example as:

```<code>Mongoose: users.remove({}, {})
Mongoose: groups.remove({}, {})
Mongoose: users.insertMany([ { __v: 0, name: 'Bill', currentMove: 1, _id: 5a0afda01643cf41789e500a }, { __v: 0, name: 'Ted', currentMove: 2, _id: 5a0afda01643cf41789e500b }, { __v: 0, name: 'Fred', currentMove: 3, _id: 5a0afda01643cf41789e500c }, { __v: 0, name: 'Sally', currentMove: 4, _id: 5a0afda01643cf41789e500d }, { __v: 0, name: 'Harry', currentMove: 5, _id: 5a0afda01643cf41789e500e } ], {})
Mongoose: groups.insert({ name: 'Group1', topic: 'This stuff', currentMove: 3, _id: ObjectId("5a0afda01643cf41789e500f"), invitee: [ { user_id: ObjectId("5a0afda01643cf41789e500a"), _id: ObjectId("5a0afda01643cf41789e5014"), confirmed: false }, { user_id: ObjectId("5a0afda01643cf41789e500b"), _id: ObjectId("5a0afda01643cf41789e5013"), confirmed: false }, { user_id: ObjectId("5a0afda01643cf41789e500c"), _id: ObjectId("5a0afda01643cf41789e5012"), confirmed: true }, { user_id: ObjectId("5a0afda01643cf41789e500d"), _id: ObjectId("5a0afda01643cf41789e5011"), confirmed: false }, { user_id: ObjectId("5a0afda01643cf41789e500e"), _id: ObjectId("5a0afda01643cf41789e5010"), confirmed: false } ], __v: 0 })
Unwinding example
Mongoose: groups.aggregate([ { '$unwind': '$invitee' }, { '$lookup': { from: 'users', localField: 'invitee.user_id', foreignField: '_id', as: 'invitee.user_id' } }, { '$unwind': '$invitee.user_id' }, { '$redact': { '$cond': { if: { '$eq': [ '$currentMove', '$invitee.user_id.currentMove' ] }, then: '$$KEEP', else: '$$PRUNE' } } }, { '$group': { _id: '$_id', name: { '$first': '$name' }, topic: { '$first': '$topic' }, currentMove: { '$first': '$currentMove' }, invitee: { '$push': '$invitee' } } } ], {})
[
  {
    "_id": "5a0afda01643cf41789e500f",
    "name": "Group1",
    "topic": "This stuff",
    "currentMove": 3,
    "invitee": [
      {
        "user_id": {
          "_id": "5a0afda01643cf41789e500c",
          "__v": 0,
          "name": "Fred",
          "currentMove": 3
        },
        "_id": "5a0afda01643cf41789e5012",
        "confirmed": true
      }
    ]
  }
]
Using $filter example
Mongoose: groups.aggregate([ { '$lookup': { from: 'users', localField: 'invitee.user_id', foreignField: '_id', as: 'inviteeT' } }, { '$addFields': { invitee: { '$map': { input: { '$filter': { input: '$inviteeT', as: 'i', cond: { '$eq': [ '$$i.currentMove', '$currentMove' ] } } }, as: 'i', in: { _id: { '$arrayElemAt': [ '$invitee._id', { '$indexOfArray': [ '$invitee.user_id', '$$i._id' ] } ] }, user_id: '$$i', confirmed: { '$arrayElemAt': [ '$invitee.confirmed', { '$indexOfArray': [ '$invitee.user_id', '$$i._id' ] } ] } } } } } }, { '$project': { inviteeT: 0 } }, { '$match': { 'invitee.0': { '$exists': true } } } ], {})
[
  {
    "_id": "5a0afda01643cf41789e500f",
    "name": "Group1",
    "topic": "This stuff",
    "currentMove": 3,
    "invitee": [
      {
        "_id": "5a0afda01643cf41789e5012",
        "user_id": {
          "_id": "5a0afda01643cf41789e500c",
          "__v": 0,
          "name": "Fred",
          "currentMove": 3
        },
        "confirmed": true
      }
    ],
    "__v": 0
  }
]
New $lookup example. Yay!
Mongoose: groups.aggregate([ { '$lookup': { from: 'users', let: { ids: '$invitee._id', users: '$invitee.user_id', confirmed: '$invitee.confirmed', currentMove: '$currentMove' }, pipeline: [ { '$match': { '$expr': { '$and': [ { '$in': [ '$_id', '$$users' ] }, { '$eq': [ '$currentMove', '$$currentMove' ] } ] } } }, { '$project': { _id: { '$arrayElemAt': [ '$$ids', { '$indexOfArray': [ '$$users', '$_id' ] } ] }, user_id: '$$ROOT', confirmed: { '$arrayElemAt': [ '$$confirmed', { '$indexOfArray': [ '$$users', '$_id' ] } ] } } } ], as: 'invitee' } }, { '$match': { 'invitee.0': { '$exists': true } } } ])
[
  {
    "_id": "5a0afda01643cf41789e500f",
    "name": "Group1",
    "topic": "This stuff",
    "currentMove": 3,
    "invitee": [
      {
        "_id": "5a0afda01643cf41789e5012",
        "user_id": {
          "_id": "5a0afda01643cf41789e500c",
          "__v": 0,
          "name": "Fred",
          "currentMove": 3
        },
        "confirmed": true
      }
    ],
    "__v": 0
  }
]
Horrible populate example :(
Mongoose: groups.find({}, { fields: {} })
Mongoose: users.find({ _id: { '$in': [ ObjectId("5a0afda01643cf41789e500a"), ObjectId("5a0afda01643cf41789e500b"), ObjectId("5a0afda01643cf41789e500c"), ObjectId("5a0afda01643cf41789e500d"), ObjectId("5a0afda01643cf41789e500e") ] }, '$where': 'this.currentMove === 3' }, { fields: {} })
All members still there
[
  {
    "_id": "5a0afda01643cf41789e500f",
    "name": "Group1",
    "topic": "This stuff",
    "currentMove": 3,
    "__v": 0,
    "invitee": [
      {
        "user_id": null,
        "_id": "5a0afda01643cf41789e5014",
        "confirmed": false
      },
      {
        "user_id": null,
        "_id": "5a0afda01643cf41789e5013",
        "confirmed": false
      },
      {
        "user_id": {
          "_id": "5a0afda01643cf41789e500c",
          "__v": 0,
          "name": "Fred",
          "currentMove": 3
        },
        "_id": "5a0afda01643cf41789e5012",
        "confirmed": true
      },
      {
        "user_id": null,
        "_id": "5a0afda01643cf41789e5011",
        "confirmed": false
      },
      {
        "user_id": null,
        "_id": "5a0afda01643cf41789e5010",
        "confirmed": false
      }
    ]
  }
]
Now they are filtered
[
  {
    "_id": "5a0afda01643cf41789e500f",
    "name": "Group1",
    "topic": "This stuff",
    "currentMove": 3,
    "__v": 0,
    "invitee": [
      {
        "user_id": {
          "_id": "5a0afda01643cf41789e500c",
          "__v": 0,
          "name": "Fred",
          "currentMove": 3
        },
        "_id": "5a0afda01643cf41789e5012",
        "confirmed": true
      }
    ]
  }
]
</code>```

Using populate()

So using .populate() here is actually pretty horrible. Sure it looks like less, but it's actually doing a lot of things that simply are not needed, and all because the "join" does not happen on the server:

```<code>   // Note that we cannot populate "here" since we need the returned value
   let results = await Group.find();

   // The value is only in context as we use `Array.map()` to process each result
   results = await Promise.all(
    results.map( r =>
      User.populate(r,{
        path: 'invitee.user_id',
        match: { "$where": `this.currentMove === ${r.currentMove}` }
      })
    )
  );

  console.log("All members still there");
  log(results);

  // Then we clean it for null values

  results = results.map( r =>
    Object.assign(r,{
      invitee: r.invitee.filter(i => i.user_id !== null)
    })
  );

  console.log("Now they are filtered");
  log(results);
</code>```

So I also included that in the output above, as well as the whole code listing.

The problem becomes evident as you cannot "chain" the populate directly to the first query. You actually need to return the documents ( potentially ALL of them ) in order to use the current document value in a subsequent populate. And this MUST be processed for each document returned.

Not only that but populate() is NOT going to "filter" the array to only those which match, even with the query condition. All it does is set's the unmatched elements to null:

```<code>[
  {
    "_id": "5a0afa889f9f7e4064d8794d",
    "name": "Group1",
    "topic": "This stuff",
    "currentMove": 3,
    "__v": 0,
    "invitee": [
      {
        "user_id": null,
        "_id": "5a0afa889f9f7e4064d87952",
        "confirmed": false
      },
      {
        "user_id": null,
        "_id": "5a0afa889f9f7e4064d87951",
        "confirmed": false
      },
      {
        "user_id": {
          "_id": "5a0afa889f9f7e4064d8794a",
          "__v": 0,
          "name": "Fred",
          "currentMove": 3
        },
        "_id": "5a0afa889f9f7e4064d87950",
        "confirmed": true
      },
      {
        "user_id": null,
        "_id": "5a0afa889f9f7e4064d8794f",
        "confirmed": false
      },
      {
        "user_id": null,
        "_id": "5a0afa889f9f7e4064d8794e",
        "confirmed": false
      }
    ]
  }
]
</code>```

This then needs an Array.filter() to be processed again for "each" document returned, which can finally remove the unwanted array items and give you the same result the other aggregation queries are doing.

So it's "really wasteful" and just not a good way to do things. Little point in having a database, when you're actually doing the majority of processing on the server. In fact, we may have well simply returned the populated result and then run an Array.filter() in order to remove the unwanted entries.

This is just not how you write fast and effective code. So the example here is sometimes "what looks simple" is actually doing a lot more damage than good.

ContentLicense: CC BY-SA 3.0

Body:
I have a mongoose Group schema which contains invitee (array of sub document) and currentMove, invitee also contains currentMove and I want to get document with only sub document that have same currentMove.

Group.findById("5a03fa29fafa645c8a399353")
.populate({
    path: 'invitee.user_id',
    select: 'currentMove',
    model:"User",
     match: {
         "currentMove":{
            $eq: "$currentMove"
        }
    }
})

This generates unknown currentMove Object id for match query. I'm not sure if mongoose has this functionality. Can anyone help me, please?

Body:
In modern MongoDB releases it is far more efficient to use $lookup here instead of .populate(). Also the basic concept that you want to filter based on a comparison of fields is something that MongoDB does quite well with native operators, but it's not something you can easily transpose into .populate().

In fact the only way possible to actually use with .populate() would be to first retrieve all results, and then use Model.populate() with a $where clause on query all whilst processing the result array with Array.map() in order to apply the local value of each document to the conditions to "join" on.

It's all kind of messy, and involves pulling all results from the server and filtering locally. So $lookup is our best option here, where all of the "filtering" and "matching" actually takes place on the server without needing to pull unnecessary documents over the network just to obtain a result.

Sample Schema

You don't actually include a "schema" in your question, so we can only work with an approximation based on what parts you actually do include in the question. So my example here uses:

const userSchema = new Schema({
  name: String,
  currentMove: Number
})

const groupSchema = new Schema({
  name: String,
  topic: String,
  currentMove: Number,
  invitee: [{
    user_id: { type: Schema.Types.ObjectId, ref: 'User' },
    confirmed: { type: Boolean, default: false }
  }]
});

Unwinding $lookup and $group

From here we have different approaches to the $lookup queries. The first basically involves applying $unwind both before and after the $lookup stage. This is partly since your "reference" is an embedded field within the array, and also partly because it's actually the most efficient query form to use here with a possible "join" result that could potentially exceed the BSON limit ( 16MB for the document ) being avoided:

  Group.aggregate([
    { "$unwind": "$invitee" },
    { "$lookup": {
      "from": User.collection.name,
      "localField": "invitee.user_id",
      "foreignField": "_id",
      "as": "invitee.user_id"
    }},
    { "$unwind": "$invitee.user_id" },
    { "$redact": {
      "$cond": {
        "if": { "$eq": ["$currentMove", "$invitee.user_id.currentMove"] },
        "then": "$$KEEP",
        "else": "$$PRUNE"
      }
    }},
    { "$group": {
      "_id": "$_id",
      "name": { "$first": "$name" },
      "topic": { "$first": "$topic" },
      "currentMove": { "$first": "$currentMove" },
      "invitee": { "$push": "$invitee" }
    }}
  ]);

The key expression here is the $redact which is processed after the $lookup result is returned. This allows a logical comparison of the "currentMove" values from both the parent document and the "joined" detail for the User objects.

Since we $unwind the array content, we use $group with $push to reconstruct the array ( if you must ) and select the other fields of the original document using $first.

There are ways to examine the schema and generate such a stage, but that's not really in the scope of the question. An example can be seen on Querying after populate in Mongoose. Point being that if you want the fields returned, then you would construct this pipeline stage around using those expressions to return a document of the original shape.

Filter $lookup result

An alternate approach where you are certain that the "unfiltered" result of the "join" will not cause the document to exceed the BSON limit is to instead make a separate target array, and then reconstruct your "joined" array content using $map and $filter, and other array operators:

  Group.aggregate([
    { "$lookup": {
      "from": User.collection.name,
      "localField": "invitee.user_id",
      "foreignField": "_id",
      "as": "inviteeT"
    }},
    { "$addFields": {
      "invitee": {
        "$map": {
          "input": {
            "$filter": {
              "input": "$inviteeT",
              "as": "i",
              "cond": { "$eq": ["$$i.currentMove","$currentMove"] }
            }
          },
          "as": "i",
          "in": {
            "_id": {
              "$arrayElemAt": [
                "$invitee._id",
                { "$indexOfArray": ["$invitee.user_id", "$$i._id"] }
              ]
            },
            "user_id": "$$i",
            "confirmed": {
              "$arrayElemAt": [
                "$invitee.confirmed",
                { "$indexOfArray": ["$invitee.user_id","$$i._id"] }
              ]
            }
          }
        }
      }
    }},
    { "$project": { "inviteeT": 0 } },
    { "$match": { "invitee.0": { "$exists": true } } }
  ]);

Instead of the $redact which would be filtering "documents", we use $filter here with the expression to only return those members of the target array "inviteeT" which share the same "currentMove". Since this is just the "foreign" content, we "join" with the original array using $map and transposing the elements.

To do that "transposition" of values from the original array, we use the $arrayElemAt and $indexOfArray expressions. The $indexOfArray allows us to match up the target's "_id" values with the "user_id" values in the original array and get it's "index" position. We always know this returns a real match because the $lookup did that part for us.

The "index" value is then supplied to $arrayElemAt which similarly applies a "mapping" of the values as an array like "$invitee.confirmed" and returns the value matched at the same index. This is basically a "lookup" between the arrays.

Differing from the first pipeline example, we now still have the "inviteeT" array as well as our re-written "invitee" array courtesy of $addFields. So one way to get rid of that is to add an additional $project and exclude the unwanted "temporary" array. And of course since we did not $unwind and "filter", there are still possible results with no matching array entries at all. So the $match expression uses $exists to test for the 0 index being present in the array result, which means there is "at least one" result, and discards any documents with empty arrays.

MongoDB 3.6 "sub-query"

MongoDB 3.6 makes this a bit cleaner as a new syntax for $lookup allows a more expressive "pipeline" to be given in argument to select the results returned, rather than the simplistic "localField" and "foreignField" matching.

  Group.aggregate([
    { "$lookup": {
      "from": User.collection.name,
      "let": {
        "ids": "$invitee._id",
        "users": "$invitee.user_id",
        "confirmed": "$invitee.confirmed",
        "currentMove": "$currentMove"
      },
      "pipeline": [
        { "$match": {
          "$expr": {
            "$and": [
              { "$in": ["$_id", "$$users"] },
              { "$eq": ["$currentMove", "$$currentMove"] }
            ]
          }
        }},
        { "$project": {
          "_id": {
            "$arrayElemAt": [
              "$$ids",
              { "$indexOfArray": ["$$users", "$_id"] }
            ]
          },
          "user_id": "$$ROOT",
          "confirmed": {
            "$arrayElemAt": [
              "$$confirmed",
              { "$indexOfArray": ["$$users", "$_id"] }
            ]
          }
        }}
      ],
      "as": "invitee"
    }},
    { "$match": { "invitee.0": { "$exists": true } } }
  ])

So there are some slightly "glitchy" things in there with the usage of mapping arrays of specific values for input due to how these are currently passed into the sub-pipeline via the "let" declaration. This should probably work cleaner, but on the current release candidate this is how it's actually required to be expressed in order to work.

With this new syntax the "let" allows us to declare "variables" from the current document which can then be referenced in the "pipeline" expression which will be executed in order to determine which results to return to the target array.

The $expr here essentially replaces the $redact or $filter conditions used before, as well as combining the "local" to "foreign" key matching which also requires us to declare such a variable. Here we mapped the "$invitee.user_id" values from the source document into a variable which we refer to as "$$users" in the rest of the expressions.

The $in operator here is a variant for the aggregation framework which returns a boolean condition where the first argument "value" is found in the second argument "array". So this is the "foreign key" filter part.

Since this is a "pipeline", we can add a $project stage in addition to the $match which selected the items from the foreign collection. So again we use a similar "transposition" technique to what was described before. This then gives us control of the "shape" of the documents returned in the array, so we don't manipulate the returned array "after" the $lookup like we did previously.

The same case applies though, since no matter what you do here the "sub-pipeline" can of course return no results when the filter conditions do not match. So again the same $exists test is used to discard those documents.

So it's all pretty cool, and once you get used to the power available in the server side "join" functionality of $lookup you likely will never look back. Whilst the syntax is a lot more terse than the "convenience" function that .populate() was introduced for, the reduced traffic load, far more advanced uses and general expressiveness basically make up for that.

As a complete example, I'm also including a self contained listing that demonstrates all of these. And if you run it with a MongoDB 3.6 compatible server attached, then you will even get that demonstration as well.

Needs a recent Node.js v8.x release to run with async/await ( or enable in other supported ), but since that's now the LTS release you really should be running that anyway. At least install one to test :)

const mongoose = require('mongoose'),
      Schema = mongoose.Schema;

mongoose.Promise = global.Promise;
mongoose.set('debug',true);

const uri = 'mongodb://localhost/rollgroup',
      options = { useMongoClient: true };

const userSchema = new Schema({
  name: String,
  currentMove: Number
})

const groupSchema = new Schema({
  name: String,
  topic: String,
  currentMove: Number,
  invitee: [{
    user_id: { type: Schema.Types.ObjectId, ref: 'User' },
    confirmed: { type: Boolean, default: false }
  }]
});

const User = mongoose.model('User', userSchema);
const Group = mongoose.model('Group', groupSchema);

function log(data) {
  console.log(JSON.stringify(data, undefined, 2))
}

(async function() {

  try {

    const conn = await mongoose.connect(uri,options);

    let { version } = await conn.db.admin().command({'buildInfo': 1});

    // Clean data
    await Promise.all(
      Object.entries(conn.models).map(([k,m]) => m.remove() )
    );

    // Add some users
    let users = await User.insertMany([
      { name: 'Bill', currentMove: 1 },
      { name: 'Ted', currentMove: 2 },
      { name: 'Fred', currentMove: 3 },
      { name: 'Sally', currentMove: 4 },
      { name: 'Harry', currentMove: 5 }
    ]);

    await Group.create({
      name: 'Group1',
      topic: 'This stuff',
      currentMove: 3,
      invitee: users.map( u =>
        ({ user_id: u._id, confirmed: (u.currentMove === 3) })
      )
    });

    await (async function() {
      console.log('Unwinding example');
      let result = await Group.aggregate([
        { "$unwind": "$invitee" },
        { "$lookup": {
          "from": User.collection.name,
          "localField": "invitee.user_id",
          "foreignField": "_id",
          "as": "invitee.user_id"
        }},
        { "$unwind": "$invitee.user_id" },
        { "$redact": {
          "$cond": {
            "if": { "$eq": ["$currentMove", "$invitee.user_id.currentMove"] },
            "then": "$$KEEP",
            "else": "$$PRUNE"
          }
        }},
        { "$group": {
          "_id": "$_id",
          "name": { "$first": "$name" },
          "topic": { "$first": "$topic" },
          "currentMove": { "$first": "$currentMove" },
          "invitee": { "$push": "$invitee" }
        }}
      ]);

      log(result);

    })();

    await (async function() {
      console.log('Using $filter example');
      let result = await Group.aggregate([
        { "$lookup": {
          "from": User.collection.name,
          "localField": "invitee.user_id",
          "foreignField": "_id",
          "as": "inviteeT"
        }},
        { "$addFields": {
          "invitee": {
            "$map": {
              "input": {
                "$filter": {
                  "input": "$inviteeT",
                  "as": "i",
                  "cond": { "$eq": ["$$i.currentMove","$currentMove"] }
                }
              },
              "as": "i",
              "in": {
                "_id": {
                  "$arrayElemAt": [
                    "$invitee._id",
                    { "$indexOfArray": ["$invitee.user_id", "$$i._id"] }
                  ]
                },
                "user_id": "$$i",
                "confirmed": {
                  "$arrayElemAt": [
                    "$invitee.confirmed",
                    { "$indexOfArray": ["$invitee.user_id","$$i._id"] }
                  ]
                }
              }
            }
          }
        }},
        { "$project": { "inviteeT": 0 } },
        { "$match": { "invitee.0": { "$exists": true } } }
      ]);

      log(result);

    })();

    await (async function() {
      if (parseFloat(version.match(/\d\.\d/)[0]) >= 3.6) {
        console.log('New $lookup example. Yay!');
        let result = await Group.collection.aggregate([
          { "$lookup": {
            "from": User.collection.name,
            "let": {
              "ids": "$invitee._id",
              "users": "$invitee.user_id",
              "confirmed": "$invitee.confirmed",
              "currentMove": "$currentMove"
            },
            "pipeline": [
              { "$match": {
                "$expr": {
                  "$and": [
                    { "$in": ["$_id", "$$users"] },
                    { "$eq": ["$currentMove", "$$currentMove"] }
                  ]
                }
              }},
              { "$project": {
                "_id": {
                  "$arrayElemAt": [
                    "$$ids",
                    { "$indexOfArray": ["$$users", "$_id"] }
                  ]
                },
                "user_id": "$$ROOT",
                "confirmed": {
                  "$arrayElemAt": [
                    "$$confirmed",
                    { "$indexOfArray": ["$$users", "$_id"] }
                  ]
                }
              }}
            ],
            "as": "invitee"
          }},
          { "$match": { "invitee.0": { "$exists": true } } }
        ]).toArray();

        log(result);

      }
    })();

    await (async function() {
      console.log("Horrible populate example :(");

      let results = await Group.find();

       results = await Promise.all(
        results.map( r =>
          User.populate(r,{
            path: 'invitee.user_id',
            match: { "$where": `this.currentMove === ${r.currentMove}` }
          })
        )
      );

      console.log("All members still there");
      log(results);

      // Then we clean it for null values

      results = results.map( r =>
        Object.assign(r,{
          invitee: r.invitee.filter(i => i.user_id !== null)
        })
      );

      console.log("Now they are filtered");
      log(results);

    })();

  } catch(e) {
    console.error(e);
  } finally {
    mongoose.disconnect();
  }

})()

Gives the output for each example as:

Mongoose: users.remove({}, {})
Mongoose: groups.remove({}, {})
Mongoose: users.insertMany([ { __v: 0, name: 'Bill', currentMove: 1, _id: 5a0afda01643cf41789e500a }, { __v: 0, name: 'Ted', currentMove: 2, _id: 5a0afda01643cf41789e500b }, { __v: 0, name: 'Fred', currentMove: 3, _id: 5a0afda01643cf41789e500c }, { __v: 0, name: 'Sally', currentMove: 4, _id: 5a0afda01643cf41789e500d }, { __v: 0, name: 'Harry', currentMove: 5, _id: 5a0afda01643cf41789e500e } ], {})
Mongoose: groups.insert({ name: 'Group1', topic: 'This stuff', currentMove: 3, _id: ObjectId("5a0afda01643cf41789e500f"), invitee: [ { user_id: ObjectId("5a0afda01643cf41789e500a"), _id: ObjectId("5a0afda01643cf41789e5014"), confirmed: false }, { user_id: ObjectId("5a0afda01643cf41789e500b"), _id: ObjectId("5a0afda01643cf41789e5013"), confirmed: false }, { user_id: ObjectId("5a0afda01643cf41789e500c"), _id: ObjectId("5a0afda01643cf41789e5012"), confirmed: true }, { user_id: ObjectId("5a0afda01643cf41789e500d"), _id: ObjectId("5a0afda01643cf41789e5011"), confirmed: false }, { user_id: ObjectId("5a0afda01643cf41789e500e"), _id: ObjectId("5a0afda01643cf41789e5010"), confirmed: false } ], __v: 0 })
Unwinding example
Mongoose: groups.aggregate([ { '$unwind': '$invitee' }, { '$lookup': { from: 'users', localField: 'invitee.user_id', foreignField: '_id', as: 'invitee.user_id' } }, { '$unwind': '$invitee.user_id' }, { '$redact': { '$cond': { if: { '$eq': [ '$currentMove', '$invitee.user_id.currentMove' ] }, then: '$$KEEP', else: '$$PRUNE' } } }, { '$group': { _id: '$_id', name: { '$first': '$name' }, topic: { '$first': '$topic' }, currentMove: { '$first': '$currentMove' }, invitee: { '$push': '$invitee' } } } ], {})
[
  {
    "_id": "5a0afda01643cf41789e500f",
    "name": "Group1",
    "topic": "This stuff",
    "currentMove": 3,
    "invitee": [
      {
        "user_id": {
          "_id": "5a0afda01643cf41789e500c",
          "__v": 0,
          "name": "Fred",
          "currentMove": 3
        },
        "_id": "5a0afda01643cf41789e5012",
        "confirmed": true
      }
    ]
  }
]
Using $filter example
Mongoose: groups.aggregate([ { '$lookup': { from: 'users', localField: 'invitee.user_id', foreignField: '_id', as: 'inviteeT' } }, { '$addFields': { invitee: { '$map': { input: { '$filter': { input: '$inviteeT', as: 'i', cond: { '$eq': [ '$$i.currentMove', '$currentMove' ] } } }, as: 'i', in: { _id: { '$arrayElemAt': [ '$invitee._id', { '$indexOfArray': [ '$invitee.user_id', '$$i._id' ] } ] }, user_id: '$$i', confirmed: { '$arrayElemAt': [ '$invitee.confirmed', { '$indexOfArray': [ '$invitee.user_id', '$$i._id' ] } ] } } } } } }, { '$project': { inviteeT: 0 } }, { '$match': { 'invitee.0': { '$exists': true } } } ], {})
[
  {
    "_id": "5a0afda01643cf41789e500f",
    "name": "Group1",
    "topic": "This stuff",
    "currentMove": 3,
    "invitee": [
      {
        "_id": "5a0afda01643cf41789e5012",
        "user_id": {
          "_id": "5a0afda01643cf41789e500c",
          "__v": 0,
          "name": "Fred",
          "currentMove": 3
        },
        "confirmed": true
      }
    ],
    "__v": 0
  }
]
New $lookup example. Yay!
Mongoose: groups.aggregate([ { '$lookup': { from: 'users', let: { ids: '$invitee._id', users: '$invitee.user_id', confirmed: '$invitee.confirmed', currentMove: '$currentMove' }, pipeline: [ { '$match': { '$expr': { '$and': [ { '$in': [ '$_id', '$$users' ] }, { '$eq': [ '$currentMove', '$$currentMove' ] } ] } } }, { '$project': { _id: { '$arrayElemAt': [ '$$ids', { '$indexOfArray': [ '$$users', '$_id' ] } ] }, user_id: '$$ROOT', confirmed: { '$arrayElemAt': [ '$$confirmed', { '$indexOfArray': [ '$$users', '$_id' ] } ] } } } ], as: 'invitee' } }, { '$match': { 'invitee.0': { '$exists': true } } } ])
[
  {
    "_id": "5a0afda01643cf41789e500f",
    "name": "Group1",
    "topic": "This stuff",
    "currentMove": 3,
    "invitee": [
      {
        "_id": "5a0afda01643cf41789e5012",
        "user_id": {
          "_id": "5a0afda01643cf41789e500c",
          "__v": 0,
          "name": "Fred",
          "currentMove": 3
        },
        "confirmed": true
      }
    ],
    "__v": 0
  }
]
Horrible populate example :(
Mongoose: groups.find({}, { fields: {} })
Mongoose: users.find({ _id: { '$in': [ ObjectId("5a0afda01643cf41789e500a"), ObjectId("5a0afda01643cf41789e500b"), ObjectId("5a0afda01643cf41789e500c"), ObjectId("5a0afda01643cf41789e500d"), ObjectId("5a0afda01643cf41789e500e") ] }, '$where': 'this.currentMove === 3' }, { fields: {} })
All members still there
[
  {
    "_id": "5a0afda01643cf41789e500f",
    "name": "Group1",
    "topic": "This stuff",
    "currentMove": 3,
    "__v": 0,
    "invitee": [
      {
        "user_id": null,
        "_id": "5a0afda01643cf41789e5014",
        "confirmed": false
      },
      {
        "user_id": null,
        "_id": "5a0afda01643cf41789e5013",
        "confirmed": false
      },
      {
        "user_id": {
          "_id": "5a0afda01643cf41789e500c",
          "__v": 0,
          "name": "Fred",
          "currentMove": 3
        },
        "_id": "5a0afda01643cf41789e5012",
        "confirmed": true
      },
      {
        "user_id": null,
        "_id": "5a0afda01643cf41789e5011",
        "confirmed": false
      },
      {
        "user_id": null,
        "_id": "5a0afda01643cf41789e5010",
        "confirmed": false
      }
    ]
  }
]
Now they are filtered
[
  {
    "_id": "5a0afda01643cf41789e500f",
    "name": "Group1",
    "topic": "This stuff",
    "currentMove": 3,
    "__v": 0,
    "invitee": [
      {
        "user_id": {
          "_id": "5a0afda01643cf41789e500c",
          "__v": 0,
          "name": "Fred",
          "currentMove": 3
        },
        "_id": "5a0afda01643cf41789e5012",
        "confirmed": true
      }
    ]
  }
]

Using populate()

So using .populate() here is actually pretty horrible. Sure it looks like less, but it's actually doing a lot of things that simply are not needed, and all because the "join" does not happen on the server:

   // Note that we cannot populate "here" since we need the returned value
   let results = await Group.find();

   // The value is only in context as we use `Array.map()` to process each result
   results = await Promise.all(
    results.map( r =>
      User.populate(r,{
        path: 'invitee.user_id',
        match: { "$where": `this.currentMove === ${r.currentMove}` }
      })
    )
  );

  console.log("All members still there");
  log(results);

  // Then we clean it for null values

  results = results.map( r =>
    Object.assign(r,{
      invitee: r.invitee.filter(i => i.user_id !== null)
    })
  );

  console.log("Now they are filtered");
  log(results);

So I also included that in the output above, as well as the whole code listing.

The problem becomes evident as you cannot "chain" the populate directly to the first query. You actually need to return the documents ( potentially ALL of them ) in order to use the current document value in a subsequent populate. And this MUST be processed for each document returned.

Not only that but populate() is NOT going to "filter" the array to only those which match, even with the query condition. All it does is set's the unmatched elements to null:

[
  {
    "_id": "5a0afa889f9f7e4064d8794d",
    "name": "Group1",
    "topic": "This stuff",
    "currentMove": 3,
    "__v": 0,
    "invitee": [
      {
        "user_id": null,
        "_id": "5a0afa889f9f7e4064d87952",
        "confirmed": false
      },
      {
        "user_id": null,
        "_id": "5a0afa889f9f7e4064d87951",
        "confirmed": false
      },
      {
        "user_id": {
          "_id": "5a0afa889f9f7e4064d8794a",
          "__v": 0,
          "name": "Fred",
          "currentMove": 3
        },
        "_id": "5a0afa889f9f7e4064d87950",
        "confirmed": true
      },
      {
        "user_id": null,
        "_id": "5a0afa889f9f7e4064d8794f",
        "confirmed": false
      },
      {
        "user_id": null,
        "_id": "5a0afa889f9f7e4064d8794e",
        "confirmed": false
      }
    ]
  }
]

This then needs an Array.filter() to be processed again for "each" document returned, which can finally remove the unwanted array items and give you the same result the other aggregation queries are doing.

So it's "really wasteful" and just not a good way to do things. Little point in having a database, when you're actually doing the majority of processing on the server. In fact, we may have well simply returned the populated result and then run an Array.filter() in order to remove the unwanted entries.

This is just not how you write fast and effective code. So the example here is sometimes "what looks simple" is actually doing a lot more damage than good.


问:
Looks for patterns across different lines
I have a file like this (test.txt):

```<code>abc
12
34
def
56
abc
ghi
78
def
90
</code>```

And I would like to search the 78 which is enclosed by "abc\nghi" and "def". Currently, I know I can do this by:

```<code>cat test.txt | awk '/abc/,/def/' | awk '/ghi/,'/def/'
</code>```

Is there any better way?

答:
This is not really clean, but you can redefine your record separator as a regular expression to be abc\nghi\n|\ndef. This however creates multiple records, and you need to keep track which ones are between the correct ones. With awk you can check which RS was found using RT.

```<code>awk 'BEGIN{RS="abc\nghi\n|\ndef"}
     (RT~/abc/){s=1}
     (s==1)&&(RT~/def/){print $0}
     {s=0}' file
</code>```

This does :

set RS to abc\nghi\n or \ndef.

check if the record is found, if RT contains abc you found the first one.

if you found the first one and the next RT contains def, then print.

Body:
I have a file like this (test.txt):

abc
12
34
def
56
abc
ghi
78
def
90

And I would like to search the 78 which is enclosed by "abc\nghi" and "def". Currently, I know I can do this by:

cat test.txt | awk '/abc/,/def/' | awk '/ghi/,'/def/'

Is there any better way?

Body:
This is not really clean, but you can redefine your record separator as a regular expression to be abc\nghi\n|\ndef. This however creates multiple records, and you need to keep track which ones are between the correct ones. With awk you can check which RS was found using RT.

awk 'BEGIN{RS="abc\nghi\n|\ndef"}
     (RT~/abc/){s=1}
     (s==1)&&(RT~/def/){print $0}
     {s=0}' file

This does :

set RS to abc\nghi\n or \ndef.

check if the record is found, if RT contains abc you found the first one.

if you found the first one and the next RT contains def, then print.


问:
Java 8: replace anonymous class with lambda
I'm having problem in replacing this particular example:

```<code>Consumer consumer = new DefaultConsumer(channel) {
    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
            throws IOException {
        String message = new String(body, "UTF-8");
        System.out.println(" [x] Received '" + message + "'");
    }
};
</code>```

Is it possible to replace that with lambda as it uses non-default constructor for DefaultConsumer?

It's from rabbitMQ java tutorial -> LINK to whole class

答:
No you can't. DefaultConsumer is not a FunctionalInterface (and can't be: more info here) hence is not a lambda target.

Explanation:

Can every anonymous class be replaced by a lambda expression?

The answer is no. You can create an anonymous class for non-final classes and interfaces. Is not the same for lambda expressions. These can be only used where a SAM interface is expected, i.e. interfaces with only a Single Abstract Method (before Java 8 every interface method was abstract but since Java 8 interfaces can also have default and static methods which aren't abstract because they have implementation).

So which anonymous classes can be replaced with a lambda expression?

Only anonymous classes which are implementations of a SAM interface (like Runnable, ActionListener, Comparator, Predicate) can be replaced by a lambda expression. DefaultConsumer cannot be a lambda target because is not even an Interface.

And what about Consumer?

Even though Consumer is an Interface, it is not a SAM Interface because it has more than 1 abstract method so it can't be a lambda target either.

Body:
I'm having problem in replacing this particular example:

Consumer consumer = new DefaultConsumer(channel) {
    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
            throws IOException {
        String message = new String(body, "UTF-8");
        System.out.println(" [x] Received '" + message + "'");
    }
};

Is it possible to replace that with lambda as it uses non-default constructor for DefaultConsumer?

It's from rabbitMQ java tutorial -> LINK to whole class


问:
React native stack navigation goBack() not working
I created common header for all pages, so create header component then i include that header in signup.js component goback navigation function working in signup.js page but not working header component getting undefined object navigate.goback error

Anyone give a solution for that like that i include component

sample code:

import React from 'react';
import { StyleSheet, Text, View, Image, ScrollView, TextInput,KeyboardAvoidingView, StatusBar } from 'react-native';
import {Icon,Body,Button,Title,Left,Right} from 'native-base';
import Expo from "expo";
import { Constants } from 'expo';
import Headerbar from "./../Header/header";
import Statusbar from "./../statusbar";
const googleIcon=require('../../../img/google_icon.png');
const fbIcon=require('../../../img/fb_icon.png');
export default class Socialsignup extends React.Component {
  constructor(props) {
  super(props);
  this.state = {
    };

  }

  render() {
    return (
      <ScrollView style={styles.socialContainer}  scrollEnabled={true}>
        <Statusbar/>
        <Headerbar title="Social Login"   />
          <View style={styles.socialText}>
                  <Text style={styles.accountText}>Choose an account</Text>
          </View>
          <View style={styles.socialIconsBase}>
                <View style={styles.socialIconsGoogle}>
                    <Image source={googleIcon} style={styles.googleIcon}/>
                    <Text style={styles.iconText}>
                      Google
                    </Text>
                </View>
                <View style={styles.socialIconsGoogle}>
                <Image source={fbIcon} style={styles.fbIcon}/>
                    <Text style={styles.iconText}>
                      Facebook
                    </Text>
                </View>
          </View>
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({

  socialContainer: {
    backgroundColor: '#fff',
  },
  accountText: {
      marginTop:25,
      fontSize:20,
      padding:20
  },
  socialIconsBase:
  {
    flexDirection:'row',
    flex:1,
    marginTop:40,
    borderBottomWidth:1,
    borderBottomColor:'#a8c0ce'
  },
  socialIconsGoogle:
  {
      flex:1,
      alignItems:'center',
      paddingTop:25,
      paddingBottom:25,
      borderRightWidth:1,
      borderRightColor:'#a8c0ce',
      marginBottom:8,
  },
  fbIcon:{
    height:50,
    width:50,
  },
  googleIcon:{
    height:50,
    width:50,
  },
  iconText:{
        fontSize:15,
        marginTop:15
  }

});```

答:
you need to use this inside the header component :

```<code>import { withRouter } from 'react-router'
</code>```

and then instead of export default HeaderClassName

use export default withRouter(HeaderClassName)

and you can go back by this.props.history.goBack()

You need to use this too:

```<code><BrowserRouter>
<App />
</code>```

and then add the pages like that

```<code><Route path='/page' component={Page} />
</code>```

Body:
you need to use this inside the header component :

import { withRouter } from 'react-router'

and then instead of export default HeaderClassName

use export default withRouter(HeaderClassName)

and you can go back by this.props.history.goBack()

You need to use this too:

<BrowserRouter>
<App />

and then add the pages like that

<Route path='/page' component={Page} />


问:
How to enable Collection lexicon in MarkLogic Database server
Could you please provide the Query for enabling the collection lexicon.

I have used this coding but i got same issue.

xquery version "1.0-ml";

```<code>  import module namespace admin = "http://marklogic.com/xdmp/admin"
          at "/MarkLogic/admin.xqy";

  let $config := admin:get-configuration()
  return
  admin:database-set-collection-lexicon($config,
        xdmp:database("myDatabase"), fn:true())
</code>```

Thanks!

答:
Configurations need to be saved.

See full example here: admin:save-configuration()

Depending on your configuration changes and situation, we may not want an auto-restart, for which case you would consider: admin:save-configuration-without-restart()

Body:
Could you please provide the Query for enabling the collection lexicon.

I have used this coding but i got same issue.

xquery version "1.0-ml";

  import module namespace admin = "http://marklogic.com/xdmp/admin"
          at "/MarkLogic/admin.xqy";

  let $config := admin:get-configuration()
  return
  admin:database-set-collection-lexicon($config,
        xdmp:database("myDatabase"), fn:true())

Thanks!


问:
Modern C++: initialize constexpr tables
Suppose I have a class X, which functionality requires a lot of constant table values, say an array A[1024]. I have a recurrent function f that computes its values, smth like

```<code>A[x] = f(A[x - 1]);
</code>```

Suppose that A[0] is a known constant, therefore the rest of the array is constant too. What is the best way to calculate these values beforehand, using features of modern C++, and without storaging file with hardcoded values of this array? My workaround was a const static dummy variable:

```<code>const bool X::dummy = X::SetupTables();

bool X::SetupTables() {
    A[0] = 1;
    for (size_t i = 1; i <= A.size(); ++i)
        A[i] = f(A[i - 1]);
}
</code>```

But I believe, it’s not the most beautiful way to go.
Note: I emphasize that array is rather big and I want to avoid monstrosity of the code.

答:
just for fun, a c++17 compact one-liner might be ( requires an std::array A, or some other memory-contiguous tuple-like ):

```<code>std::apply( [](auto, auto&... x){ ( ( x = f((&x)[-1]) ), ... ); }, A );
</code>```

note that this can be used in a constexpr function too.

That said, from c++14 we can use loops in constexpr functions, so we can write a constexpr function returning an std::array directly, written (almost) the usual way.

Title: Modern C++: initialize constexpr tables

Body:
Suppose I have a class X, which functionality requires a lot of constant table values, say an array A[1024]. I have a recurrent function f that computes its values, smth like

A[x] = f(A[x - 1]);

Suppose that A[0] is a known constant, therefore the rest of the array is constant too. What is the best way to calculate these values beforehand, using features of modern C++, and without storaging file with hardcoded values of this array? My workaround was a const static dummy variable:

const bool X::dummy = X::SetupTables();

bool X::SetupTables() {
    A[0] = 1;
    for (size_t i = 1; i <= A.size(); ++i)
        A[i] = f(A[i - 1]);
}

But I believe, it’s not the most beautiful way to go.
Note: I emphasize that array is rather big and I want to avoid monstrosity of the code.

Body:
just for fun, a c++17 compact one-liner might be ( requires an std::array A, or some other memory-contiguous tuple-like ):

std::apply( [](auto, auto&... x){ ( ( x = f((&x)[-1]) ), ... ); }, A );

note that this can be used in a constexpr function too.

That said, from c++14 we can use loops in constexpr functions, so we can write a constexpr function returning an std::array directly, written (almost) the usual way.


问:
Getting child class info from extends construction
I'm not quite sure how to formulate my question, so sorry in advance for this uninformative title.

So here is the problem. I have a couple of files in the same directory, each of them is a class holder. When i inherit one of the classes i need to know in which file (or more like the folder) i do it.

I don't really like the solution i came to, but still to demonstrate what exactly i mean.

foo.php

```<code>class Foo {
}
</code>```

bar.php

```<code>include_once 'bootstrap.php' ;

class Bar extends Foo {
}

$bar = new Bar() ;
</code>```

bootstrap.php

```<code>function __autoload( $class ) {
    $trace = debug_backtrace() ;
    // Here i've got the directory i need:
    $folder = dirname( $trace[ 0 ][ 'file' ] ) ;
}
</code>```

Is there any other (proper) way to get folder name, cause it debug_backtrace is not actually meant for this kind of operations. And not good from the performance point of view either.

Limitation: should work for php 5.2.12

答: $folder = dirname(__FILE__) doesn't do the job?

Body:
I'm not quite sure how to formulate my question, so sorry in advance for this uninformative title.

So here is the problem. I have a couple of files in the same directory, each of them is a class holder. When i inherit one of the classes i need to know in which file (or more like the folder) i do it.

I don't really like the solution i came to, but still to demonstrate what exactly i mean.

foo.php

class Foo {
}

bar.php

include_once 'bootstrap.php' ;

class Bar extends Foo {
}

$bar = new Bar() ;

bootstrap.php

function __autoload( $class ) {
    $trace = debug_backtrace() ;
    // Here i've got the directory i need:
    $folder = dirname( $trace[ 0 ][ 'file' ] ) ;
}

Is there any other (proper) way to get folder name, cause it debug_backtrace is not actually meant for this kind of operations. And not good from the performance point of view either.

Limitation: should work for php 5.2.12


问:
Trying to eliminate delay of filter command to match the results with conv command
Blue coloured curve in the diagram is the result of using conv command in MATLAB for generating a Gaussian modulated signal. But I need to use filter command for the same purpose, resulting in magenta coloured curve. It is shifted towards right by almost 15 points which I have taken care of by discarding first 15 points, which has resulted in red coloured curve. It perfectly follows the curve of convolution command until the point pointed out in the given diagram.

I have added 15 zeros at the end of red curve to match the resultant rector length with that of conv command.

My question is that how can I make the red curve follow the blue cure?

My code lines are:

```<code>     phase = conv (integrated_signal,gaussFilter,'same');
     phase_1 = filter (gaussFilter,1,integrated_signal);
     delay=16;
     phase_1=phase_1(delay:end);
     phase_1(1,length(phase_2)+delay)=0;
</code>```

答:
In general conv(u,v) produces the same result as filter(u,1,padded_v) where padded_v is v zero padded to a length of length(u)+length(v)-1. Assuming that integrated_signal is a row vector, this can be done with the following:

```<code>padded_signal = [integrated_signal zeros(1,length(gaussFilter)-1)];
% or following for column vectors:
% padded_signal = transpose([transpose(integrated_signal) zeros(1,length(gaussFilter)-1)]);
phase_1 = filter (gaussFilter,1,padded_signal);
</code>```

Now, according to the documentation,
conv(u,v,'same') with the 'same' argument produces the

Central part of the convolution of the same size as u.

It then only suffices to extract the same central part:

```<code>delay = floor(length(gaussFilter)/2);
phase_1=phase_1(delay + [1:length(integrated_signal)]);
</code>```

Body:
Blue coloured curve in the diagram is the result of using conv command in MATLAB for generating a Gaussian modulated signal. But I need to use filter command for the same purpose, resulting in magenta coloured curve. It is shifted towards right by almost 15 points which I have taken care of by discarding first 15 points, which has resulted in red coloured curve. It perfectly follows the curve of convolution command until the point pointed out in the given diagram.

I have added 15 zeros at the end of red curve to match the resultant rector length with that of conv command.

My question is that how can I make the red curve follow the blue cure?

My code lines are:

     phase = conv (integrated_signal,gaussFilter,'same');
     phase_1 = filter (gaussFilter,1,integrated_signal);
     delay=16;
     phase_1=phase_1(delay:end);
     phase_1(1,length(phase_2)+delay)=0;

Body:
In general conv(u,v) produces the same result as filter(u,1,padded_v) where padded_v is v zero padded to a length of length(u)+length(v)-1. Assuming that integrated_signal is a row vector, this can be done with the following:

padded_signal = [integrated_signal zeros(1,length(gaussFilter)-1)];
% or following for column vectors:
% padded_signal = transpose([transpose(integrated_signal) zeros(1,length(gaussFilter)-1)]);
phase_1 = filter (gaussFilter,1,padded_signal);

Now, according to the documentation,
conv(u,v,'same') with the 'same' argument produces the

Central part of the convolution of the same size as u.

It then only suffices to extract the same central part:

delay = floor(length(gaussFilter)/2);
phase_1=phase_1(delay + [1:length(integrated_signal)]);


问:
End of scrollbar listbox was split and one of my listheaders is not appearing
I am trying to create a listbox inside a groupbox component which has eight columns. However the last column is gone and I don't know why, even though my listbox has a horizontal scrollbar. I've tried to add:

```<code>`<library-property>
  <name>org.zkoss.zul.nativebar</name>
  <value>true</value>
</library-property>`
</code>```

In my zk.xml and many things
but it's not working. Here is my code:

```<code><groupbox
    visible="@bind(vm.gbxGridPo)"  width="100%">
    <caption label="${labels.common.label.hasil_pencarian}" style="color:blue" />
    <vlayout >
        <checkbox  name="chkBPKB" label="Print SPP/SIP BPKB" checked="@bind(vm.chkBPKB)" />
        <listbox model="@load(vm.poDTOs)" mold="paging" pageSize="10"
                 emptyMessage="Tidak ada data" checkmark="true"
                 width="97%" style="overflow:hidden"
                 selectedItem="@bind(vm.aksiSelectedPO)"
                 onClick="@command('onCheckRadio')">
            <listhead  >
                 <listheader label="${labels.common.label.pilih}" align="center" width="50px" />
                 <listheader label="${labels.common.label.sentra}" align="center" sort="auto(sentraID)"  width="150px" />
                 <listheader label="${labels.common.label.unit}" align="center" sort="auto(unitID)" width="150px" />
                 <listheader label="${labels.common.label.jenis_pihak_ketiga}" align="center" sort="auto(thirdPartyTypeID)" width="150px" />
                 <listheader label="${labels.common.label.nama_pihak_ketiga}" align="center" sort="auto(thirdPartyName)" width="150px"  />
                 <listheader label="${labels.common.label.no_po}" align="center" sort="auto(poNumber)"  width="120px"/>
                 <listheader label="${labels.common.label.nama_lengkap}" align="center" sort="auto(customerName)" width="180px" />
                 <listheader label="${labels.common.label.no_aplikasi}" align="center" sort="auto(orderID)" width="140px"/>
             </listhead>
             <template name="model"  status="s" var="item">
                 <listitem>
                     <listcell />
                     <listcell label="@load(item.sentraID)" />
                     <listcell label="@load(item.unitID)" />
                     <listcell label="@load(item.thirdPartyTypeID)" />
                     <listcell label="@load(item.thirdPartyName)" />
                     <listcell label="@load(item.poNumber)" />
                     <listcell label="@load(item.customerName)" />
                     <listcell label="@load(item.orderID)" />
                 </listitem>
            </template>
        </listbox>
    </vlayout>
</groupbox>
</code>```

答:
Two ideas about what is going wrong:

First, setting the vlayout's width to 100% or hflex to 1 could help. Right now, the vlayout will be as wide as necessary to fit its children. The 97% on the listbox don't help, since the parent (vlayout) does not have a width restriction.

Second, is the 100% on groupbox correct? What container is that one in? If the groupbox's container spans the whole page, 100% will make the groupbox also span the whole page; and since there is another box on the left, the groupbox is extends beyond the page.

EDIT

After playing with your zul a bit, I think it is the second case. Look at this zul:

```<code><hlayout width="100%">
    <div width="100px" height="100px" style="background: green" />
    <groupbox width="100%">
        <caption label="Bla" />
        <vlayout >
            <checkbox  label="Check" />
            <listbox model="@load(vm.poDTOs)" width="97%" style="overflow:hidden">
                <listhead  >
                     <listheader label="1" width="50px" />
                     <listheader label="2" width="150px" />
                     <listheader label="2" width="150px" />
                     <listheader label="2" width="150px" />
                     <listheader label="2" width="150px" />
                     <listheader label="2" width="150px" />
                     <listheader label="2" width="150px" />
                     <listheader label="2" width="150px" />
                     <listheader label="2" width="150px" />
                 </listhead>
            </listbox>
        </vlayout>
    </groupbox>
</hlayout>
</code>```

This produces behavior looking similar to yours. But changing the groupbox from width="100%" to hflex="1" fixes it, as it will only take the remaining space left behind the div.

Body:
I am trying to create a listbox inside a groupbox component which has eight columns. However the last column is gone and I don't know why, even though my listbox has a horizontal scrollbar. I've tried to add:

`<library-property>
  <name>org.zkoss.zul.nativebar</name>
  <value>true</value>
</library-property>`

In my zk.xml and many things
but it's not working. Here is my code:

<groupbox
    visible="@bind(vm.gbxGridPo)"  width="100%">

    <vlayout >
        <checkbox  name="chkBPKB" label="Print SPP/SIP BPKB" checked="@bind(vm.chkBPKB)" />
        <listbox model="@load(vm.poDTOs)" mold="paging" pageSize="10"
                 emptyMessage="Tidak ada data" checkmark="true"
                 width="97%" style="overflow:hidden"
                 selectedItem="@bind(vm.aksiSelectedPO)"
                 onClick="@command('onCheckRadio')">
            <listhead  >
                 <listheader label="${labels.common.label.pilih}" align="center" width="50px" />
                 <listheader label="${labels.common.label.sentra}" align="center" sort="auto(sentraID)"  width="150px" />
                 <listheader label="${labels.common.label.unit}" align="center" sort="auto(unitID)" width="150px" />
                 <listheader label="${labels.common.label.jenis_pihak_ketiga}" align="center" sort="auto(thirdPartyTypeID)" width="150px" />
                 <listheader label="${labels.common.label.nama_pihak_ketiga}" align="center" sort="auto(thirdPartyName)" width="150px"  />
                 <listheader label="${labels.common.label.no_po}" align="center" sort="auto(poNumber)"  width="120px"/>
                 <listheader label="${labels.common.label.nama_lengkap}" align="center" sort="auto(customerName)" width="180px" />
                 <listheader label="${labels.common.label.no_aplikasi}" align="center" sort="auto(orderID)" width="140px"/>
             </listhead>
             <template name="model"  status="s" var="item">
                 <listitem>
                     <listcell />
                     <listcell label="@load(item.sentraID)" />
                     <listcell label="@load(item.unitID)" />
                     <listcell label="@load(item.thirdPartyTypeID)" />
                     <listcell label="@load(item.thirdPartyName)" />
                     <listcell label="@load(item.poNumber)" />
                     <listcell label="@load(item.customerName)" />
                     <listcell label="@load(item.orderID)" />
                 </listitem>
            </template>
        </listbox>
    </vlayout>
</groupbox>

Body:
Two ideas about what is going wrong:

First, setting the vlayout's width to 100% or hflex to 1 could help. Right now, the vlayout will be as wide as necessary to fit its children. The 97% on the listbox don't help, since the parent (vlayout) does not have a width restriction.

Second, is the 100% on groupbox correct? What container is that one in? If the groupbox's container spans the whole page, 100% will make the groupbox also span the whole page; and since there is another box on the left, the groupbox is extends beyond the page.

EDIT

After playing with your zul a bit, I think it is the second case. Look at this zul:

<hlayout width="100%">
    <div width="100px" height="100px" style="background: green" />
    <groupbox width="100%">
        <caption label="Bla" />
        <vlayout >
            <checkbox  label="Check" />
            <listbox model="@load(vm.poDTOs)" width="97%" style="overflow:hidden">
                <listhead  >
                     <listheader label="1" width="50px" />
                     <listheader label="2" width="150px" />
                     <listheader label="2" width="150px" />
                     <listheader label="2" width="150px" />
                     <listheader label="2" width="150px" />
                     <listheader label="2" width="150px" />
                     <listheader label="2" width="150px" />
                     <listheader label="2" width="150px" />
                     <listheader label="2" width="150px" />
                 </listhead>
            </listbox>
        </vlayout>
    </groupbox>
</hlayout>

This produces behavior looking similar to yours. But changing the groupbox from width="100%" to hflex="1" fixes it, as it will only take the remaining space left behind the div.


问:
Check if at least two out of three booleans are true
An interviewer recently asked me this question: given three boolean variables, a, b, and c, return true if at least two out of the three are true.

My solution follows:

```<code>boolean atLeastTwo(boolean a, boolean b, boolean c) {
    if ((a && b) || (b && c) || (a && c)) {
        return true;
    }
    else{
        return false;
    }
}
</code>```

He said that this can be improved further, but how?

答:
It seems to me that three out of three are quite arbitrary numbers, and the function should work with an arbitrary number. So in order to answer the question, I'd write a function that would work out if x in an array were true, for example,</p>

```<code>bool istrue ( int x, bool[] list)
    y = count true in list
    return y >= x
</code>```

Body:
An interviewer recently asked me this question: given three boolean variables, a, b, and c, return true if at least two out of the three are true.

My solution follows:

boolean atLeastTwo(boolean a, boolean b, boolean c) {
    if ((a && b) || (b && c) || (a && c)) {
        return true;
    }
    else{
        return false;
    }
}

He said that this can be improved further, but how?

Body:
It seems to me that three out of three are quite arbitrary numbers, and the function should work with an arbitrary number. So in order to answer the question, I'd write a function that would work out if x in an array were true, for example,

bool istrue ( int x, bool[] list)
    y = count true in list
    return y >= x


问:
How to make a pseudo element same height and width in pure CSS?
The .speech height may vary therefore looking for solution to make .speech::after's width same as .speech's height.

ideal result

body {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.speech {
  width: 250px;
  padding: 1rem;
  background-color: tomato;
  color: white;
  border: 1px solid;
  position: relative;
}

.speech::after {
  content: '';
  position: absolute;
  top: 0;
  left: 100%;
  border: 3px solid deepskyblue;
  height: 100%;
  padding-left: 50%;
  background: linear-gradient(45deg, transparent 50%, green 0%);
  transform: translateX(-50%) rotate(45deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="speech">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem.</div></code>```

答:
Defining a clip-path will give you the intended result.

The clip-path CSS property creates a clipping region that defines what
  part of an element should be displayed. Those portions that are inside
  the region are shown, while those outside are hidden. The clipping
  region is a path specified either as a URL referencing inline or
  external SVG, or as a shape, such as a circle().

clip-path - CSS | MDN

var addText = "Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem.";

jQuery('.add-text').on('click', function(){
  jQuery('.alt-speech').append(addText);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column; /* for the sake of demonstration */
}

.speech {
  width: 250px;
  padding: 1rem;
  background-color: tomato;
  color: white;
  border: 1px solid;
  position: relative;
}

.speech::after {
  content: '';
  position: absolute;
  top: 0;
  left: 100%;
  border: 3px solid deepskyblue;
  height: 100%;
  padding-left: 50%;
  background: linear-gradient(45deg, transparent 50%, green 0%);
  transform: translateX(-50%) rotate(45deg);
}

/* Additional */

.alt-speech {
  width: 250px;
  padding: 1rem;
  background-color: tomato;
  color: white;
  border: 1px solid;
  position: relative;
}

.alt-speech:after {
    content: "";
    width: 50%;
    background: tomato;
    -webkit-clip-path: polygon(0 0, 0% 100%, 30% 50%);
    clip-path: polygon(0 0, 0% 100%, 30% 50%);
    top: 0;
    bottom: 0;
    left: 100%;
    position: absolute;
}

.add-text {
    transition: .7s;
    color: white;
    background: tomato;
    padding: 10px 20px;
    cursor: pointer;
}

.add-text:hover {
    background: #c12a0f;
}</code>```

Add Text

Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem.
```

Further Reading:

Creating Responsive Shapes With Clip-Path And Breaking Out Of The Box (Smashing Magazine)

NOTE:

This is an experimental technology, carefully review cross browser compatibility and support before implementing in production.

Cross browser compatibility & support Overview:

caniuse.com

clip-path - CSS | MDN

Body:
The .speech height may vary therefore looking for solution to make .speech::after's width same as .speech's height.

ideal result

body {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.speech {
  width: 250px;
  padding: 1rem;
  background-color: tomato;
  color: white;
  border: 1px solid;
  position: relative;
}

.speech::after {
  content: '';
  position: absolute;
  top: 0;
  left: 100%;
  border: 3px solid deepskyblue;
  height: 100%;
  padding-left: 50%;
  background: linear-gradient(45deg, transparent 50%, green 0%);
  transform: translateX(-50%) rotate(45deg);
}

Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem.

Body:
Defining a clip-path will give you the intended result.

The clip-path CSS property creates a clipping region that defines what
  part of an element should be displayed. Those portions that are inside
  the region are shown, while those outside are hidden. The clipping
  region is a path specified either as a URL referencing inline or
  external SVG, or as a shape, such as a circle().

clip-path - CSS | MDN

var addText = "Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem.";

jQuery('.add-text').on('click', function(){
  jQuery('.alt-speech').append(addText);
});

body {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column; /* for the sake of demonstration */
}

.speech {
  width: 250px;
  padding: 1rem;
  background-color: tomato;
  color: white;
  border: 1px solid;
  position: relative;
}

.speech::after {
  content: '';
  position: absolute;
  top: 0;
  left: 100%;
  border: 3px solid deepskyblue;
  height: 100%;
  padding-left: 50%;
  background: linear-gradient(45deg, transparent 50%, green 0%);
  transform: translateX(-50%) rotate(45deg);
}

/* Additional */

.alt-speech {
  width: 250px;
  padding: 1rem;
  background-color: tomato;
  color: white;
  border: 1px solid;
  position: relative;
}

.alt-speech:after {
    content: "";
    width: 50%;
    background: tomato;
    -webkit-clip-path: polygon(0 0, 0% 100%, 30% 50%);
    clip-path: polygon(0 0, 0% 100%, 30% 50%);
    top: 0;
    bottom: 0;
    left: 100%;
    position: absolute;
}

.add-text {
    transition: .7s;
    color: white;
    background: tomato;
    padding: 10px 20px;
    cursor: pointer;
}

.add-text:hover {
    background: #c12a0f;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add-text">Add Text</div>

<div style="margin: 20px 0px"></div>

<div class="alt-speech">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem.</div>

Further Reading:

Creating Responsive Shapes With Clip-Path And Breaking Out Of The Box (Smashing Magazine)

NOTE:

This is an experimental technology, carefully review cross browser compatibility and support before implementing in production.

Cross browser compatibility & support Overview:

caniuse.com

clip-path - CSS | MDN