问:
How can I get the spacing to be equal?
When I run this code there is a line between the 1st and 4th box. I'm using a flexbox. I wanted to make two rows of three items, but there's a line of space that I can't get rid of. I've tried everything that I could think of, but nothing is working. I've read up on the spacing, but nothing is working. Any ideas on this issue?

```<code>
            <div class="projects">
            <h1 id="project" class="pro">Projects</h1>
            <div class="flex-container">

            <div class="container-fluid p-0 d-flex  justify-content-center d-inline align-content-center">
                  <div class="row " >
                     <div class="col-6 col-sm-2" >

                      <div class="one" style="width: 285px; height: 275px;">
                            <div class="flip-card">
                            <div class="flip-card-inner">
                              <div class="flip-card-front">
                                <img class="light" src="light.png">
                              </div>
                              <div class="flip-card-back">
                                <h1>John Doe</h1>
                                <p>Architect & Engineer</p>
                                <p>We love that guy</p>
                              </div>
                            </div>
                          </div> </div> </div>

                       <div class="two"style="width: 299px; height: 275px;">
                            <div class="flip-card">
                            <div class="flip-card-inner">
                              <div class="flip-card-front t2">
                                <img class="light" src="light.png">
                              </div>
                              <div class="flip-card-back">
                                <h1>John Doe</h1>
                                <p>Architect & Engineer</p>
                                <p>We love that guy</p>
                            </div>

                        </div> </div>
                        </div></div>

                        <div class="three "style="width:285px; height:275px;  ">
                                <div class="flip-card">
                                <div class="flip-card-inner">
                                  <div class="flip-card-front t3">
                                    <img class="light" src="light.png">
                                  </div>
                                  <div class="flip-card-back">
                                    <h1>John Doe</h1>
                                    <p>Architect & Engineer</p>
                                    <p>We love that guy</p>
                                </div>

                            </div> </div>
                            </div></div>

                            <div class="container-fluid p-0 d-flex align-content-center justify-content-center d-inline  ">

                          <div class="row ">

                                <div class="col-6 col-sm-2" >

                       <div class="four"style="width: 285px; height:275px;">
                            <div class="flip-card">
                            <div class="flip-card-inner">
                              <div class="flip-card-front t4">
                                <img class="light" src="light.png">
                              </div>
                              <div class="flip-card-back">
                                <h1>John Doe</h1>
                                <p>Architect & Engineer</p>
                                <p>We love that guy</p>
                              </div>

                          </div> </div>
                          </div></div>

                        <div class="five"style="width: 299px; height:275px;">
                            <div class="flip-card">
                            <div class="flip-card-inner">
                              <div class="flip-card-front t5">
                                <img class="light" src="light.png" >
                              </div>
                              <div class="flip-card-back">
                                <h1>John Doe</h1>
                                <p>Architect & Engineer</p>
                                <p>We love that guy</p>
                              </div>
                            </div>
                          </div></div></div>

                        <div class="six"style="width: 285px; height:275px;">
                            <div class="flip-card">
                            <div class="flip-card-inner">
                              <div class="flip-card-front t6 ">
                                <img class="light" src="light.png">
                              </div>
                              <div class="flip-card-back">
                                <h1>John Doe</h1>
                                <p>Architect & Engineer</p>
                                <p>We love that guy</p>
                              </div>
                          </div></div></div></div></div>

                </div>
            </div>

        </div>

      </div>
</code>```

```<code>CSS

.flip-card, .one,.two,.three,.four,.five,.six {
    background-color: transparent;
    width: 280px;
    height: 275px;
    /*border: 1px solid #f1f1f1;*/
    perspective: 1000px;

}

  .flip-card-inner {
    position: relative;
    width: 100%;
    height: 100%;
    text-align: center;
    transition: transform 0.8s;
    transform-style: preserve-3d;
  }

  /* Do an horizontal flip when you move the mouse over the flip box container*/
  .flip-card:hover .flip-card-inner {
    transform: rotateY(180deg);
  }

  /* Position the front and back side */
  .flip-card-front, .flip-card-back {
    position: absolute;
    width: 100%;
    height: 100%;
    backface-visibility: hidden;
  }

  /* Style the front side (fallback if image is missing)*/
  .flip-card-front, .t3,.t5 {
    background-color:white;
    color: black;
   background-position: top 15px;

  }

   .flip-card-front.t2 ,.t4,.t6 {
    background-color: rgb(248, 122, 4);
    color: black;

  }

  /* Style the back side */
  .flip-card-back {
    background-color: dodgerblue;
    color: white;
    transform: rotateY(180deg);
  }
  /*@media screen and (max-width:959px){
  }

/*END FLIP*/
.projects{
    background-color: blueviolet;
    width:100%;
height:680px;
display:block;}

.row{
    justify-content:space-between;
    display:block;

}

I want the boxes to have equal spacing.

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.flip-card, .one,.two,.three,.four,.five,.six {
    background-color: transparent;
    width: 280px;
    height: 275px;
    /*border: 1px solid #f1f1f1;*/
    perspective: 1000px;

}

  .flip-card-inner {
    position: relative;
    width: 100%;
    height: 100%;
    text-align: center;
    transition: transform 0.8s;
    transform-style: preserve-3d;
  }

  /* Do a horizontal flip when you move the mouse over the flip box container*/
  .flip-card:hover .flip-card-inner {
    transform: rotateY(180deg);
  }

  /* Position the front and back side */
  .flip-card-front, .flip-card-back {
    position: absolute;
    width: 100%;
    height: 100%;
    backface-visibility: hidden;
  }

  /* Style the front side (fallback if image is missing)*/
  .flip-card-front, .t3,.t5 {
    background-color:green;
    color: black;
   background-position: top 15px;

  }

   .flip-card-front.t2 ,.t4,.t6 {
    background-color: rgb(248, 122, 4);
    color: black;

  }

  /* Style the back side */
  .flip-card-back {
    background-color: dodgerblue;
    color: white;
    transform: rotateY(180deg);
  }
  /*@media screen and (max-width:959px){
  }

/*END FLIP*/
.projects{
    background-color: blueviolet;
    width:100%;
height:680px;
display:block;}

.row{
    justify-content:space-between;
    display:block;

}</code>```

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

Projects

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy

           ```
</div>
</div>

</code>```

答:
I was seeing a vertical line between the second and third column. I removed that by removing the width on .flip-card in this snippet.

.flip-card,
.one,
.two,
.three,
.four,
.five,
.six {
  background-color: transparent;
  height: 275px;
  /*border: 1px solid #f1f1f1;*/
  perspective: 1000px;
}

.flip-card-inner {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  transition: transform 0.8s;
  transform-style: preserve-3d;
}

/* Do an horizontal flip when you move the mouse over the flip box container*/

.flip-card:hover .flip-card-inner {
  transform: rotateY(180deg);
}

/* Position the front and back side */

.flip-card-front,
.flip-card-back {
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
}

/* Style the front side (fallback if image is missing)*/

.flip-card-front,
.t3,
.t5 {
  background-color: white;
  color: black;
  background-position: top 15px;
}

.flip-card-front.t2,
.t4,
.t6 {
  background-color: rgb(248, 122, 4);
  color: black;
}

/* Style the back side */

.flip-card-back {
  background-color: dodgerblue;
  color: white;
  transform: rotateY(180deg);
}

/*@media screen and (max-width:959px){
  }

/*END FLIP*/

.projects {
  background-color: blueviolet;
  width: 100%;
  height: 680px;
  display: block;
}

.row {
  justify-content: space-between;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="projects">
  <h1 id="project" class="pro">Projects</h1>
  <div class="flex-container">

    <div class="container-fluid p-0 d-flex  justify-content-center d-inline align-content-center">
      <div class="row ">
        <div class="col-6 col-sm-2">

          <div class="one" style="width: 285px; height: 275px;">
            <div class="flip-card">
              <div class="flip-card-inner">
                <div class="flip-card-front">
                  <img class="light" src="light.png">
                </div>
                <div class="flip-card-back">
                  <h1>John Doe</h1>
                  <p>Architect & Engineer</p>
                  <p>We love that guy</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="two" style="width: 299px; height: 275px;">
          <div class="flip-card">
            <div class="flip-card-inner">
              <div class="flip-card-front t2">
                <img class="light" src="light.png">
              </div>
              <div class="flip-card-back">
                <h1>John Doe</h1>
                <p>Architect & Engineer</p>
                <p>We love that guy</p>
              </div>

            </div>
          </div>
        </div>
      </div>

      <div class="three " style="width:285px; height:275px;  ">
        <div class="flip-card">
          <div class="flip-card-inner">
            <div class="flip-card-front t3">
              <img class="light" src="light.png">
            </div>
            <div class="flip-card-back">
              <h1>John Doe</h1>
              <p>Architect & Engineer</p>
              <p>We love that guy</p>
            </div>

          </div>
        </div>
      </div>
    </div>

    <div class="container-fluid p-0 d-flex align-content-center justify-content-center d-inline  ">

      <div class="row ">

        <div class="col-6 col-sm-2">

          <div class="four" style="width: 285px; height:275px;">
            <div class="flip-card">
              <div class="flip-card-inner">
                <div class="flip-card-front t4">
                  <img class="light" src="light.png">
                </div>
                <div class="flip-card-back">
                  <h1>John Doe</h1>
                  <p>Architect & Engineer</p>
                  <p>We love that guy</p>
                </div>

              </div>
            </div>
          </div>
        </div>

        <div class="five" style="width: 299px; height:275px;">
          <div class="flip-card">
            <div class="flip-card-inner">
              <div class="flip-card-front t5">
                <img class="light" src="light.png">
              </div>
              <div class="flip-card-back">
                <h1>John Doe</h1>
                <p>Architect & Engineer</p>
                <p>We love that guy</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="six" style="width: 285px; height:275px;">
        <div class="flip-card">
          <div class="flip-card-inner">
            <div class="flip-card-front t6 ">
              <img class="light" src="light.png">
            </div>
            <div class="flip-card-back">
              <h1>John Doe</h1>
              <p>Architect & Engineer</p>
              <p>We love that guy</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</div></code>```

Title: How can I get the spacing to be equal?

Body:
When I run this code there is a line between the 1st and 4th box. I'm using a flexbox. I wanted to make two rows of three items, but there's a line of space that I can't get rid of. I've tried everything that I could think of, but nothing is working. I've read up on the spacing, but nothing is working. Any ideas on this issue?

Projects

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy

CSS

.flip-card, .one,.two,.three,.four,.five,.six {
    background-color: transparent;
    width: 280px;
    height: 275px;
    /*border: 1px solid #f1f1f1;*/
    perspective: 1000px;

}

  .flip-card-inner {
    position: relative;
    width: 100%;
    height: 100%;
    text-align: center;
    transition: transform 0.8s;
    transform-style: preserve-3d;
  }

  /* Do an horizontal flip when you move the mouse over the flip box container*/
  .flip-card:hover .flip-card-inner {
    transform: rotateY(180deg);
  }

  /* Position the front and back side */
  .flip-card-front, .flip-card-back {
    position: absolute;
    width: 100%;
    height: 100%;
    backface-visibility: hidden;
  }

  /* Style the front side (fallback if image is missing)*/
  .flip-card-front, .t3,.t5 {
    background-color:white;
    color: black;
   background-position: top 15px;

  }

   .flip-card-front.t2 ,.t4,.t6 {
    background-color: rgb(248, 122, 4);
    color: black;

  }

  /* Style the back side */
  .flip-card-back {
    background-color: dodgerblue;
    color: white;
    transform: rotateY(180deg);
  }
  /*@media screen and (max-width:959px){
  }

/*END FLIP*/
.projects{
    background-color: blueviolet;
    width:100%;
height:680px;
display:block;}

.row{
    justify-content:space-between;
    display:block;

}

I want the boxes to have equal spacing.

.flip-card, .one,.two,.three,.four,.five,.six {
    background-color: transparent;
    width: 280px;
    height: 275px;
    /*border: 1px solid #f1f1f1;*/
    perspective: 1000px;

}

  .flip-card-inner {
    position: relative;
    width: 100%;
    height: 100%;
    text-align: center;
    transition: transform 0.8s;
    transform-style: preserve-3d;
  }

  /* Do a horizontal flip when you move the mouse over the flip box container*/
  .flip-card:hover .flip-card-inner {
    transform: rotateY(180deg);
  }

  /* Position the front and back side */
  .flip-card-front, .flip-card-back {
    position: absolute;
    width: 100%;
    height: 100%;
    backface-visibility: hidden;
  }

  /* Style the front side (fallback if image is missing)*/
  .flip-card-front, .t3,.t5 {
    background-color:green;
    color: black;
   background-position: top 15px;

  }

   .flip-card-front.t2 ,.t4,.t6 {
    background-color: rgb(248, 122, 4);
    color: black;

  }

  /* Style the back side */
  .flip-card-back {
    background-color: dodgerblue;
    color: white;
    transform: rotateY(180deg);
  }
  /*@media screen and (max-width:959px){
  }

/*END FLIP*/
.projects{
    background-color: blueviolet;
    width:100%;
height:680px;
display:block;}

.row{
    justify-content:space-between;
    display:block;

}

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

Projects

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy

Body:
I was seeing a vertical line between the second and third column. I removed that by removing the width on .flip-card in this snippet.

.flip-card,
.one,
.two,
.three,
.four,
.five,
.six {
  background-color: transparent;
  height: 275px;
  /*border: 1px solid #f1f1f1;*/
  perspective: 1000px;
}

.flip-card-inner {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  transition: transform 0.8s;
  transform-style: preserve-3d;
}

/* Do an horizontal flip when you move the mouse over the flip box container*/

.flip-card:hover .flip-card-inner {
  transform: rotateY(180deg);
}

/* Position the front and back side */

.flip-card-front,
.flip-card-back {
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
}

/* Style the front side (fallback if image is missing)*/

.flip-card-front,
.t3,
.t5 {
  background-color: white;
  color: black;
  background-position: top 15px;
}

.flip-card-front.t2,
.t4,
.t6 {
  background-color: rgb(248, 122, 4);
  color: black;
}

/* Style the back side */

.flip-card-back {
  background-color: dodgerblue;
  color: white;
  transform: rotateY(180deg);
}

/*@media screen and (max-width:959px){
  }

/*END FLIP*/

.projects {
  background-color: blueviolet;
  width: 100%;
  height: 680px;
  display: block;
}

.row {
  justify-content: space-between;
  display: block;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="projects">
  <h1 id="project" class="pro">Projects</h1>
  <div class="flex-container">

    <div class="container-fluid p-0 d-flex  justify-content-center d-inline align-content-center">
      <div class="row ">
        <div class="col-6 col-sm-2">

          <div class="one" style="width: 285px; height: 275px;">
            <div class="flip-card">
              <div class="flip-card-inner">
                <div class="flip-card-front">
                  <img class="light" src="light.png">
                </div>
                <div class="flip-card-back">
                  <h1>John Doe</h1>
                  <p>Architect & Engineer</p>
                  <p>We love that guy</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="two" style="width: 299px; height: 275px;">
          <div class="flip-card">
            <div class="flip-card-inner">
              <div class="flip-card-front t2">
                <img class="light" src="light.png">
              </div>
              <div class="flip-card-back">
                <h1>John Doe</h1>
                <p>Architect & Engineer</p>
                <p>We love that guy</p>
              </div>

            </div>
          </div>
        </div>
      </div>

      <div class="three " style="width:285px; height:275px;  ">
        <div class="flip-card">
          <div class="flip-card-inner">
            <div class="flip-card-front t3">
              <img class="light" src="light.png">
            </div>
            <div class="flip-card-back">
              <h1>John Doe</h1>
              <p>Architect &amp; Engineer</p>
              <p>We love that guy</p>
            </div>

          </div>
        </div>
      </div>
    </div>

    <div class="container-fluid p-0 d-flex align-content-center justify-content-center d-inline  ">

      <div class="row ">

        <div class="col-6 col-sm-2">

          <div class="four" style="width: 285px; height:275px;">
            <div class="flip-card">
              <div class="flip-card-inner">
                <div class="flip-card-front t4">
                  <img class="light" src="light.png">
                </div>
                <div class="flip-card-back">
                  <h1>John Doe</h1>
                  <p>Architect & Engineer</p>
                  <p>We love that guy</p>
                </div>

              </div>
            </div>
          </div>
        </div>

        <div class="five" style="width: 299px; height:275px;">
          <div class="flip-card">
            <div class="flip-card-inner">
              <div class="flip-card-front t5">
                <img class="light" src="light.png">
              </div>
              <div class="flip-card-back">
                <h1>John Doe</h1>
                <p>Architect & Engineer</p>
                <p>We love that guy</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="six" style="width: 285px; height:275px;">
        <div class="flip-card">
          <div class="flip-card-inner">
            <div class="flip-card-front t6 ">
              <img class="light" src="light.png">
            </div>
            <div class="flip-card-back">
              <h1>John Doe</h1>
              <p>Architect &amp; Engineer</p>
              <p>We love that guy</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</div>


来源: stackexchange

问:
How to add array of object to an entry of odata array
I want to add a array of objects to a specific entry of an odata array.
It is a JSON-Model in sapui5 and I wanted to do oModel.getData()[j].setProperty(""), but this does not. Can anyone help?

I have:

```<code>    [{
            attributes: (5) [{…}, {…}, {…}, {…}, {…}]
            creationDate: "2019-05-20T09:14:16.622Z"
            deleted: false
            eventDate: "20.05.19"
            message: "Aufgabe xyz"
            object: "Aufgabe"
    },
{
            attributes: (5) [{…}, {…}, {…}, {…}, {…}]
            creationDate: "2019-05-20T09:14:16.622Z"
            deleted: false
            eventDate: "21.05.19"
            message: "Aufgabe"
            object: "Aufgabe"    }
]
</code>```

And I want to add a new Item:

```<code>[{
        description: "Ereignisgruppe"
        key: "objectGroup"
        value: "Aufgaben"
    },{
        description: "Ereignis"
        key: "object"
        value: "Aufgabe"
   }]
</code>```

To get this:

```<code> [{
                attributes: (5) [{…}, {…}, {…}, {…}, {…}]
                creationDate: "2019-05-20T09:14:16.622Z"
                deleted: false
                eventDate: "20.05.19"
                message: "Aufgabe xyz"
                object: "Aufgabe",
                masterAttributes: (2) [{…}, {…}]        <-------------- new
        },
    {
                attributes: (5) [{…}, {…}, {…}, {…}, {…}]
                creationDate: "2019-05-20T09:14:16.622Z"
                deleted: false
                eventDate: "21.05.19"
                message: "Aufgabe"
                object: "Aufgabe"
   }]
</code>```

Best regards!

答:
You just need to create a new property and assign the corresponding values</p>

```<code>var oData= [{
    attributes: [],
    creationDate: "2019-05-20T09:14:16.622Z",
    deleted: false,
    eventDate: "20.05.19"  ,
    message: "Aufgabe xyz",
    object: "Aufgabe"
}, {
    attributes: [],
    creationDate: "2019-05-20T09:14:16.622Z",
    deleted: false,
    eventDate: "21.05.19",
    message: "Aufgabe",
    object: "Aufgabe"
   }
];
var oMergeData = [{
    description: "Ereignisgruppe",
    key: "objectGroup",
    value: "Aufgaben"
   },{
    description: "Ereignis",
    key: "object",
    value: "Aufgabe",
   }
];
//Loop main object and add new property with corresponding values
for( var i in oData) {
  var oNewData = oData[i];
  oNewData['masterAttributes '] = oMergeData[i];
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to add a array of objects to a specific entry of an odata array.
It is a JSON-Model in sapui5 and I wanted to do oModel.getData()[j].setProperty(""), but this does not. Can anyone help?

I have:

    [{
            attributes: (5) [{…}, {…}, {…}, {…}, {…}]
            creationDate: "2019-05-20T09:14:16.622Z"
            deleted: false
            eventDate: "20.05.19"
            message: "Aufgabe xyz"
            object: "Aufgabe"
    },
{
            attributes: (5) [{…}, {…}, {…}, {…}, {…}]
            creationDate: "2019-05-20T09:14:16.622Z"
            deleted: false
            eventDate: "21.05.19"
            message: "Aufgabe"
            object: "Aufgabe"    }
]

And I want to add a new Item:

[{
        description: "Ereignisgruppe"
        key: "objectGroup"
        value: "Aufgaben"
    },{
        description: "Ereignis"
        key: "object"
        value: "Aufgabe"
   }]

To get this:

 [{
                attributes: (5) [{…}, {…}, {…}, {…}, {…}]
                creationDate: "2019-05-20T09:14:16.622Z"
                deleted: false
                eventDate: "20.05.19"
                message: "Aufgabe xyz"
                object: "Aufgabe",
                masterAttributes: (2) [{…}, {…}]        <-------------- new
        },
    {
                attributes: (5) [{…}, {…}, {…}, {…}, {…}]
                creationDate: "2019-05-20T09:14:16.622Z"
                deleted: false
                eventDate: "21.05.19"
                message: "Aufgabe"
                object: "Aufgabe"
   }]

Best regards!

Body:
You just need to create a new property and assign the corresponding values

var oData= [{
    attributes: [],
    creationDate: "2019-05-20T09:14:16.622Z",
    deleted: false,
    eventDate: "20.05.19"  ,
    message: "Aufgabe xyz",
    object: "Aufgabe"
}, {
    attributes: [],
    creationDate: "2019-05-20T09:14:16.622Z",
    deleted: false,
    eventDate: "21.05.19",
    message: "Aufgabe",
    object: "Aufgabe"
   }
];
var oMergeData = [{
    description: "Ereignisgruppe",
    key: "objectGroup",
    value: "Aufgaben"
   },{
    description: "Ereignis",
    key: "object",
    value: "Aufgabe",
   }
];
//Loop main object and add new property with corresponding values
for( var i in oData) {
  var oNewData = oData[i];
  oNewData['masterAttributes '] = oMergeData[i];
}


问:
A recursive function to extract the files from a nested JSON like object
I have a data which consists of directory name and its files . Given a specific directory name in the argument say , I need to find all the files it encloses .
my data :

```<code>var fileData = {
      dir : 'app',
      files : [
        'index.html',
        {
          dir : 'js',
          files: [
            'main.js',
            'app.js',
            'misc.js',
            {
              dir : 'vendor',
              files : [
                'jquery.js',
                'underscore.js'
              ]
            }
          ]
        },
        {
          dir : 'css',
          files : [
            'reset.css',
            'main.css'
          ]
        }
      ]
    };
</code>```

I have a function listfiles where I am passing the directory name

```<code>listFiles(fileData, 'js')
</code>```

Expected output :

```<code>['main.js','app.js','misc.js','jquery.js','underscore.js']
</code>```

In my code i am able to get the answer in the console but could not return the value .

```<code>listFiles = (data, dirName) => {
          var filesArray = [];
          matchedDir = (data,dirName) => {
            data['files'].map(el => {
                if(typeof(el) === 'object'){
                  return matchedDir(el,dirName)
                }
                else{filesArray.push(el)}
              })
              console.log(filesArray)
            }
          if(Object.values(data).includes(dirName)) {
            return matchedDir(data,dirName)
          }
          else{
            data['files'].map(el => {
              if(typeof(el) === 'object'){
                return this.listFiles(el,dirName)
              }
            })
          }
        return filesArray
}
</code>```

答:
Here's a decomposed approach to the problem using functional techniques.

First implement a generic files function -

```<code>const emptyTree =
  { dir: "", files: [] }

const files = (tree = emptyTree, path = "") =>
  Object(tree) === tree
    ? tree.files.flatMap(f => files(f, `${path}/${tree.dir}`))
    : [ `${path}/${tree}` ]

files(fileData)
// [ "/app/index.html"
// , "/app/js/main.js"
// , "/app/js/app.js"
// , "/app/js/misc.js"
// , "/app/js/vendor/jquery.js"
// , "/app/js/vendor/underscore.js"
// , "/app/css/reset.css"
// , "/app/css/main.css"
// ]
</code>```

Then implement search as a higher-order function, like Array.prototype.filter -

```<code>const identity = x =>
  x

const search = (test = identity, tree = emptyTree) =>
  files(tree).filter(test)
</code>```

Finally, we can use search in intuitive ways -

```<code>search(f => f.endsWith(".js"), fileData)
// [ "/app/js/main.js"
// , "/app/js/app.js"
// , "/app/js/misc.js"
// , "/app/js/vendor/jquery.js"
// , "/app/js/vendor/underscore.js"
// ]

search(f => f.startsWith("/app/css"), fileData)
// [ "/app/css/reset.css"
// , "/app/css/main.css"
// ]
</code>```

By separating a tough problem into isolated parts, each function is easier to write, test, and maintain. With an added advantage that files and search offer even more functionality than your original function and they can be reused more easily in other areas of your program. Hopefully this demonstrates how higher-order functions give you increased flexibility – and with less code too.

Run the complete program in your own browser by expanding the snippet below -

const fileData =
  { dir: 'app', files: [ 'index.html', { dir: 'js', files: [ 'main.js','app.js','misc.js', { dir: 'vendor', files: [ 'jquery.js','underscore.js' ] } ] }, { dir: 'css', files: [ 'reset.css','main.css' ] } ] }

const emptyTree =
  { dir: "", files: [] }

const files = (tree = emptyTree, path = "") =>
  Object(tree) === tree
    ? tree.files.flatMap(f => files(f, `${path}/${tree.dir}`))
    : [ `${path}/${tree}` ]

console.log(files(fileData))
// [ "/app/index.html"
// , "/app/js/main.js"
// , "/app/js/app.js"
// , "/app/js/misc.js"
// , "/app/js/vendor/jquery.js"
// , "/app/js/vendor/underscore.js"
// , "/app/css/reset.css"
// , "/app/css/main.css"
// ]

const identity = x =>
  x

const search = (test = identity, tree = emptyTree) =>
  files(tree).filter(test)

console.log(search(f => f.endsWith(".js"), fileData))
// [ "/app/js/main.js"
// , "/app/js/app.js"
// , "/app/js/misc.js"
// , "/app/js/vendor/jquery.js"
// , "/app/js/vendor/underscore.js"
// ]

console.log(search(f => f.startsWith("/app/css"), fileData))
// [ "/app/css/reset.css"
// , "/app/css/main.css"
// ]```
</div>
</div>
</p>

<hr>

<p>Another approach is to use generators. Notice the similarity between this program and the one above -</p>

```const files = function* (tree = emptyTree, path = "")
{ if (Object(tree) === tree)
    for (const f of tree.files)
      yield* files(f, `${path}/${tree.dir}`)
  else
    yield `${path}/${tree}`
}

const search = function* (test = identity, tree = emptyTree)
{ for (const f of files(tree))
    if (test(f))
      yield f
}
```

<p>Now <code>files</code> and <code>search</code> return a lazy result, where results can be processed one-by-one as they come out of the generator. Or we can collect all of the results using <code>Array.from</code>. The results are the same -</p>

```Array.from(search(f => f.endsWith(".js"), fileData))
// [ "/app/js/main.js"
// , "/app/js/app.js"
// , "/app/js/misc.js"
// , "/app/js/vendor/jquery.js"
// , "/app/js/vendor/underscore.js"
// ]

Array.from(search(f => f.startsWith("/app/css"), fileData))
// [ "/app/css/reset.css"
// , "/app/css/main.css"
// ]
```

<p>Because generators can pause and resume, this program has the added advantage that the computation can stop early. By contrast, the first program using <code>Array.prototype.flatMap</code> and <code>Array.prototype.filter</code> will always iterate through the entire <code>tree</code>.</p>

<p>Expand the snippet below to verify the results in your own browser</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const fileData =
  { dir: 'app', files: [ 'index.html', { dir: 'js', files: [ 'main.js','app.js','misc.js', { dir: 'vendor', files: [ 'jquery.js','underscore.js' ] } ] }, { dir: 'css', files: [ 'reset.css','main.css' ] } ] }

const emptyTree =
  { dir: "", files: [] }

const files = function* (tree = emptyTree, path = "")
{ if (Object(tree) === tree)
    for (const f of tree.files)
      yield* files(f, `${path}/${tree.dir}`)
  else
    yield `${path}/${tree}`
}

console.log(Array.from(files(fileData)))
// [ "/app/index.html"
// , "/app/js/main.js"
// , "/app/js/app.js"
// , "/app/js/misc.js"
// , "/app/js/vendor/jquery.js"
// , "/app/js/vendor/underscore.js"
// , "/app/css/reset.css"
// , "/app/css/main.css"
// ]

const identity = x =>
  x

const search = function* (test = identity, tree = emptyTree)
{ for (const f of files(tree))
    if (test(f))
      yield f
}

console.log(Array.from(search(f => f.endsWith(".js"), fileData)))
// [ "/app/js/main.js"
// , "/app/js/app.js"
// , "/app/js/misc.js"
// , "/app/js/vendor/jquery.js"
// , "/app/js/vendor/underscore.js"
// ]

console.log(Array.from(search(f => f.startsWith("/app/css"), fileData)))
// [ "/app/css/reset.css"
// , "/app/css/main.css"
// ]</code>```

Body:
I have a data which consists of directory name and its files . Given a specific directory name in the argument say , I need to find all the files it encloses .
my data :

var fileData = {
      dir : 'app',
      files : [
        'index.html',
        {
          dir : 'js',
          files: [
            'main.js',
            'app.js',
            'misc.js',
            {
              dir : 'vendor',
              files : [
                'jquery.js',
                'underscore.js'
              ]
            }
          ]
        },
        {
          dir : 'css',
          files : [
            'reset.css',
            'main.css'
          ]
        }
      ]
    };

I have a function listfiles where I am passing the directory name

listFiles(fileData, 'js')

Expected output :

['main.js','app.js','misc.js','jquery.js','underscore.js']

In my code i am able to get the answer in the console but could not return the value .

listFiles = (data, dirName) => {
          var filesArray = [];
          matchedDir = (data,dirName) => {
            data['files'].map(el => {
                if(typeof(el) === 'object'){
                  return matchedDir(el,dirName)
                }
                else{filesArray.push(el)}
              })
              console.log(filesArray)
            }
          if(Object.values(data).includes(dirName)) {
            return matchedDir(data,dirName)
          }
          else{
            data['files'].map(el => {
              if(typeof(el) === 'object'){
                return this.listFiles(el,dirName)
              }
            })
          }
        return filesArray
}

Body:
Here's a decomposed approach to the problem using functional techniques.

First implement a generic files function -

const emptyTree =
  { dir: "", files: [] }

const files = (tree = emptyTree, path = "") =>
  Object(tree) === tree
    ? tree.files.flatMap(f => files(f, `${path}/${tree.dir}`))
    : [ `${path}/${tree}` ]

files(fileData)
// [ "/app/index.html"
// , "/app/js/main.js"
// , "/app/js/app.js"
// , "/app/js/misc.js"
// , "/app/js/vendor/jquery.js"
// , "/app/js/vendor/underscore.js"
// , "/app/css/reset.css"
// , "/app/css/main.css"
// ]

Then implement search as a higher-order function, like Array.prototype.filter -

const identity = x =>
  x

const search = (test = identity, tree = emptyTree) =>
  files(tree).filter(test)

Finally, we can use search in intuitive ways -

search(f => f.endsWith(".js"), fileData)
// [ "/app/js/main.js"
// , "/app/js/app.js"
// , "/app/js/misc.js"
// , "/app/js/vendor/jquery.js"
// , "/app/js/vendor/underscore.js"
// ]

search(f => f.startsWith("/app/css"), fileData)
// [ "/app/css/reset.css"
// , "/app/css/main.css"
// ]

By separating a tough problem into isolated parts, each function is easier to write, test, and maintain. With an added advantage that files and search offer even more functionality than your original function and they can be reused more easily in other areas of your program. Hopefully this demonstrates how higher-order functions give you increased flexibility – and with less code too.

Run the complete program in your own browser by expanding the snippet below -

const fileData =
  { dir: 'app', files: [ 'index.html', { dir: 'js', files: [ 'main.js','app.js','misc.js', { dir: 'vendor', files: [ 'jquery.js','underscore.js' ] } ] }, { dir: 'css', files: [ 'reset.css','main.css' ] } ] }

const emptyTree =
  { dir: "", files: [] }

const files = (tree = emptyTree, path = "") =>
  Object(tree) === tree
    ? tree.files.flatMap(f => files(f, `${path}/${tree.dir}`))
    : [ `${path}/${tree}` ]

console.log(files(fileData))
// [ "/app/index.html"
// , "/app/js/main.js"
// , "/app/js/app.js"
// , "/app/js/misc.js"
// , "/app/js/vendor/jquery.js"
// , "/app/js/vendor/underscore.js"
// , "/app/css/reset.css"
// , "/app/css/main.css"
// ]

const identity = x =>
  x

const search = (test = identity, tree = emptyTree) =>
  files(tree).filter(test)

console.log(search(f => f.endsWith(".js"), fileData))
// [ "/app/js/main.js"
// , "/app/js/app.js"
// , "/app/js/misc.js"
// , "/app/js/vendor/jquery.js"
// , "/app/js/vendor/underscore.js"
// ]

console.log(search(f => f.startsWith("/app/css"), fileData))
// [ "/app/css/reset.css"
// , "/app/css/main.css"
// ]

Another approach is to use generators. Notice the similarity between this program and the one above -

const files = function* (tree = emptyTree, path = "")
{ if (Object(tree) === tree)
    for (const f of tree.files)
      yield* files(f, `${path}/${tree.dir}`)
  else
    yield `${path}/${tree}`
}

const search = function* (test = identity, tree = emptyTree)
{ for (const f of files(tree))
    if (test(f))
      yield f
}

Now files and search return a lazy result, where results can be processed one-by-one as they come out of the generator. Or we can collect all of the results using Array.from. The results are the same -

Array.from(search(f => f.endsWith(".js"), fileData))
// [ "/app/js/main.js"
// , "/app/js/app.js"
// , "/app/js/misc.js"
// , "/app/js/vendor/jquery.js"
// , "/app/js/vendor/underscore.js"
// ]

Array.from(search(f => f.startsWith("/app/css"), fileData))
// [ "/app/css/reset.css"
// , "/app/css/main.css"
// ]

Because generators can pause and resume, this program has the added advantage that the computation can stop early. By contrast, the first program using Array.prototype.flatMap and Array.prototype.filter will always iterate through the entire tree.

Expand the snippet below to verify the results in your own browser

const fileData =
  { dir: 'app', files: [ 'index.html', { dir: 'js', files: [ 'main.js','app.js','misc.js', { dir: 'vendor', files: [ 'jquery.js','underscore.js' ] } ] }, { dir: 'css', files: [ 'reset.css','main.css' ] } ] }

const emptyTree =
  { dir: "", files: [] }

const files = function* (tree = emptyTree, path = "")
{ if (Object(tree) === tree)
    for (const f of tree.files)
      yield* files(f, `${path}/${tree.dir}`)
  else
    yield `${path}/${tree}`
}

console.log(Array.from(files(fileData)))
// [ "/app/index.html"
// , "/app/js/main.js"
// , "/app/js/app.js"
// , "/app/js/misc.js"
// , "/app/js/vendor/jquery.js"
// , "/app/js/vendor/underscore.js"
// , "/app/css/reset.css"
// , "/app/css/main.css"
// ]

const identity = x =>
  x

const search = function* (test = identity, tree = emptyTree)
{ for (const f of files(tree))
    if (test(f))
      yield f
}

console.log(Array.from(search(f => f.endsWith(".js"), fileData)))
// [ "/app/js/main.js"
// , "/app/js/app.js"
// , "/app/js/misc.js"
// , "/app/js/vendor/jquery.js"
// , "/app/js/vendor/underscore.js"
// ]

console.log(Array.from(search(f => f.startsWith("/app/css"), fileData)))
// [ "/app/css/reset.css"
// , "/app/css/main.css"
// ]


问:
Access Data in the navigation controller
I have a controller1 which contains a view which contain many subviews ( Textfields,....).
I use a navigation controller. I push the controller1 and in this controller I push an other controller2.

My problem is to access the data of the controller1, for example I want to access the data of the textfield of my controller1 in the controller2.

How I can do this please ???

Thanks for your answers

答:
As you are using navigation controller you will have access of all the viewcontrollers you pushed on navigation stack. You can retreive any one of them using following code.

```<code>[[self.navigationController viewControllers] objectAtIndex:<Here you need to take care of the correct index of your desired viewcontroller>];
</code>```

//above code will return viewcontroller at that index.

for knowing correct index, use

```<code>NSLog(@"View Controllers : \n%@\n",[self.navigationController viewControllers]];
</code>```

Thanks,

ContentLicense: CC BY-SA 3.0

Body:
As you are using navigation controller you will have access of all the viewcontrollers you pushed on navigation stack. You can retreive any one of them using following code.

[[self.navigationController viewControllers] objectAtIndex:<Here you need to take care of the correct index of your desired viewcontroller>];

//above code will return viewcontroller at that index.

for knowing correct index, use

NSLog(@"View Controllers : \n%@\n",[self.navigationController viewControllers]];

Thanks,


问:
How to create a new row after 3 column in my code
I am customizing a theme in which there was a option to add only three services sections. I had added more three sections and are getting reflected on my HTML. defacult is is createing somthing like this :

row > col1 > col1 > col1 > col1 > col1 > col1

I want to create Like this :

row > col1 > col1 > col1
row > col1 > col1 > col1

Kindly help me with this

```<code><?php
/**
 * lessons Section
 *
 * @package Preschool_and_Kindergarten
*/
     $title        = get_theme_mod( 'preschool_and_kindergarten_lessons_section_title' );
     $description  = get_theme_mod( 'preschool_and_kindergarten_lessons_section_description' );
     $lesson_one   = get_theme_mod( 'preschool_and_kindergarten_lesson_post_one' );
     $lesson_two   = get_theme_mod( 'preschool_and_kindergarten_lesson_post_two' );
     $lesson_three = get_theme_mod( 'preschool_and_kindergarten_lesson_post_three' );
     $lesson_four = get_theme_mod( 'preschool_and_kindergarten_lesson_post_four' );
     $lesson_five = get_theme_mod( 'preschool_and_kindergarten_lesson_post_five' );
     $lesson_six = get_theme_mod( 'preschool_and_kindergarten_lesson_post_six' );
     $lessons_posts = array( $lesson_one, $lesson_two, $lesson_three, $lesson_four, $lesson_five, $lesson_six );
     $lessons_posts = array_diff( array_unique( $lessons_posts ), array('') );
?>
<section class="section-2">
    <div class="container">
        <?php
            preschool_and_kindergarten_get_section_header( $title, $description );

            if( $lessons_posts ):

                $lesson_qry = new WP_Query(array(
                    'post__in'   => $lessons_posts,
                    'orderby'   => 'post__in',
                    'posts_per_page' => -1,
                    'ignore_sticky_posts' => true
                    ));

                if( $lesson_qry->have_posts() ){ ?>
                    <div class="row">

                       <?php
                        while( $lesson_qry->have_posts() ){ $lesson_qry->the_post(); ?>

                            <div class="col">

                                <?php
                                    if( has_post_thumbnail() ){ ?>
                                        <div class="img-holder">
                                            <?php the_post_thumbnail( 'preschool-and-kindergarten-lesson-thumb', array( 'itemprop' => 'image' ) ); ?>
                                        </div>
                                <?php } ?>

                                <div class="text-holder">
                                    <h3 class="title"><?php the_title(); ?></h3>
                                    <?php the_content(); ?>
                                </div>

                            </div>

                        <?php } ?>

                    </div>
                <?php }
            wp_reset_postdata();
        endif; ?>
    </div>
</section>
</code>```

答:
You may use logic like:</p>

```<code>......
......

<?php

                            $col_count = 1;
                            while( $lesson_qry->have_posts() ){ $lesson_qry->the_post(); ?>

                                  <?php if($col_count==1){ ?>
                                    <div class="row">
                                  <?php } ?>

                                        <div class="col">

                                            <?php
                                                if( has_post_thumbnail() ){ ?>
                                                    <div class="img-holder">
                                                        <?php the_post_thumbnail( 'preschool-and-kindergarten-lesson-thumb', array( 'itemprop' => 'image' ) ); ?>
                                                    </div>
                                            <?php } ?>

                                            <div class="text-holder">
                                                <h3 class="title"><?php the_title(); ?></h3>
                                                <?php the_content(); ?>
                                            </div>

                                        </div>

                                  <?php if($col_count==1){ ?>
                                        </div>
                                  <?php } ?>

                       <?php
                                  $col_count++;
                                  if($col_count==4){ $col_count==1; }
                               } ?>

......
......
</code>```

Body:
I am customizing a theme in which there was a option to add only three services sections. I had added more three sections and are getting reflected on my HTML. defacult is is createing somthing like this :

row > col1 > col1 > col1 > col1 > col1 > col1

I want to create Like this :

row > col1 > col1 > col1
row > col1 > col1 > col1

Kindly help me with this

<?php
/**
 * lessons Section
 *
 * @package Preschool_and_Kindergarten
*/
     $title        = get_theme_mod( 'preschool_and_kindergarten_lessons_section_title' );
     $description  = get_theme_mod( 'preschool_and_kindergarten_lessons_section_description' );
     $lesson_one   = get_theme_mod( 'preschool_and_kindergarten_lesson_post_one' );
     $lesson_two   = get_theme_mod( 'preschool_and_kindergarten_lesson_post_two' );
     $lesson_three = get_theme_mod( 'preschool_and_kindergarten_lesson_post_three' );
     $lesson_four = get_theme_mod( 'preschool_and_kindergarten_lesson_post_four' );
     $lesson_five = get_theme_mod( 'preschool_and_kindergarten_lesson_post_five' );
     $lesson_six = get_theme_mod( 'preschool_and_kindergarten_lesson_post_six' );
     $lessons_posts = array( $lesson_one, $lesson_two, $lesson_three, $lesson_four, $lesson_five, $lesson_six );
     $lessons_posts = array_diff( array_unique( $lessons_posts ), array('') );
?>

        <?php
            preschool_and_kindergarten_get_section_header( $title, $description );

            if( $lessons_posts ):

                $lesson_qry = new WP_Query(array(
                    'post__in'   => $lessons_posts,
                    'orderby'   => 'post__in',
                    'posts_per_page' => -1,
                    'ignore_sticky_posts' => true
                    ));

                if( $lesson_qry->have_posts() ){ ?>

                       <?php
                        while( $lesson_qry->have_posts() ){ $lesson_qry->the_post(); ?>

                                <?php
                                    if( has_post_thumbnail() ){ ?>

                                            <?php the_post_thumbnail( 'preschool-and-kindergarten-lesson-thumb', array( 'itemprop' => 'image' ) ); ?>

                                <?php } ?>

<?php the_title(); ?>

                                    <?php the_content(); ?>

                        <?php } ?>

                <?php }
            wp_reset_postdata();
        endif; ?>

Body:
You may use logic like:

......
......

<?php

                            $col_count = 1;
                            while( $lesson_qry->have_posts() ){ $lesson_qry->the_post(); ?>

                                  <?php if($col_count==1){ ?>
                                    <div class="row">
                                  <?php } ?>

                                        <div class="col">

                                            <?php
                                                if( has_post_thumbnail() ){ ?>
                                                    <div class="img-holder">
                                                        <?php the_post_thumbnail( 'preschool-and-kindergarten-lesson-thumb', array( 'itemprop' => 'image' ) ); ?>
                                                    </div>
                                            <?php } ?>

                                            <div class="text-holder">
                                                <h3 class="title"><?php the_title(); ?></h3>
                                                <?php the_content(); ?>
                                            </div>

                                        </div>

                                  <?php if($col_count==1){ ?>
                                        </div>
                                  <?php } ?>

                       <?php
                                  $col_count++;
                                  if($col_count==4){ $col_count==1; }
                               } ?>

......
......


问:
Why regex "\\[\\]" is redundant in Java?
I want to match just the bracket [], in my code:

```<code>// #peekToken() -> String
do { ... } while (context.peekToken().matches("\\[\\]"));
</code>```

the intellij says:

and the auto-fixing makes it into:

```<code>"\\[]"
</code>```

Why are they the same?

答:
This is because the character "close bracket" ] is not a regular expression unless there was a bracket opened [ before. Therefore it is redundant to escape it \\], since Java is smart enough to know we are searching for the character itself in that case.

You can read the documentation for more informations on contexts where characters are percieved as regular-expressions.

Body:
I want to match just the bracket [], in my code:

// #peekToken() -> String
do { ... } while (context.peekToken().matches("\\[\\]"));

the intellij says:

and the auto-fixing makes it into:

"\\[]"

Why are they the same?


问:
Why is tempered mcmc fit not convering well?
I am trying to fit a simple straight line y=mx+c type to some synthetic data using parallel-tempered mcmc. My goal is to just be able to understand how to use it, so that I can apply to some more complex models later. The example I am trying is the replica of what has already been done in a simple emcee code :
http://dfm.io/emcee/current/user/line/
but instead of using mcmc, I want to use parallel-tempered mcmc:
http://dfm.io/emcee/current/user/pt/

Here is a working code:

```<code>import numpy as np
from emcee import PTSampler
import emcee

# Choose the "true" parameters.
m_true = -0.9594
b_true = 4.294
f_true = 0.534

# Generate some synthetic data from the model.
N = 50
x = np.sort(10*np.random.rand(N))
yerr = 0.1+0.5*np.random.rand(N)
y = m_true*x+b_true
y += np.abs(f_true*y) * np.random.randn(N)
y += yerr * np.random.randn(N)

def lnlike(theta, x, y, yerr):
    m, b, lnf = theta
    model = m * x + b
    inv_sigma2 = 1.0/(yerr**2 + model**2*np.exp(2*lnf))
    return -0.5*(np.sum((y-model)**2*inv_sigma2 - np.log(inv_sigma2)))
def lnprior(theta):
    m, b, lnf = theta
    if -5.0 < m < 0.5 and 0.0 < b < 10.0 and -10.0 < lnf < 1.0:
        return 0.0
    return -np.inf
def lnprob(theta, x, y, yerr):
    lp = lnprior(theta)
    if not np.isfinite(lp):
        return -np.inf
    return lp + lnlike(theta, x, y, yerr)

import scipy.optimize as op
nll = lambda *args: -lnlike(*args)
result = op.minimize(nll, [m_true, b_true, np.log(f_true)], args=(x, y, yerr))
m_ml, b_ml, lnf_ml = result["x"]
init = [0.5, m_ml, b_ml, lnf_ml]

ntemps = 10
nwalkers = 100
ndim = 3
from multiprocessing import Pool
pos = np.random.uniform(low=-1, high=1, size=(ntemps, nwalkers, ndim))
for i in range(ntemps):
    #initialize parameters near scipy optima
    pos[i:,] = np.array([result["x"] + 1e-4*np.random.randn(ndim) for i in range(nwalkers)])
pool = Pool(processes=4)
sampler=PTSampler(ntemps,nwalkers, ndim, lnlike, lnprior, loglargs=(x, y, yerr), pool=pool)# args=(x, y, yerr))
#burn-in
sampler.run_mcmc(pos, 1000)
sampler.reset()
sampler.run_mcmc(pos, 10000, thin=10)
samples = sampler.chain.reshape((-1, ndim))
print('Number of posterior samples is {}'.format(samples.shape[0]))
#print best fit value together with errors
print(map(lambda v: (v[1], v[2]-v[1], v[1]-v[0]),
                             zip(*np.percentile(samples, [16, 50, 84],
                                                axis=0))))

import corner
fig = corner.corner(samples, labels=["$m$", "$b$", "$\ln\,f$"],
                      truths=[m_true, b_true, np.log(f_true)])
fig.savefig("triangle.png")
</code>```

The only problem when running this code is I get optimal parameters value which are way off the true values. And increasing the number of walkers or samples is not helping in any sense. Can anyone please advice why tempered-mcmc is not working here?

Update:

I found out a useful package called ptemcee (https://pypi.org/project/ptemcee/#description), although the documentation of this package is non-existent. It seems that this package might be useful, any help on how to implement the same linear fitting with this package would also be highly appreciated.

答:
I have modified some lines

import time
import numpy as np
from emcee import PTSampler
import corner
import matplotlib.pyplot as plt
import scipy.optimize as op

t1 = time.time()

np.random.seed(6) # To reproduce results
# Choose the "true" parameters.
m_true = -0.9594
b_true = 4.294
f_true = 0.534

# Generate some synthetic data from the model.
N = 50
x = np.sort(10 * np.random.rand(N))
yerr = 0.1 + 0.5 * np.random.rand(N)
y_1 = m_true * x + b_true
y = np.abs(f_true * y_1) * np.random.randn(N) + y_1
y += yerr * np.random.randn(N)

plt.plot(x, y, 'o')

# With emcee

def lnlike(theta, x, y, yerr):
    m, b, lnf = theta
    model = m * x + b
    inv_sigma2 = 1.0/(yerr**2 + model**2*np.exp(2*lnf))
    return -0.5*(np.sum((y-model)**2*inv_sigma2 - np.log(inv_sigma2)))
def lnprior(theta):
    m, b, lnf = theta
    if -5.0 < m < 0.5 and 0.0 < b < 10.0 and -10.0 < lnf < 1.0:
        return 0.0
    return -np.inf
def lnprob(theta, x, y, yerr):
    lp = lnprior(theta)
    if not np.isfinite(lp):
        return -np.inf
    return lp + lnlike(theta, x, y, yerr)

nll = lambda *args: -lnlike(*args)
result = op.minimize(nll, [m_true, b_true, np.log(f_true)], args=(x, y, yerr))
m_ml, b_ml, lnf_ml = result["x"]

init = [0.5, m_ml, b_ml, lnf_ml]

ntemps = 10
nwalkers = 100
ndim = 3

pos = np.random.uniform(low=-1, high=1, size=(ntemps, nwalkers, ndim))
for i in range(ntemps):
    pos[i:, :] = np.array([result["x"] + 1e-4*np.random.randn(ndim) for i in range(nwalkers)])

sampler = PTSampler(ntemps, nwalkers, ndim, lnlike, lnprior, loglargs=(x, y, yerr), threads=4) # args=(x, y, yerr))

#burn-in
print(pos.shape)
sampler.run_mcmc(pos, 100)
sampler.reset()
sampler.run_mcmc(pos, 5000, thin=10)
samples = sampler.chain.reshape((-1, ndim))

print('Number of posterior samples is {}'.format(samples.shape[0]))

#print best fit value together with errors

p1, p2, p3 = map(lambda v: (v[1], v[2]-v[1], v[1]-v[0]),
                             zip(*np.percentile(samples, [16, 50, 84],
                                                axis=0)))

print(p1, '\n', p2, '\n', p3)

fig = corner.corner(samples, labels=["$m$", "$b$", "$\ln\,f$"],
                      truths=[m_true, b_true, np.log(f_true)])

t2 = time.time()

print('It took {:.3f} s'.format(t2 - t1))

plt.show()
```

<p>The figure I get with <code>corner</code> is:</p>

<p><img src="https://i.stack.imgur.com/ei3an.png" alt="enter image description here"></p>

<p>The important line is</p>

<pre class="lang-py prettyprint-override"><code>sampler = PTSampler(ntemps, nwalkers, ndim, lnlike, lnprior, loglargs=(x, y, yerr), threads=4)
</code>```

I have used threads=4 instead of Pool.

Look closely at this line print(p1, '\n', p2, '\n', p3), it prints the values of m_true, b_true and f_true you get:

(-1.277782877669762, 0.5745273177144817, 2.0813620981463297)
(4.800481378230051, 3.1747356851201163, 2.245189235990341)
(-0.9391847529845194, 1.1196053087321716, 3.6017609114364273)
```

<p>For <code>f</code>, you need <code>np.exp(-0.93918)</code>, which is <code>0.3909</code>, which is close to <code>0.534</code>. The values you get are close (<code>-1.277</code> compared to <code>-0.9594</code> and <code>4.8</code> compared to <code>4.294</code>), although the errors are not bad (except for <code>f</code>). I mean, are you expecting to get the exact numbers? With this method, in my computer, it takes 111 s to complete, is that normal?</p>

<p>Let's try something different. Let's be clear: the problem is not easy when <code>f_true</code> is added. I will use <code>pymc3</code> (you don't need to know how to use <code>pymc3</code>, I want to check the results found by <code>emcee</code>).</p>

<pre class="lang-py prettyprint-override"><code>import time
import numpy as np
import corner
import matplotlib.pyplot as plt
import pymc3 as pm

t1 = time.time()

np.random.seed(6)
# Choose the "true" parameters.
m_true = -0.9594
b_true = 4.294
f_true = 0.534

# Generate some synthetic data from the model.
N = 50
x = np.sort(10 * np.random.rand(N))
yerr = 0.1 + 0.5 * np.random.rand(N)
y_1 = m_true * x + b_true
y = np.abs(f_true * y_1) * np.random.randn(N) + y_1
y += yerr * np.random.randn(N)

plt.plot(x, y, 'o')

with pm.Model() as model: # model specifications in PyMC3 are wrapped in a with-statement
    # Define priors
    f = pm.HalfCauchy('f', beta=5)
    m = pm.Normal('m', 0, sd=20)
    b = pm.Normal('b', 0, sd=20)

    mu2 = b + m * x
    sigma2 = yerr**2 + f**2 * (y_1)**2

    post = pm.Normal('y', mu=mu2, sd=pm.math.sqrt(sigma2), observed=y)

with model:
    trace = pm.sample(2000, tune=2000)

print(pm.summary(trace))
pm.traceplot(trace)

all_values = np.stack([trace.get_values('b'), trace.get_values('m'), trace.get_values('f')], axis=1)

fig2 = corner.corner(all_values, labels=["$b$", "$m$", "$f$"],
                      truths=[b_true, m_true, f_true])

t2 = time.time()

print('It took {:.3f} s'.format(t2 - t1))

plt.show()
</code>```

The summary is

```<code>       mean        sd  mc_error   hpd_2.5  hpd_97.5        n_eff      Rhat
m -0.995545  0.067818  0.001174 -1.123187 -0.857653  2685.610018  1.000121
b  4.398158  0.332526  0.005585  3.767336  5.057909  2746.736563  1.000201
f  0.425442  0.063884  0.000904  0.311037  0.554446  4195.591204  1.000309
</code>```

The important part is the column mean, you see that the values found by pymc3 are close to the true values. The columns hpd_2.5 and hpd_97.5 are the errors for f, b and m. And it took 14 s.

The figure I get with corner is

You will say that the results of emcee are not quite good, but if you really want more accuracy, you have to modify this function:

def lnprior(theta):
    m, b, lnf = theta
    if -5.0 < m < 0.5 and 0.0 < b < 10.0 and -10.0 < lnf < 1.0:
        return 0.0
    return -np.inf
```

The famous prior. In this case, it is flat, and since there are a lot of priors...

Body:
I am trying to fit a simple straight line y=mx+c type to some synthetic data using parallel-tempered mcmc. My goal is to just be able to understand how to use it, so that I can apply to some more complex models later. The example I am trying is the replica of what has already been done in a simple emcee code :
http://dfm.io/emcee/current/user/line/
but instead of using mcmc, I want to use parallel-tempered mcmc:
http://dfm.io/emcee/current/user/pt/

Here is a working code:

import numpy as np
from emcee import PTSampler
import emcee

# Choose the "true" parameters.
m_true = -0.9594
b_true = 4.294
f_true = 0.534

# Generate some synthetic data from the model.
N = 50
x = np.sort(10*np.random.rand(N))
yerr = 0.1+0.5*np.random.rand(N)
y = m_true*x+b_true
y += np.abs(f_true*y) * np.random.randn(N)
y += yerr * np.random.randn(N)

def lnlike(theta, x, y, yerr):
    m, b, lnf = theta
    model = m * x + b
    inv_sigma2 = 1.0/(yerr**2 + model**2*np.exp(2*lnf))
    return -0.5*(np.sum((y-model)**2*inv_sigma2 - np.log(inv_sigma2)))
def lnprior(theta):
    m, b, lnf = theta
    if -5.0 < m < 0.5 and 0.0 < b < 10.0 and -10.0 < lnf < 1.0:
        return 0.0
    return -np.inf
def lnprob(theta, x, y, yerr):
    lp = lnprior(theta)
    if not np.isfinite(lp):
        return -np.inf
    return lp + lnlike(theta, x, y, yerr)

import scipy.optimize as op
nll = lambda *args: -lnlike(*args)
result = op.minimize(nll, [m_true, b_true, np.log(f_true)], args=(x, y, yerr))
m_ml, b_ml, lnf_ml = result["x"]
init = [0.5, m_ml, b_ml, lnf_ml]

ntemps = 10
nwalkers = 100
ndim = 3
from multiprocessing import Pool
pos = np.random.uniform(low=-1, high=1, size=(ntemps, nwalkers, ndim))
for i in range(ntemps):
    #initialize parameters near scipy optima
    pos[i:,] = np.array([result["x"] + 1e-4*np.random.randn(ndim) for i in range(nwalkers)])
pool = Pool(processes=4)
sampler=PTSampler(ntemps,nwalkers, ndim, lnlike, lnprior, loglargs=(x, y, yerr), pool=pool)# args=(x, y, yerr))
#burn-in
sampler.run_mcmc(pos, 1000)
sampler.reset()
sampler.run_mcmc(pos, 10000, thin=10)
samples = sampler.chain.reshape((-1, ndim))
print('Number of posterior samples is {}'.format(samples.shape[0]))
#print best fit value together with errors
print(map(lambda v: (v[1], v[2]-v[1], v[1]-v[0]),
                             zip(*np.percentile(samples, [16, 50, 84],
                                                axis=0))))

import corner
fig = corner.corner(samples, labels=["$m$", "$b$", "$\ln\,f$"],
                      truths=[m_true, b_true, np.log(f_true)])
fig.savefig("triangle.png")

The only problem when running this code is I get optimal parameters value which are way off the true values. And increasing the number of walkers or samples is not helping in any sense. Can anyone please advice why tempered-mcmc is not working here?

Update:

I found out a useful package called ptemcee (https://pypi.org/project/ptemcee/#description), although the documentation of this package is non-existent. It seems that this package might be useful, any help on how to implement the same linear fitting with this package would also be highly appreciated.

Body:
I have modified some lines

import time
import numpy as np
from emcee import PTSampler
import corner
import matplotlib.pyplot as plt
import scipy.optimize as op

t1 = time.time()

np.random.seed(6) # To reproduce results
# Choose the "true" parameters.
m_true = -0.9594
b_true = 4.294
f_true = 0.534

# Generate some synthetic data from the model.
N = 50
x = np.sort(10 * np.random.rand(N))
yerr = 0.1 + 0.5 * np.random.rand(N)
y_1 = m_true * x + b_true
y = np.abs(f_true * y_1) * np.random.randn(N) + y_1
y += yerr * np.random.randn(N)

plt.plot(x, y, 'o')

# With emcee

def lnlike(theta, x, y, yerr):
    m, b, lnf = theta
    model = m * x + b
    inv_sigma2 = 1.0/(yerr**2 + model**2*np.exp(2*lnf))
    return -0.5*(np.sum((y-model)**2*inv_sigma2 - np.log(inv_sigma2)))
def lnprior(theta):
    m, b, lnf = theta
    if -5.0 < m < 0.5 and 0.0 < b < 10.0 and -10.0 < lnf < 1.0:
        return 0.0
    return -np.inf
def lnprob(theta, x, y, yerr):
    lp = lnprior(theta)
    if not np.isfinite(lp):
        return -np.inf
    return lp + lnlike(theta, x, y, yerr)

nll = lambda *args: -lnlike(*args)
result = op.minimize(nll, [m_true, b_true, np.log(f_true)], args=(x, y, yerr))
m_ml, b_ml, lnf_ml = result["x"]

init = [0.5, m_ml, b_ml, lnf_ml]

ntemps = 10
nwalkers = 100
ndim = 3

pos = np.random.uniform(low=-1, high=1, size=(ntemps, nwalkers, ndim))
for i in range(ntemps):
    pos[i:, :] = np.array([result["x"] + 1e-4*np.random.randn(ndim) for i in range(nwalkers)])

sampler = PTSampler(ntemps, nwalkers, ndim, lnlike, lnprior, loglargs=(x, y, yerr), threads=4) # args=(x, y, yerr))

#burn-in
print(pos.shape)
sampler.run_mcmc(pos, 100)
sampler.reset()
sampler.run_mcmc(pos, 5000, thin=10)
samples = sampler.chain.reshape((-1, ndim))

print('Number of posterior samples is {}'.format(samples.shape[0]))

#print best fit value together with errors

p1, p2, p3 = map(lambda v: (v[1], v[2]-v[1], v[1]-v[0]),
                             zip(*np.percentile(samples, [16, 50, 84],
                                                axis=0)))

print(p1, '\n', p2, '\n', p3)

fig = corner.corner(samples, labels=["$m$", "$b$", "$\ln\,f$"],
                      truths=[m_true, b_true, np.log(f_true)])

t2 = time.time()

print('It took {:.3f} s'.format(t2 - t1))

plt.show()

The figure I get with corner is:

The important line is

sampler = PTSampler(ntemps, nwalkers, ndim, lnlike, lnprior, loglargs=(x, y, yerr), threads=4)

I have used threads=4 instead of Pool.

Look closely at this line print(p1, '\n', p2, '\n', p3), it prints the values of m_true, b_true and f_true you get:

(-1.277782877669762, 0.5745273177144817, 2.0813620981463297)
(4.800481378230051, 3.1747356851201163, 2.245189235990341)
(-0.9391847529845194, 1.1196053087321716, 3.6017609114364273)

For f, you need np.exp(-0.93918), which is 0.3909, which is close to 0.534. The values you get are close (-1.277 compared to -0.9594 and 4.8 compared to 4.294), although the errors are not bad (except for f). I mean, are you expecting to get the exact numbers? With this method, in my computer, it takes 111 s to complete, is that normal?

Let's try something different. Let's be clear: the problem is not easy when f_true is added. I will use pymc3 (you don't need to know how to use pymc3, I want to check the results found by emcee).

import time
import numpy as np
import corner
import matplotlib.pyplot as plt
import pymc3 as pm

t1 = time.time()

np.random.seed(6)
# Choose the "true" parameters.
m_true = -0.9594
b_true = 4.294
f_true = 0.534

# Generate some synthetic data from the model.
N = 50
x = np.sort(10 * np.random.rand(N))
yerr = 0.1 + 0.5 * np.random.rand(N)
y_1 = m_true * x + b_true
y = np.abs(f_true * y_1) * np.random.randn(N) + y_1
y += yerr * np.random.randn(N)

plt.plot(x, y, 'o')

with pm.Model() as model: # model specifications in PyMC3 are wrapped in a with-statement
    # Define priors
    f = pm.HalfCauchy('f', beta=5)
    m = pm.Normal('m', 0, sd=20)
    b = pm.Normal('b', 0, sd=20)

    mu2 = b + m * x
    sigma2 = yerr**2 + f**2 * (y_1)**2

    post = pm.Normal('y', mu=mu2, sd=pm.math.sqrt(sigma2), observed=y)

with model:
    trace = pm.sample(2000, tune=2000)

print(pm.summary(trace))
pm.traceplot(trace)

all_values = np.stack([trace.get_values('b'), trace.get_values('m'), trace.get_values('f')], axis=1)

fig2 = corner.corner(all_values, labels=["$b$", "$m$", "$f$"],
                      truths=[b_true, m_true, f_true])

t2 = time.time()

print('It took {:.3f} s'.format(t2 - t1))

plt.show()

The summary is

       mean        sd  mc_error   hpd_2.5  hpd_97.5        n_eff      Rhat
m -0.995545  0.067818  0.001174 -1.123187 -0.857653  2685.610018  1.000121
b  4.398158  0.332526  0.005585  3.767336  5.057909  2746.736563  1.000201
f  0.425442  0.063884  0.000904  0.311037  0.554446  4195.591204  1.000309

The important part is the column mean, you see that the values found by pymc3 are close to the true values. The columns hpd_2.5 and hpd_97.5 are the errors for f, b and m. And it took 14 s.

The figure I get with corner is

You will say that the results of emcee are not quite good, but if you really want more accuracy, you have to modify this function:

def lnprior(theta):
    m, b, lnf = theta
    if -5.0 < m < 0.5 and 0.0 < b < 10.0 and -10.0 < lnf < 1.0:
        return 0.0
    return -np.inf

The famous prior. In this case, it is flat, and since there are a lot of priors...


问:
Does Google Dataproc support Apache Impala?
I am new to using cloud services and navigating Google's Cloud Platform is quite intimidating. When it comes to Google Dataproc, they do advertise Hadoop, Spark and Hive.

My question is, is Impala available at all?

I would like to do some benchmarking projects using all four of these tools and I require Apache Impala along side Spark/Hive.

答:
You can try also using another new instance of Dataproc, instead of using the default.

For example, you can create a Dataproc instance with HUE (Hadoop User Experience) which is an interface to handle Hadoop cluster built by Cloudera. The advantage here is that HUE has as a default component Apache Impala. It also has Pig, Hive, etc. So it's a pretty good solution for using Impala.

Another solution will be to create your own cluster by the beginning but is not a good idea (at least you want to customize everything). With this way, you can install Impala.

Here is a link, for more information:

https://github.com/GoogleCloudPlatform/dataproc-initialization-actions/tree/master/hue


问:
NPM browserstack alias installed by package.json for TestCafe not recognized
Installing 'testcafe-browser-provider-browserstack' by package.json causes Jenkins job not to recognize 'browserstack'

Tried removing from package.json and install from command line but dependencies cause npm install to error.

testcafe 1.1.4
testcafe-browser-provider-browserstack 1.8.0

npm install

node_modules/.bin/testcafe -e  browserstack:safari  auth-subscriber-access-myaccount.js

ERROR Unable to find the browser. "browserstack:safari" is not a browser alias or path to an executable file.

答:
One way to debug the issue would be to run the test explicitly with your BrowserStack credentials with the following command - </p>

```<code>BROWSERSTACK_USERNAME="YOUR_USERNAME" BROWSERSTACK_ACCESS_KEY="YOUR_KEY" testcafe "browserstack:safari@12.0:OS X Mojave" "path/to/test/file.js"
</code>```

Body:
One way to debug the issue would be to run the test explicitly with your BrowserStack credentials with the following command -

BROWSERSTACK_USERNAME="YOUR_USERNAME" BROWSERSTACK_ACCESS_KEY="YOUR_KEY" testcafe "browserstack:safari@12.0:OS X Mojave" "path/to/test/file.js"


问:
Can Web-bluetooth provision nodes in a BLE-mesh?
I have a web-app that needs to communicate with about 48 BLE devices in a BLE-mesh.

I found that Web-bluetooth can work with one bluetooth device, but could not find if there is a way to provision BLE-mesh and then send messages to nodes in the mesh with Web-bluetooth.

If it matters, I am putting it here for information, that the web-app is an Angular app written in Typescript. For Web-bluetooth, I am using this library https://github.com/manekinekko/angular-web-bluetooth.

答:
I suspect that "Smart Mesh" technology is not the standard Bluetooth mesh from Bluetooth SIG (and it's 33,000 members), so watch out for that. I could be wrong but I don't see anything from that company in the qualified mesh products list: https://www.bluetooth.com/bluetooth-technology/topology-options/le-mesh/mesh-qualified/

The place to look for answers to questions like this is in the mesh profile 1.0 specification:

https://www.bluetooth.com/specifications/mesh-specifications/

The mesh intro for developers is a shorter read for getting started: https://www.bluetooth.com/bluetooth-resources/?types=paper&categories=&tags=mesh&keyword=

And for hands-on experience, there are a couple of "study guides" with coding projects, from the SIG:

https://www.bluetooth.com/bluetooth-resources/?tags=mesh&keyword&types=study-guide

In short though, provisioning can be performed over two "bearers" including GATT (known as PB-GATT). Since Web Bluetooth supports connection-oriented GATT, I believe you should be able to implement provisioning over GATT using Web Bluetooth. You will be unable to access the Device UUID in the ServiceData advertising packets from unprovisioned nodes, but it's likely this will not be an issue for you.... depends on detailed requirements, however.

Hope this helps.

Additional: To "send messages" you need to use a proxy node and the proxy protocol. This allows GATT to be used over a connection to send mesh messages into / back from your mesh network. There's a hands-on study guide which actually uses Web Bluetooth at bluetooth.com here: https://www.bluetooth.com/bluetooth-resources/?tags=mesh&keyword&types=study-guide

Also... you can see me demonstrating Web Bluetooth controlling a small (64 nodes) Bluetooth mesh network here: https://youtu.be/1rxgY1EnmJw?t=1173


问:
Concatenate a string on map function javascript
I have an object lengthOfStay in which I'm trying to concatenate the values inside it and put it on customerApplication.lengthOfStay

```<code>lengthOfStay:{
    yrs: '',
    mos:''
},
customerApplication: {
    length_of_stay: this.lengthOfStayYrsMos
}

computed: {
     lengthOfStayYrsMos(){
        return this.customerApplication.length_of_stay =
        Object.keys(this.lengthOfStay).map(k =>  this.lengthOfStay[k]).join(" ")
      }
}
</code>```

so for the concatenation looks good and the result for example is

```<code>lengthOfStay:{
    yrs: '2',
    mos:'2'
},
//result
customerApplication: {
    length_of_stay: "2 2"
}
</code>```

how can I concatenate a string on it ? so that the result would be

```<code>customerApplication: {
    length_of_stay: "2 Yrs. & 2 Mos."
}
</code>```

答:
You can use Object.entries() to get both key and value from object, then change first character to uppercase and concatenate in desired format

let data ={ lengthOfStay:{ yrs: '2', mos:'2' }}
let capFirstChar = (str)=> str[0].toUpperCase() + str.substr(1,)

let op = Object.entries(data.lengthOfStay)
               .map(([key, value]) => `${value} ${capFirstChar(key)}.`)
               .join(' & ')

console.log(op)```

Body:
I have an object lengthOfStay in which I'm trying to concatenate the values inside it and put it on customerApplication.lengthOfStay

lengthOfStay:{
    yrs: '',
    mos:''
},
customerApplication: {
    length_of_stay: this.lengthOfStayYrsMos
}

computed: {
     lengthOfStayYrsMos(){
        return this.customerApplication.length_of_stay =
        Object.keys(this.lengthOfStay).map(k =>  this.lengthOfStay[k]).join(" ")
      }
}

so for the concatenation looks good and the result for example is

lengthOfStay:{
    yrs: '2',
    mos:'2'
},
//result
customerApplication: {
    length_of_stay: "2 2"
}

how can I concatenate a string on it ? so that the result would be

customerApplication: {
    length_of_stay: "2 Yrs. & 2 Mos."
}


问:
laravel request not redirect right page
I want to make a filter based on request kelas on database table. It gives me no error just when I click one of the filter, it don't show jadwal page with my filter. It show the main page but the url is right like lps.com/?jadwal-2

I have done make a middleware called SanitizeMiddleware from stackoverflow but still not worked.

This is my route web.php

```<code>Route::get('/', 'HomepageController@index');

Route::resource('pengumuman', 'PengumumanController');
Route::resource('jadwal', 'JadwalController');
Route::resource('rapot', 'RapotController');
</code>```

This is my index() from my JadwalController

```<code>public function index()
{
    if (request()->has('kelas')) {
        $jadwal = jadwal::where('kelas', request('kelas'));
    } else {
        $jadwal = jadwal::all();
    }

    return view('jadwal.index')->with('jadwal',$jadwal);

    //$jadwal = jadwal::all();
    //return view('jadwal.index')->with('jadwal',$jadwal);
}
</code>```

This is my index.blade.php

```<code><div class="container">
    <br>
    <h1>
        <strong>Jadwal Pelajaran</strong>
    </h1>
    <a href="/?kelas=1">jadwwal kelas 1</a>
    <a href="/?kelas-2">jadwal kelas 2</a>
    <a href="/?kelas-3">jadwal kelas 3</a>
    </form>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th scope="col"></th>
                <th scope="col">07.00-08.00</th>
                <th scope="col">08.00-09.00</th>
                <th scope="col">09.00-10.00</th>
                <th scope="col">10.00-11.00</th>
                <th scope="col">10.00-12.00</th>
                <th scope="col">action</th>
            </tr>
        </thead>
        <tbody>
            @if(count($jadwal)>0)
                @foreach($jadwal as $jadwals)
                    <tr>
                        <th scope="row">{{$jadwals->hari}}</th>
                        <td>{{$jadwals->jamke1}}</td>
                        <td>{{$jadwals->jamke2}}</td>
                        <td>{{$jadwals->jamke3}}</td>
                        <td>{{$jadwals->jamke4}}</td>
                        <td>{{$jadwals->jamke4}}</td>
                        <td>
                            <a href="/jadwal/{{$jadwals->id}}/edit" class="btn btn-info">Edit</a>
                        </td>
                    </tr>
                @endforeach
            @else
                <p>tidak ada jadwal</p>
            @endif
        </tbody>
    </table>
</div>
</code>```

And this is the picture of problem:-

this is my jadwal page before filter

this my page after i click the filter using request()

答:
its just a simple url issue

as you see the list of jadwal is displayed in the route

```<code>lps.com/jadwal
</code>```

What is the issue as you see

```<code><a href="/?kelas=1">jadwwal kelas 1</a>
<a href="/?kelas=2">jadwal kelas 2</a>
<a href="/?kelas=3">jadwal kelas 3</a>
</code>```

While Clicking this any of the link its redirecting to

For Example If i Clicked jadwwal kelas 1

```<code>lps.com/?kelas=1
</code>```

So Its not redireting to lps.com/jadwal?kelas=1

So Try to change

```<code><a href="jadwal/?kelas=1">jadwwal kelas 1</a>
<a href="jadwal/?kelas=2">jadwal kelas 2</a>
<a href="jadwal/?kelas=3">jadwal kelas 3</a>
</code>```

And the final thing if you are using the pagination

```<code>{{$jadwal->links()}}
</code>```

This Will only add the ?page=yourCurrentPageNumber

But in Some situation You need both the filters and pagination

So Try below Method

```<code>{{$jadwal->appends(request()->input())->links()}}
</code>```

It will appends all the GET Request Parameter

So If You need to vist the nth page of kelas=1 its will work

Hope its helps

if you are facing and issue kindly comment below

Title: laravel request not redirect right page

Body:
I want to make a filter based on request kelas on database table. It gives me no error just when I click one of the filter, it don't show jadwal page with my filter. It show the main page but the url is right like lps.com/?jadwal-2

I have done make a middleware called SanitizeMiddleware from stackoverflow but still not worked.

This is my route web.php

Route::get('/', 'HomepageController@index');

Route::resource('pengumuman', 'PengumumanController');
Route::resource('jadwal', 'JadwalController');
Route::resource('rapot', 'RapotController');

This is my index() from my JadwalController

public function index()
{
    if (request()->has('kelas')) {
        $jadwal = jadwal::where('kelas', request('kelas'));
    } else {
        $jadwal = jadwal::all();
    }

    return view('jadwal.index')->with('jadwal',$jadwal);

    //$jadwal = jadwal::all();
    //return view('jadwal.index')->with('jadwal',$jadwal);
}

This is my index.blade.php

        Jadwal Pelajaran

    jadwwal kelas 1
    jadwal kelas 2
    jadwal kelas 3
    </form>

                07.00-08.00
                08.00-09.00
                09.00-10.00
                10.00-11.00
                10.00-12.00
                action

            @if(count($jadwal)>0)
                @foreach($jadwal as $jadwals)

                        {{$jadwals->hari}}
                        {{$jadwals->jamke1}}
                        {{$jadwals->jamke2}}
                        {{$jadwals->jamke3}}
                        {{$jadwals->jamke4}}
                        {{$jadwals->jamke4}}

                            id}}/edit" class="btn btn-info">Edit

                @endforeach
            @else

tidak ada jadwal

            @endif

And this is the picture of problem:-

this is my jadwal page before filter

this my page after i click the filter using request()

Body:
its just a simple url issue

as you see the list of jadwal is displayed in the route

lps.com/jadwal

What is the issue as you see

<a href="/?kelas=1">jadwwal kelas 1</a>
<a href="/?kelas=2">jadwal kelas 2</a>
<a href="/?kelas=3">jadwal kelas 3</a>

While Clicking this any of the link its redirecting to

For Example If i Clicked jadwwal kelas 1

lps.com/?kelas=1

So Its not redireting to lps.com/jadwal?kelas=1

So Try to change

<a href="jadwal/?kelas=1">jadwwal kelas 1</a>
<a href="jadwal/?kelas=2">jadwal kelas 2</a>
<a href="jadwal/?kelas=3">jadwal kelas 3</a>

And the final thing if you are using the pagination

{{$jadwal->links()}}

This Will only add the ?page=yourCurrentPageNumber

But in Some situation You need both the filters and pagination

So Try below Method

{{$jadwal->appends(request()->input())->links()}}

It will appends all the GET Request Parameter

So If You need to vist the nth page of kelas=1 its will work

Hope its helps

if you are facing and issue kindly comment below


问:
Error while upgrading Ubuntu 18.04 LTS packages from Local Repository
I am maintaining a local repository for Ubuntu 18.04 LTS and recently updated the repository using apt-mirror. The I tried to upgrade the packages using the following commands

```<code>sudo apt-get clean
sudo apt-get update
sudo apt-get upgrade
</code>```

The first two commands worked without any error. However, sudo apt-get upgrade resulted in the following error

```<code>Get:645 http://192.168.1.1/ubuntuRepo bionic-updates/multiverse amd64 virtualbox-guest-additions-iso all 5.2.18-1~ubuntu18.04.1 [39.0 MB]
Err:645 http://192.168.1.1/ubuntuRepo bionic-updates/multiverse amd64 virtualbox-guest-additions-iso all 5.2.18-1~ubuntu18.04.1
  File has unexpected size (38955904 != 39016736). Mirror sync in progress? [IP: 192.168.1.1 80]
  Hashes of expected file:
   - SHA256:f7c5ab5ea5b1feadc2cf5d8527d7c14c8b34439d5345fd04822f12381681b2a6
   - SHA1:5e0d43ebddd08d6256ac809c746de9c483ea83f1 [weak]
   - MD5Sum:b2e992fd6462e216bc651ddb020216b8 [weak]
   - Filesize:39016736 [weak]
Get:646 http://192.168.1.1/ubuntuRepo bionic-updates/main amd64 xbrlapi amd64 5.5-4ubuntu2.0.1 [61.9 kB]
Fetched 763 MB in 1min 7s (11.4 MB/s)
E: Failed to fetch http://192.168.1.1/ubuntuRepo/pool/multiverse/v/virtualbox-guest-additions-iso/virtualbox-guest-additions-iso_5.2.18-1~ubuntu18.04.1_all.deb  File has unexpected size (38955904 != 39016736). Mirror sync in progress? [IP: 192.168.1.1 80]
   Hashes of expected file:
    - SHA256:f7c5ab5ea5b1feadc2cf5d8527d7c14c8b34439d5345fd04822f12381681b2a6
    - SHA1:5e0d43ebddd08d6256ac809c746de9c483ea83f1 [weak]
    - MD5Sum:b2e992fd6462e216bc651ddb020216b8 [weak]
    - Filesize:39016736 [weak]
E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?
</code>```

How to fix it?

The contents of my /etc/apt/sources.list is given below.

```<code>deb [arch=amd64] http://192.168.1.1/ubuntuRepo bionic main restricted universe multiverse
deb [arch=amd64] http://192.168.1.1/ubuntuRepo bionic-security main restricted universe multiverse
deb [arch=amd64] http://192.168.1.1/ubuntuRepo bionic-updates main restricted universe multiverse
deb [arch=amd64] http://192.168.1.1/ubuntuRepo bionic-proposed main restricted universe multiverse
deb [arch=amd64] http://192.168.1.1/ubuntuRepo bionic-backports main restricted universe multiverse
</code>```

答: The problem was solved by clearing the files in /var/lib/apt/ and running sudo apt-mirror in my machine which holds the local repository.</p>

Body:
I am maintaining a local repository for Ubuntu 18.04 LTS and recently updated the repository using apt-mirror. The I tried to upgrade the packages using the following commands

sudo apt-get clean
sudo apt-get update
sudo apt-get upgrade

The first two commands worked without any error. However, sudo apt-get upgrade resulted in the following error

Get:645 http://192.168.1.1/ubuntuRepo bionic-updates/multiverse amd64 virtualbox-guest-additions-iso all 5.2.18-1~ubuntu18.04.1 [39.0 MB]
Err:645 http://192.168.1.1/ubuntuRepo bionic-updates/multiverse amd64 virtualbox-guest-additions-iso all 5.2.18-1~ubuntu18.04.1
  File has unexpected size (38955904 != 39016736). Mirror sync in progress? [IP: 192.168.1.1 80]
  Hashes of expected file:
   - SHA256:f7c5ab5ea5b1feadc2cf5d8527d7c14c8b34439d5345fd04822f12381681b2a6
   - SHA1:5e0d43ebddd08d6256ac809c746de9c483ea83f1 [weak]
   - MD5Sum:b2e992fd6462e216bc651ddb020216b8 [weak]
   - Filesize:39016736 [weak]
Get:646 http://192.168.1.1/ubuntuRepo bionic-updates/main amd64 xbrlapi amd64 5.5-4ubuntu2.0.1 [61.9 kB]
Fetched 763 MB in 1min 7s (11.4 MB/s)
E: Failed to fetch http://192.168.1.1/ubuntuRepo/pool/multiverse/v/virtualbox-guest-additions-iso/virtualbox-guest-additions-iso_5.2.18-1~ubuntu18.04.1_all.deb  File has unexpected size (38955904 != 39016736). Mirror sync in progress? [IP: 192.168.1.1 80]
   Hashes of expected file:
    - SHA256:f7c5ab5ea5b1feadc2cf5d8527d7c14c8b34439d5345fd04822f12381681b2a6
    - SHA1:5e0d43ebddd08d6256ac809c746de9c483ea83f1 [weak]
    - MD5Sum:b2e992fd6462e216bc651ddb020216b8 [weak]
    - Filesize:39016736 [weak]
E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?

How to fix it?

The contents of my /etc/apt/sources.list is given below.

deb [arch=amd64] http://192.168.1.1/ubuntuRepo bionic main restricted universe multiverse
deb [arch=amd64] http://192.168.1.1/ubuntuRepo bionic-security main restricted universe multiverse
deb [arch=amd64] http://192.168.1.1/ubuntuRepo bionic-updates main restricted universe multiverse
deb [arch=amd64] http://192.168.1.1/ubuntuRepo bionic-proposed main restricted universe multiverse
deb [arch=amd64] http://192.168.1.1/ubuntuRepo bionic-backports main restricted universe multiverse


问:
Linq - how to convert this code to linq
My Linq-fu is not good enough to translate the following into hopefully one or two lines.</p>

```<code> var errors = new List<string>();
 foreach (var key in ModelState.Keys)
 {
   errors.Add(ModelState[key].Errors.FirstOrDefault().ErrorMessage);
 }

 return Json(new { success = false, errors = errors });
</code>```

答:
```<code>return new Json(new
   {
      success = false,
      errors = ModelState.Keys.Select(k => ModelState[key].Errors.First().ErrorMessage).ToList()
   });
</code>```

Title: Linq - how to convert this code to linq

Body:
My Linq-fu is not good enough to translate the following into hopefully one or two lines.

 var errors = new List<string>();
 foreach (var key in ModelState.Keys)
 {
   errors.Add(ModelState[key].Errors.FirstOrDefault().ErrorMessage);
 }

 return Json(new { success = false, errors = errors });