问:
JQuery dynamic height issue
1- I want the right sidebar to take the same video height

2- also when I change the video it doesn't take the same height, please click on chapter 2 to see the issue

its work only when I resize the page

I don't know why the sidebar didn't take the same video height can anyone help me, please?

https://codepen.io/kemozzz/full/gXEjjJ/

var vidHeight = $('.video-container').height();
$('.description').css('height', vidHeight + 'px');
$(window).resize(function() {
  var vidHeight = $('.video-container').height();
  $('.description').css('height', vidHeight + 'px');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Tools */

.no-padding {
  padding: 0!important;
}

.slow-effect {
  transition: all .2s ease-in-out;
  -webkit-transition: all .2s ease-in-out;
}

/* ======================================================================================= */

/* Layout ================================================================================ */

.space {
  height: 50px;
}

.container-fluid {
  padding: 0 4%;
}

/* Global Styles ========================================================================= */

/* Form Elements */

/*start places*/

body {
  height: 2000px;
}

.main-container {
  border: 2px solid #000;
  overflow: hidden;
}

.description {
  background-color: #898989;
  padding: 16px 30px;
  overflow: auto;
}

.description ul {
  margin: 0;
  padding: 0;
}

.description ul li a {
  background-color: #898989;
  color: #fff;
  padding-bottom: 18px;
  margin-bottom: 18px;
  position: relative;
  border: none;
}

.nav-tabs>li>a:hover {
  border: none;
  border-bottom: 2px solid #fff;
  background-color: #fff;
  color: #555555;
}

.description ul li a>h2 {
  font-weight: 700;
  font-size: 35px;
  margin: 0;
}

.description ul li a>p {
  font-size: 18px;
  line-height: 30px;
  margin-top: 5px;
  margin-bottom: 0;
}

.video-container {
  position: relative;
}

.video-container .tools {
  position: absolute;
  width: 100%;
  height: 40px;
  background-color: #a4a4a4;
  left: 0;
  bottom: 0;
  z-index: 999;
}

.video-container:hover .tools {
  visibility: hidden;
}

#style-1::-webkit-scrollbar {
  background-color: #898989;
}

#style-1::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
  background-color: #adadad
}

#style-1::-webkit-scrollbar {
  width: 20px;
}

@media(min-width: 992px) {
  .description {
    border-left: 2px solid #000;
  }
  .description ul li a {
    border-bottom: 2px solid #fff;
  }
}

@media(max-width: 991px) {
  .description {
    border-left: 2px solid #000;
    white-space: nowrap;
    padding: 0;
    height: auto!important;
  }
  .description ul li a {
    display: inline-block;
    width: 34%;
    padding: 14px;
    text-align: left;
    overflow: hidden;
    min-height: 252px;
    white-space: normal;
    vertical-align: text-top;
    margin-bottom: 0;
  }
  .description ul li:after {
    content: "";
    display: inline-block;
    width: 2px;
    height: 170px;
    position: absolute;
    right: 6px;
    top: 20px;
    background-color: #fff;
  }
  .description ul li:last-child:after {
    content: "";
    display: none;
  }
  .description ul li a>h2 {
    font-size: 22px;
  }
  .description ul li a>p {
    font-size: 14px;
    line-height: 23px;
  }
}

@media screen and (min-width: 220px) and (max-width: 550px) {
  .description ul li a {
    padding: 8px;
    min-height: 200px;
  }
  .description ul li a h2 {
    font-size: 14px;
  }
  .description ul li a p {
    font-size: 10px;
    line-height: 16px;
  }
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<video controls="" width="100%"><source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4"> <source src="test.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

<video controls="" width="100%"><source src="https://www.w3schools.com/html/movie.mp4" type="video/mp4"> <source src="mov_bbb.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

<video controls="" width="100%"><source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

<video controls="" width="100%"><source src="test.WEBM" type="video/mp4"> <source src="test.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

Chapter 1

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt doloremque incidunt.

Chapter 2

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt, rerum doloremque incidunt laudantium aliquid itaque cum error nobis.

Chapter 3

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit.

Chapter 4

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt, rerum doloremque incidunt laudantium aliquid itaque.

```

答:
Flexbox will solve this for you without any extra Javascript at all.

#exTab2 {
  display: flex;
}
.video-container {
  flex: 0 0 auto;
}
#style-1 {
  flex: 1 0 auto;
  position: relative;
}
@media(min-width: 992px) {
  .wrap {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
  }
  #exTab2 {
    flex-direction: row;
  }
}
@media(max-width: 991px) {
  #exTab2 {
    flex-direction: column;
  }
}
```

<p>(You'll need to wrap your <code>ul</code> in a <code>.wrap</code> <code>div</code> and move the <code>description</code> class to that <code>div</code> in order to keep the sidebar from stretching the container, as seen in this answer. This also breaks your control-hiding <code>div</code>, but that's not how you want to achieve that anyway.)</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-css lang-css prettyprint-override"><code>/* Tools */
.no-padding   { padding: 0!important; }
.slow-effect { transition: all .2s ease-in-out; -webkit-transition: all .2s ease-in-out; }

/* ======================================================================================= */
/* Layout ================================================================================ */
.container-fluid {
  margin-top: 50px;
  padding: 0 4%;
}

#exTab2 {
  display: flex;
}

.video-container {
  flex: 0 0 auto;
}

#style-1 {
  flex: 1 0 auto;
  position: relative;
}

/* Global Styles ========================================================================= */
/* Form Elements */
/*start places*/
body {
  height: 2000px;
}
.main-container {
  border: 2px solid #000;
  overflow: hidden;
}
.description {
  background-color: #898989;
  padding: 16px 30px;
  overflow: auto;
}
.description ul {
  margin: 0;
  padding: 0;
}
.description ul li a {
  background-color: #898989;
  color: #fff;
  padding-bottom: 18px;
  margin-bottom: 18px;
  position: relative;
  border:none;
}
.nav-tabs>li>a:hover {
  border:none;
  border-bottom: 2px solid #fff;
  background-color: #fff;
  color: #555555;
}

.description ul li a > h2 {
  font-weight: 700;
  font-size: 35px;
  margin: 0;
}
.description ul li a > p {
  font-size: 18px;
  line-height: 30px;
  margin-top: 5px;
  margin-bottom: 0;
}
.video-container {
  position: relative;
}

.video-container .tools {
  position: absolute;
  width: 100%;
  height: 40px;
  background-color: #a4a4a4;
  left: 0;
  bottom: 0;
  z-index: 999;
}

.video-container:hover .tools {
  visibility: hidden;
}

#style-1::-webkit-scrollbar {
  background-color: #898989;
}

#style-1::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
  background-color: #adadad
}
#style-1::-webkit-scrollbar {
  width: 20px;
}
@media(min-width: 992px) {
  .wrap {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
  }
  #exTab2 {
    flex-direction: row;
  }
  .description {
    border-left: 2px solid #000;
  }
  .description ul li a {
    border-bottom: 2px solid #fff;
  }
}

@media(max-width: 991px) {
  #exTab2 {
    flex-direction: column;
  }
  .description {
    border-left: 2px solid #000;
    white-space: nowrap;
    padding: 0;
    height: auto!important;
  }
  .description ul li a {
    display: inline-block;
    width: 34%;
    padding: 14px;
    text-align: left;
    overflow: hidden;
    min-height: 252px;
    white-space: normal;
    vertical-align: text-top;
    margin-bottom: 0;
  }
  .description ul li:after {
    content: "";
    display: inline-block;
    width: 2px;
    height: 170px;
    position: absolute;
    right: 6px;
    top: 20px;
    background-color: #fff;
  }
  .description ul li:last-child:after {
    content: "";
    display: none;
  }
  .description ul li a > h2 {
    font-size: 22px;
  }
  .description ul li a > p {
    font-size: 14px;
    line-height: 23px;
  }
}

@media screen and (min-width: 220px) and (max-width: 550px) {
  .description ul li a {
    padding: 8px;
    min-height: 200px;
  }
  .description ul li a h2 {
    font-size: 14px;
  }
  .description ul li a p {
    font-size: 10px;
    line-height: 16px;
  }
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

            <video controls="" width="100%">
              <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
              <source src="test.ogg" type="video/ogg">
              Your browser does not support HTML5 video.
            </video>

            <video controls="" width="100%">
              <source src="https://www.w3schools.com/html/movie.mp4" type="video/mp4">
              <source src="mov_bbb.ogg" type="video/ogg">
              Your browser does not support HTML5 video.
            </video>

            <video controls="" width="100%">
              <source src="movie.mp4" type="video/mp4">
              <source src="movie.ogg" type="video/ogg">
              Your browser does not support HTML5 video.
            </video>

            <video controls="" width="100%">
              <source src="test.WEBM" type="video/mp4">
              <source src="test.ogg" type="video/ogg">
              Your browser does not support HTML5 video.
            </video>

Chapter 1

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt doloremque incidunt.

Chapter 2

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt, rerum doloremque incidunt laudantium aliquid itaque cum error nobis.

Chapter 3

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit.

Chapter 4

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt, rerum doloremque incidunt laudantium aliquid itaque.

```

Title: JQuery dynamic height issue

Body:
1- I want the right sidebar to take the same video height

2- also when I change the video it doesn't take the same height, please click on chapter 2 to see the issue

its work only when I resize the page

I don't know why the sidebar didn't take the same video height can anyone help me, please?

https://codepen.io/kemozzz/full/gXEjjJ/

var vidHeight = $('.video-container').height();
$('.description').css('height', vidHeight + 'px');
$(window).resize(function() {
  var vidHeight = $('.video-container').height();
  $('.description').css('height', vidHeight + 'px');
});

/* Tools */

.no-padding {
  padding: 0!important;
}

.slow-effect {
  transition: all .2s ease-in-out;
  -webkit-transition: all .2s ease-in-out;
}

/* ======================================================================================= */

/* Layout ================================================================================ */

.space {
  height: 50px;
}

.container-fluid {
  padding: 0 4%;
}

/* Global Styles ========================================================================= */

/* Form Elements */

/*start places*/

body {
  height: 2000px;
}

.main-container {
  border: 2px solid #000;
  overflow: hidden;
}

.description {
  background-color: #898989;
  padding: 16px 30px;
  overflow: auto;
}

.description ul {
  margin: 0;
  padding: 0;
}

.description ul li a {
  background-color: #898989;
  color: #fff;
  padding-bottom: 18px;
  margin-bottom: 18px;
  position: relative;
  border: none;
}

.nav-tabs>li>a:hover {
  border: none;
  border-bottom: 2px solid #fff;
  background-color: #fff;
  color: #555555;
}

.description ul li a>h2 {
  font-weight: 700;
  font-size: 35px;
  margin: 0;
}

.description ul li a>p {
  font-size: 18px;
  line-height: 30px;
  margin-top: 5px;
  margin-bottom: 0;
}

.video-container {
  position: relative;
}

.video-container .tools {
  position: absolute;
  width: 100%;
  height: 40px;
  background-color: #a4a4a4;
  left: 0;
  bottom: 0;
  z-index: 999;
}

.video-container:hover .tools {
  visibility: hidden;
}

#style-1::-webkit-scrollbar {
  background-color: #898989;
}

#style-1::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
  background-color: #adadad
}

#style-1::-webkit-scrollbar {
  width: 20px;
}

@media(min-width: 992px) {
  .description {
    border-left: 2px solid #000;
  }
  .description ul li a {
    border-bottom: 2px solid #fff;
  }
}

@media(max-width: 991px) {
  .description {
    border-left: 2px solid #000;
    white-space: nowrap;
    padding: 0;
    height: auto!important;
  }
  .description ul li a {
    display: inline-block;
    width: 34%;
    padding: 14px;
    text-align: left;
    overflow: hidden;
    min-height: 252px;
    white-space: normal;
    vertical-align: text-top;
    margin-bottom: 0;
  }
  .description ul li:after {
    content: "";
    display: inline-block;
    width: 2px;
    height: 170px;
    position: absolute;
    right: 6px;
    top: 20px;
    background-color: #fff;
  }
  .description ul li:last-child:after {
    content: "";
    display: none;
  }
  .description ul li a>h2 {
    font-size: 22px;
  }
  .description ul li a>p {
    font-size: 14px;
    line-height: 23px;
  }
}

@media screen and (min-width: 220px) and (max-width: 550px) {
  .description ul li a {
    padding: 8px;
    min-height: 200px;
  }
  .description ul li a h2 {
    font-size: 14px;
  }
  .description ul li a p {
    font-size: 10px;
    line-height: 16px;
  }
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<video controls="" width="100%"><source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4"> <source src="test.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

<video controls="" width="100%"><source src="https://www.w3schools.com/html/movie.mp4" type="video/mp4"> <source src="mov_bbb.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

<video controls="" width="100%"><source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

<video controls="" width="100%"><source src="test.WEBM" type="video/mp4"> <source src="test.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

Chapter 1

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt doloremque incidunt.

Chapter 2

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt, rerum doloremque incidunt laudantium aliquid itaque cum error nobis.

Chapter 3

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit.

Chapter 4

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt, rerum doloremque incidunt laudantium aliquid itaque.

Body:
Flexbox will solve this for you without any extra Javascript at all.

#exTab2 {
  display: flex;
}
.video-container {
  flex: 0 0 auto;
}
#style-1 {
  flex: 1 0 auto;
  position: relative;
}
@media(min-width: 992px) {
  .wrap {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
  }
  #exTab2 {
    flex-direction: row;
  }
}
@media(max-width: 991px) {
  #exTab2 {
    flex-direction: column;
  }
}

(You'll need to wrap your ul in a .wrap div and move the description class to that div in order to keep the sidebar from stretching the container, as seen in this answer. This also breaks your control-hiding div, but that's not how you want to achieve that anyway.)

/* Tools */
.no-padding   { padding: 0!important; }
.slow-effect { transition: all .2s ease-in-out; -webkit-transition: all .2s ease-in-out; }

/* ======================================================================================= */
/* Layout ================================================================================ */
.container-fluid {
  margin-top: 50px;
  padding: 0 4%;
}

#exTab2 {
  display: flex;
}

.video-container {
  flex: 0 0 auto;
}

#style-1 {
  flex: 1 0 auto;
  position: relative;
}

/* Global Styles ========================================================================= */
/* Form Elements */
/*start places*/
body {
  height: 2000px;
}
.main-container {
  border: 2px solid #000;
  overflow: hidden;
}
.description {
  background-color: #898989;
  padding: 16px 30px;
  overflow: auto;
}
.description ul {
  margin: 0;
  padding: 0;
}
.description ul li a {
  background-color: #898989;
  color: #fff;
  padding-bottom: 18px;
  margin-bottom: 18px;
  position: relative;
  border:none;
}
.nav-tabs>li>a:hover {
  border:none;
  border-bottom: 2px solid #fff;
  background-color: #fff;
  color: #555555;
}

.description ul li a > h2 {
  font-weight: 700;
  font-size: 35px;
  margin: 0;
}
.description ul li a > p {
  font-size: 18px;
  line-height: 30px;
  margin-top: 5px;
  margin-bottom: 0;
}
.video-container {
  position: relative;
}

.video-container .tools {
  position: absolute;
  width: 100%;
  height: 40px;
  background-color: #a4a4a4;
  left: 0;
  bottom: 0;
  z-index: 999;
}

.video-container:hover .tools {
  visibility: hidden;
}

#style-1::-webkit-scrollbar {
  background-color: #898989;
}

#style-1::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
  background-color: #adadad
}
#style-1::-webkit-scrollbar {
  width: 20px;
}
@media(min-width: 992px) {
  .wrap {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
  }
  #exTab2 {
    flex-direction: row;
  }
  .description {
    border-left: 2px solid #000;
  }
  .description ul li a {
    border-bottom: 2px solid #fff;
  }
}

@media(max-width: 991px) {
  #exTab2 {
    flex-direction: column;
  }
  .description {
    border-left: 2px solid #000;
    white-space: nowrap;
    padding: 0;
    height: auto!important;
  }
  .description ul li a {
    display: inline-block;
    width: 34%;
    padding: 14px;
    text-align: left;
    overflow: hidden;
    min-height: 252px;
    white-space: normal;
    vertical-align: text-top;
    margin-bottom: 0;
  }
  .description ul li:after {
    content: "";
    display: inline-block;
    width: 2px;
    height: 170px;
    position: absolute;
    right: 6px;
    top: 20px;
    background-color: #fff;
  }
  .description ul li:last-child:after {
    content: "";
    display: none;
  }
  .description ul li a > h2 {
    font-size: 22px;
  }
  .description ul li a > p {
    font-size: 14px;
    line-height: 23px;
  }
}

@media screen and (min-width: 220px) and (max-width: 550px) {
  .description ul li a {
    padding: 8px;
    min-height: 200px;
  }
  .description ul li a h2 {
    font-size: 14px;
  }
  .description ul li a p {
    font-size: 10px;
    line-height: 16px;
  }
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <div class="row container-fluid">
      <div id="exTab2" class="col-xs-12 no-padding main-container">
        <div class="col-md-9 no-padding video-container tab-content">
          <div id="1" class="tabs-container tab-pane fade in active">
            <!-- Item-1 -->
            <div class="tools slow-effect"></div>
            <video controls="" width="100%">
              <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
              <source src="test.ogg" type="video/ogg">
              Your browser does not support HTML5 video.
            </video>
          </div>
          <div id="2" class="tabs-container tab-pane fade">
            <!-- Item-2 -->
            <div class="tools slow-effect"></div>
            <video controls="" width="100%">
              <source src="https://www.w3schools.com/html/movie.mp4" type="video/mp4">
              <source src="mov_bbb.ogg" type="video/ogg">
              Your browser does not support HTML5 video.
            </video>
          </div>
          <div id="3" class="tabs-container tab-pane fade">
            <!-- Item-3 -->
            <div class="tools slow-effect"></div>
            <video controls="" width="100%">
              <source src="movie.mp4" type="video/mp4">
              <source src="movie.ogg" type="video/ogg">
              Your browser does not support HTML5 video.
            </video>
          </div>
          <div id="4" class="tabs-container tab-pane fade">
            <!-- Item-4 -->
            <div class="tools slow-effect"></div>
            <video controls="" width="100%">
              <source src="test.WEBM" type="video/mp4">
              <source src="test.ogg" type="video/ogg">
              Your browser does not support HTML5 video.
            </video>
          </div>
        </div>
        <!-- Item-2 -->
        <div class="col-md-3" id="style-1">
          <div class="wrap description">
            <ul class="nav nav-tabs">
              <li class="active">
                <a data-toggle="tab" href="#1">
                  <h2>Chapter 1</h2>
                  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt doloremque incidunt.</p>
                </a>
              </li>
              <li>
                <a data-toggle="tab" href="#2">
                  <h2>Chapter 2</h2>
                  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt, rerum doloremque incidunt laudantium aliquid itaque cum error nobis.</p>
                </a>
              </li>
              <li>
                <a data-toggle="tab" href="#3">
                  <h2>Chapter 3</h2>
                  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit.</p>
                </a>
              </li>
              <li>
                <a data-toggle="tab" href="#4">
                  <h2>Chapter 4</h2>
                  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt, rerum doloremque incidunt laudantium aliquid itaque.</p>
                </a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>


来源: stackexchange

问:
select option not working with ng-model in angular 4
I have a select box where I show elements from a list
Code Snippet:

```<code>export class CreateauctionComponent implements OnInit{

    createAuctionForm: FormGroup;
    test:any = ["cat","dog"];

    constructor(private _formBuilder: FormBuilder,private _categories: UserCategoriesForAuctionService){
        //
    }
}
</code>```

In HTML rendered as:

```<code><div class="form-col">
    <h5><span style="color:red;">*</span>{{'createAuction.category' | translate}}:</h5>
    <select class="form_cbx long-select" name="" ng-model="test">
        <option  ng-options="t in test">{{t}}</option>
    </select>
</div>
</code>```

I am not able to see any values. Only one blank field in the list. Can anyone direct what is the issue here?

答:
You need to use compareWith property on select tag, but If you are using angular 4, your html still looks like using angularJs.

HTML File :

```<code><select [compareWith]="byAnimal" [(ngModel)]="selectedAnimal">
  <option *ngFor="let animal of animals" [ngValue]="animal">
    {{animal.type}}
  </option>
</select>
</code>```

TS File

```<code>byAnimal(item1,item2){
  return item1.type == item2.type;
}
</code>```

One of the best soltion from this link

ContentLicense: CC BY-SA 3.0

Body:
I have a select box where I show elements from a list
Code Snippet:

export class CreateauctionComponent implements OnInit{

    createAuctionForm: FormGroup;
    test:any = ["cat","dog"];

    constructor(private _formBuilder: FormBuilder,private _categories: UserCategoriesForAuctionService){
        //
    }
}

In HTML rendered as:

*{{'createAuction.category' | translate}}:

    <select class="form_cbx long-select" name="" ng-model="test">
        <option  ng-options="t in test">{{t}}</option>
    </select>

I am not able to see any values. Only one blank field in the list. Can anyone direct what is the issue here?

Body:
You need to use compareWith property on select tag, but If you are using angular 4, your html still looks like using angularJs.

HTML File :

<select [compareWith]="byAnimal" [(ngModel)]="selectedAnimal">
  <option *ngFor="let animal of animals" [ngValue]="animal">
    {{animal.type}}
  </option>
</select>

TS File

byAnimal(item1,item2){
  return item1.type == item2.type;
}

One of the best soltion from this link


问:
nodejs azure application throwing errors about javascript syntax that do not occur in localhost environment
I have a simple one-page screenshot app  using puppeteer/headless chrome that works fine in localhost.

When I run it in azure, page fails to load due to server error.

When I check the logs, I get 'unexpected token' errors on what looks like valid javascript and must be valid since it runs fine local.

Using the line numbers in error logs as a guide,
I re-wrote the code in different formats, trying to work-around the issue.
Conde runs fine local every time, but in azure, the exception just moves to a different line.

Has anyone else encountered this issue?

code of file that is throwing errors:

```<code>'use strict';
var express = require('express');
var AWS = require('aws-sdk');
var awsConfig = require('aws-config');
var http = require("http");
var fs = require('fs')
var request = require("request");
var router = express.Router();
var puppeteer = require('puppeteer');

var screenshot = async function (req) {

    var appUrl = "x";

    if (req.query.localHost) {
        appUrl = "x";
    }

    var url = appUrl + "x";

    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    await page.setViewport({ width: 1600, height: 900 });

    var path = "x";

    try {

        await page.goto(url, { waitUntil: 'load' });

        page.on('console', function (msg) {
            if (msg.text === "all are done") {
                (async () => {

                    //  console.log(msg.text);

                    await page.screenshot({ path: path, type: "jpeg", quality: 90 });

                    var fileName = "x";

                    saveAutoGenThumbnail(fileName, fs.createReadStream(path), function (err, data) {
                        if (err) {

                        } else {
                            //fs.unlink(path);
                            fs.unlinkSync(path);
                        }
                    });

                    await browser.close();

                })();
            }

        });

    } catch (e) {
        console.error(e);
    }

}

function saveAutoGenThumbnail(imageName, imageFile, callBack) {

    AWS.config.accessKeyId = "x";
    AWS.config.secretAccessKey = "x";
    AWS.config.region = "x";

    var s3 = new AWS.S3();

    var s3Bucket = new AWS.S3({ params: { Bucket: 'x' } })

    var data = {
        Key: imageName, Body: imageFile, ACL: 'public-read', ContentType: "image/jpeg"
    };

    s3Bucket.putObject(data, callBack);

}

/* GET home page. */
router.get('/', function (req, res) {

   // screenshot(req);

    res.render('screenshot', { title: 'screenshot' });
});

module.exports = router;
</code>```

web config:

```<code><?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your Node.js application, please visit
  http://go.microsoft.com/fwlink/?LinkId=290972
  -->
<configuration>
  <appSettings>

  </appSettings>
  <system.webServer>
    <!-- mimeMap enables IIS to serve particular file types as specified by fileExtension. -->
    <staticContent>
      <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
    </staticContent>

    <modules runAllManagedModulesForAllRequests="false" />

    <!-- Web.Debug.config adds attributes to this to enable remote debugging when publishing in Debug configuration. -->
    <iisnode watchedFiles="web.config;*.js;routes\*.js;views\*.pug"/>

    <handlers>
      <add name="iisnode" path="app.js" verb="*" modules="iisnode" />

    </handlers>

    <security>
      <requestFiltering>
        <hiddenSegments>
          <remove segment="bin" />
        </hiddenSegments>
      </requestFiltering>
    </security>

    <rewrite>
      <rules>
        <clear />

        <!-- Don't interfere with requests for node-inspector debugging -->
        <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
          <match url="^server.js\/debug[\/]?" />
        </rule>

        <rule name="app" enabled="true" patternSyntax="ECMAScript" stopProcessing="true">
          <match url="iisnode.+" negate="true" />
          <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
          <action type="Rewrite" url="app.js" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>

</configuration>
</code>```

答:
Two things:

Async functions are not supported by Node.js versions older than version 7.6.

Azure Web Apps currently doesn't support Node.js 8.9.1. You can check all available versions in Azure via https://<yourappname>.scm.azurewebsites.net/api/diagnostics/runtime.

So, to avoid this error, you'll need to set the Node.js version to 8.9.0 instead:

Body:
I have a simple one-page screenshot app  using puppeteer/headless chrome that works fine in localhost.

When I run it in azure, page fails to load due to server error.

When I check the logs, I get 'unexpected token' errors on what looks like valid javascript and must be valid since it runs fine local.

Using the line numbers in error logs as a guide,
I re-wrote the code in different formats, trying to work-around the issue.
Conde runs fine local every time, but in azure, the exception just moves to a different line.

Has anyone else encountered this issue?

code of file that is throwing errors:

'use strict';
var express = require('express');
var AWS = require('aws-sdk');
var awsConfig = require('aws-config');
var http = require("http");
var fs = require('fs')
var request = require("request");
var router = express.Router();
var puppeteer = require('puppeteer');

var screenshot = async function (req) {

    var appUrl = "x";

    if (req.query.localHost) {
        appUrl = "x";
    }

    var url = appUrl + "x";

    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    await page.setViewport({ width: 1600, height: 900 });

    var path = "x";

    try {

        await page.goto(url, { waitUntil: 'load' });

        page.on('console', function (msg) {
            if (msg.text === "all are done") {
                (async () => {

                    //  console.log(msg.text);

                    await page.screenshot({ path: path, type: "jpeg", quality: 90 });

                    var fileName = "x";

                    saveAutoGenThumbnail(fileName, fs.createReadStream(path), function (err, data) {
                        if (err) {

                        } else {
                            //fs.unlink(path);
                            fs.unlinkSync(path);
                        }
                    });

                    await browser.close();

                })();
            }

        });

    } catch (e) {
        console.error(e);
    }

}

function saveAutoGenThumbnail(imageName, imageFile, callBack) {

    AWS.config.accessKeyId = "x";
    AWS.config.secretAccessKey = "x";
    AWS.config.region = "x";

    var s3 = new AWS.S3();

    var s3Bucket = new AWS.S3({ params: { Bucket: 'x' } })

    var data = {
        Key: imageName, Body: imageFile, ACL: 'public-read', ContentType: "image/jpeg"
    };

    s3Bucket.putObject(data, callBack);

}

/* GET home page. */
router.get('/', function (req, res) {

   // screenshot(req);

    res.render('screenshot', { title: 'screenshot' });
});

module.exports = router;

web config:

<?xml version="1.0" encoding="utf-8"?>

<configuration>
  <appSettings>

  </appSettings>
  <system.webServer>

    <staticContent>
      <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
    </staticContent>

    <modules runAllManagedModulesForAllRequests="false" />

    <iisnode watchedFiles="web.config;*.js;routes\*.js;views\*.pug"/>

    <handlers>
      <add name="iisnode" path="app.js" verb="*" modules="iisnode" />

    </handlers>

    <security>
      <requestFiltering>
        <hiddenSegments>
          <remove segment="bin" />
        </hiddenSegments>
      </requestFiltering>
    </security>

    <rewrite>
      <rules>
        <clear />

        <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
          <match url="^server.js\/debug[\/]?" />
        </rule>

        <rule name="app" enabled="true" patternSyntax="ECMAScript" stopProcessing="true">
          <match url="iisnode.+" negate="true" />
          <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
          <action type="Rewrite" url="app.js" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>

</configuration>


问:
how to call a custom PDF plug-in in dita-ot -3.0
I am a non-programmer TW, thank you first for your help, if any.(*￣︶￣)

I custom a PDF plugin by using http://dita-generator.elovirta.com/.
and use dita --install command to install the plugin .zip file. I check the plugins file in default dita-ot-3.0 directory, the plugin has been successfully installed.
Here is the question: how can i call the custom PDF plugin when outputting PDF from a ditamap file.

Thanks.

答:
You have defined a name for the transformation in the last step. Open the plugin.xml and look up the transtype name from the extension point dita.transtype.print.

```<code><feature extension="dita.transtype.print" value="NAME_OF_YOUR_TRANSTYPE"/>
</code>```

Then call dita --input your.fitamap --format NAME_OF_YOUR_TRANSTYPE.

Body:
You have defined a name for the transformation in the last step. Open the plugin.xml and look up the transtype name from the extension point dita.transtype.print.

<feature extension="dita.transtype.print" value="NAME_OF_YOUR_TRANSTYPE"/>

Then call dita --input your.fitamap --format NAME_OF_YOUR_TRANSTYPE.


问:
How can I send the POST request to the other server binding file into formdata
I have a pdf file which is generated into my local server with my server side code. I want to send a request to the another server requesting POST. The post method take parameter as FormData where formdata types

one is string and another is file type.

```<code>content-type
form-data
Body
 　PDF file (file type)
   string value

</code>```

Is it possible to make the POST request without browsing the file location?

答:
Doing some R&D I have overcome this problem with following some steps, as there is no way to get the file object from the physical location automatically in client side (basically in js) except browsing for security reason.

In my local server I have created a REST service. which response base64 string of the desired file.

Than I call the REST api from my javaScript and as a response I receive the base64 string. And than I convert it into bytes array and than Blob object and than File object.

base64 string==>bytes array==>Blob object==>File object

```<code>var base64 = this.getpdfFromLocal() //get the base64 string
var byteArray= this.base64ToByte(base64 );
var file = this.getFileFromByteArray(byteArray);

//return the byte array form the base64 string
MyApi.prototype.base64ToByte= function(base64) {
    var binaryString = window.atob(base64);
    var binaryLen = binaryString.length;
    var bytes = new Uint8Array(binaryLen);
    for (var i = 0; i < binaryLen; i++) {
        var ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
    }
    return bytes;
};
MyApi.prototype.getFileFromByteArray=function(byteArray) {
    var blob = new Blob([byteArray]);
    var file = new File([blob], "resource.pdf");
    return file;
 };
</code>```

Lastly I make from data using file object and send request the another server REST web services.

```<code>var formdata = new FormData();
formdata.append("some_value", "Some String");
formdata.append("file", file);
var url = "http://yoururl.com";
var result =$.ajax({
    url             : url ,
    type            : 'POST',
    data            : formdata,
    contentType     : false,
    cache           : false,
    processData     : false,
    scriptCharset   : 'utf-8',
    async           : false
}).responseText;
</code>```

Body:
I have a pdf file which is generated into my local server with my server side code. I want to send a request to the another server requesting POST. The post method take parameter as FormData where formdata types

one is string and another is file type.

content-type
form-data
Body
 　PDF file (file type)
   string value

Is it possible to make the POST request without browsing the file location?

Body:
Doing some R&D I have overcome this problem with following some steps, as there is no way to get the file object from the physical location automatically in client side (basically in js) except browsing for security reason.

In my local server I have created a REST service. which response base64 string of the desired file.

Than I call the REST api from my javaScript and as a response I receive the base64 string. And than I convert it into bytes array and than Blob object and than File object.

base64 string==>bytes array==>Blob object==>File object

var base64 = this.getpdfFromLocal() //get the base64 string
var byteArray= this.base64ToByte(base64 );
var file = this.getFileFromByteArray(byteArray);

//return the byte array form the base64 string
MyApi.prototype.base64ToByte= function(base64) {
    var binaryString = window.atob(base64);
    var binaryLen = binaryString.length;
    var bytes = new Uint8Array(binaryLen);
    for (var i = 0; i < binaryLen; i++) {
        var ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
    }
    return bytes;
};
MyApi.prototype.getFileFromByteArray=function(byteArray) {
    var blob = new Blob([byteArray]);
    var file = new File([blob], "resource.pdf");
    return file;
 };

Lastly I make from data using file object and send request the another server REST web services.

var formdata = new FormData();
formdata.append("some_value", "Some String");
formdata.append("file", file);
var url = "http://yoururl.com";
var result =$.ajax({
    url             : url ,
    type            : 'POST',
    data            : formdata,
    contentType     : false,
    cache           : false,
    processData     : false,
    scriptCharset   : 'utf-8',
    async           : false
}).responseText;


问:
How can HTML <select/> prevent click through parent's div
I'm creating shopping cart page that there's a div have a click listener for redirecting to the product page, but you also can select qty on the div. How can I prevent the redirection when selecting from <select/>

I've tried event.stopPropagation() / e.preventDefault() on select but not working

Here's the sample code.

https://jsfiddle.net/hk7861es/2/

答:
You can test whether the target is the parent div by event.target == this

Example:

```<code>$('#box').click(function(event) {
    if ( event.target == this ){
          $('#text').append('You clicked');
    }
})
</code>```

Fiddle: https://jsfiddle.net/hk7861es/3/

Body:
You can test whether the target is the parent div by event.target == this

Example:

$('#box').click(function(event) {
    if ( event.target == this ){
          $('#text').append('You clicked');
    }
})

Fiddle: https://jsfiddle.net/hk7861es/3/


问:
SQL query where ALL records in a join match a condition?
I have what seems to be a simple problem, but can not figure out the proper solution via SQL. I'm using postgresql specifically.

Take the following:

```<code>SELECT *
FROM users INNER JOIN tags
  ON (tags.user_id = users.id)
WHERE tags.name IN ('word1', 'word2')
</code>```

This does not do what I need. I want to find users whose tags are ONLY included in the list. If the user has a tag that is not in the list, the user should not be included.

'user1' tags: word1, word2, word3

'user2' tags: word1

'user3' tags: word1, word2

Given: word1 and word2. I want to prepare a query that returns 'user2' and 'user3'. 'user1' is excluded because it has a tag that is not in the list.

Hopefully I made this clear. Thanks for your help!

答:
To get all users that don't have a tag that is not in the list, use the query below. Could be that users are returned that have no tag or only one tag matching the words, but I understand that is the desired functionality.</p>

```<code>SELECT
  u.*
FROM
  users u
  LEFT JOIN tags t
    ON t.user_id = u.userid AND
       t.name NOT IN ('word1', 'word2')
WHERE
  t.user_id IS NULL
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have what seems to be a simple problem, but can not figure out the proper solution via SQL. I'm using postgresql specifically.

Take the following:

SELECT *
FROM users INNER JOIN tags
  ON (tags.user_id = users.id)
WHERE tags.name IN ('word1', 'word2')

This does not do what I need. I want to find users whose tags are ONLY included in the list. If the user has a tag that is not in the list, the user should not be included.

'user1' tags: word1, word2, word3

'user2' tags: word1

'user3' tags: word1, word2

Given: word1 and word2. I want to prepare a query that returns 'user2' and 'user3'. 'user1' is excluded because it has a tag that is not in the list.

Hopefully I made this clear. Thanks for your help!

Body:
To get all users that don't have a tag that is not in the list, use the query below. Could be that users are returned that have no tag or only one tag matching the words, but I understand that is the desired functionality.

SELECT
  u.*
FROM
  users u
  LEFT JOIN tags t
    ON t.user_id = u.userid AND
       t.name NOT IN ('word1', 'word2')
WHERE
  t.user_id IS NULL

ContentLicense: CC BY-SA 2.5


问:
Getting Null Pointer Exception While reading value from Config Properties File in Selenium
```<code>package com.HybridFramework.testbase;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class TestBase {

public WebDriver driver;

 public Properties a1;
 public File f1;
 public FileInputStream file;
public void loadPropertiesFile() throws IOException{
        Properties a1 = new Properties();
        System.out.println(System.getProperty("user.dir"));
        //f1= new File("E:\\Selenium-2017\\HybridFramework\\src\\main\\java\\com\\HybridFramework\\config\\config.properties");
    f1 = new File(System.getProperty("user.dir")+"/src/main/java/com/HybridFramework/config/config.properties");
    System.out.println("lola");
    file= new FileInputStream(f1);
    a1.load(file);

    f1 = new File(System.getProperty("user.dir")+"/src/main/java/com/HybridFramework/config/or.properties");
    file= new FileInputStream(f1);
    a1.load(file);

    }
    public void getPropertiesData(){

    }
public static void main(String[] args) throws IOException   {
    TestBase test = new  TestBase();
    //test.getBrowser("firefox");
    System.out.println("Start");
    test.loadPropertiesFile();
System.out.println(test.a1.getProperty("Username"));
    test.a1.getProperty("testname");
}

 }
</code>```

Below is my properties file which I am referencing to.

config.properties file

```<code>Username=Bhanu
Password=password
url=https://www.google.com
</code>```

or.properties file

```<code>test=test1
testname=login
</code>```

Error is Below

Exception in thread "main" java.lang.NullPointerException
    at com.HybridFramework.testbase.TestBase.main(TestBase.java:61)

答:
You've declared an instance property of type Properties but never initialized.
Use a1 = new Properties(); instead of Porperties a1 = new Properties(); in your loadPropertiesFile() method.

Body:
package com.HybridFramework.testbase;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class TestBase {

public WebDriver driver;

 public Properties a1;
 public File f1;
 public FileInputStream file;
public void loadPropertiesFile() throws IOException{
        Properties a1 = new Properties();
        System.out.println(System.getProperty("user.dir"));
        //f1= new File("E:\\Selenium-2017\\HybridFramework\\src\\main\\java\\com\\HybridFramework\\config\\config.properties");
    f1 = new File(System.getProperty("user.dir")+"/src/main/java/com/HybridFramework/config/config.properties");
    System.out.println("lola");
    file= new FileInputStream(f1);
    a1.load(file);

    f1 = new File(System.getProperty("user.dir")+"/src/main/java/com/HybridFramework/config/or.properties");
    file= new FileInputStream(f1);
    a1.load(file);

    }
    public void getPropertiesData(){

    }
public static void main(String[] args) throws IOException   {
    TestBase test = new  TestBase();
    //test.getBrowser("firefox");
    System.out.println("Start");
    test.loadPropertiesFile();
System.out.println(test.a1.getProperty("Username"));
    test.a1.getProperty("testname");
}

 }

Below is my properties file which I am referencing to.

config.properties file

Username=Bhanu
Password=password
url=https://www.google.com

or.properties file

test=test1
testname=login

Error is Below

Exception in thread "main" java.lang.NullPointerException
    at com.HybridFramework.testbase.TestBase.main(TestBase.java:61)


问:
mule: how to add value to payload array list
I have a payload as list of maps and another flow variable as map.
I wanted to add flow variable to payload list. I tried using this expression #[payload.addAll(flowVars['entitlement'])]in expression component. But it sets the payload to boolean value true.

答:
Try using Set Payload transformer.
and add

[payload.addAll(flowVars['entitlement']) as value.


问:
Swing components are too small
So I have this code in my contructor, my class extends JFrame:

```<code>    super("myBucketList");

    i = new Item();

    //controls panel
    controls = new JPanel();

    itemField = new JTextField();
    itemField.addActionListener(new ListenAction());

    delField = new JTextField();
    delField.addActionListener(new ListenAction());

    listArea = new JTextArea();
    listArea.setEditable(false);

    controls.add(delField);
    controls.add(itemField);

    //txtareaPanel
    textareaPanel = new JPanel();

    listScroll = new JScrollPane();
    listScroll.setViewportView(listArea);

    textareaPanel.add(listScroll);

    //tab1 panel
    tab1 = new JPanel();
    tab1.setLayout(new BorderLayout());

    tab1.add(controls, BorderLayout.NORTH);
    tab1.add(textareaPanel, BorderLayout.CENTER);

    add(tab1);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(500,200);
    setVisible(true);
</code>```

Now if I run my application the components are really small, how to fix it?

Here is a screenshot of the situation/problem: http://snag.gy/yjbUl.jpg

Thanks

答:
If you are using jdk 8 then keep it but
download the jre 9 and your widgets
etc will be of normal size. This solves the
problem!</p>

Title: Swing components are too small

Body:
So I have this code in my contructor, my class extends JFrame:

    super("myBucketList");

    i = new Item();

    //controls panel
    controls = new JPanel();

    itemField = new JTextField();
    itemField.addActionListener(new ListenAction());

    delField = new JTextField();
    delField.addActionListener(new ListenAction());

    listArea = new JTextArea();
    listArea.setEditable(false);

    controls.add(delField);
    controls.add(itemField);

    //txtareaPanel
    textareaPanel = new JPanel();

    listScroll = new JScrollPane();
    listScroll.setViewportView(listArea);

    textareaPanel.add(listScroll);

    //tab1 panel
    tab1 = new JPanel();
    tab1.setLayout(new BorderLayout());

    tab1.add(controls, BorderLayout.NORTH);
    tab1.add(textareaPanel, BorderLayout.CENTER);

    add(tab1);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(500,200);
    setVisible(true);

Now if I run my application the components are really small, how to fix it?

Here is a screenshot of the situation/problem: http://snag.gy/yjbUl.jpg

Thanks


问:
How to get a distinct sub document list by excluding one named field?
I'm looking for a pre 3.4 solution (i.e. no replaceRoot and project by exclusion option) for how to get a distinct list of sub document values, by excluding one named field.

I have something like:-

```<code>{
"field1":"sadasdasdasdas",
"field2":"whatever bla dasdasda",
"source_display_tags" : {
        "name" : "Hot Toast Cafe",
        "updateId" : NumberLong(12345),
        "address" : "2 Burnt Street",
        "postal_code" : "HT1 8RT",
        "town" : "Breadville"
    }
}
</code>```

And I wish to get a distinct list of source_display_tags by excluding the updateId field, i.e.

```<code>{
    "source_display_tags" : {
        "name" : "Hot Toast Cafe",
        "address" : "2 Burnt Street",
        "postal_code" : "HT1 8RT",
        "town" : "Breadville"}
},
{
    "source_display_tags" : {
        "name" : "Banana Grove Restaurant",
         etc...
</code>```

in some way which does not involve naming any of the other fields. i.e. I don't want to do this:-

```<code>db.getCollection('updates').aggregate([
{$unwind:"$source_display_tags"},
{"$project": {_id:0, name: "$source_display_tags.name", address: "$source_display_tags.address", town: "$source_display_tags.town", postal_code: "$source_display_tags.postal_code"}},
{ $group: { _id: { name: "$name", address: "$address", town: "$town", postal_code:"$postal_code"}}}
])
</code>```

Is there any way to produce this output by only naming the "updateId" field?

答:
Add another $project to your existing query and that will do the magic for us, In the $project pipeline have a tag named source_display_tags and pass the content of _id (from the previous pipeline result) to this tag and suppress the _id,

here is the query

```<code>db.getCollection('updates').aggregate([
     {$unwind:"$source_display_tags"},
     {"$project": { _id:0,
               name: "$source_display_tags.name",
               address: "$source_display_tags.address",
               town: "$source_display_tags.town",
               postal_code: "$source_display_tags.postal_code"
     }},
     { "$group": {
                _id: {
                        name: "$name",
                        address: "$address",
                        town: "$town",
                        postal_code:"$postal_code"
                }}
      },
      {"$project":{source_display_tags: "$_id", "_id":0}}
])
</code>```

If there is no need of grouping we can simply use the below find query

```<code>db.so.find( {},
            {
             "source_display_tags.name":1,
              "source_display_tags.address":1,
              "source_display.tags.postal_code":1,
              "source_display_tags.town":1,
              _id:0
            }
);
</code>```

Body:
I'm looking for a pre 3.4 solution (i.e. no replaceRoot and project by exclusion option) for how to get a distinct list of sub document values, by excluding one named field.

I have something like:-

{
"field1":"sadasdasdasdas",
"field2":"whatever bla dasdasda",
"source_display_tags" : {
        "name" : "Hot Toast Cafe",
        "updateId" : NumberLong(12345),
        "address" : "2 Burnt Street",
        "postal_code" : "HT1 8RT",
        "town" : "Breadville"
    }
}

And I wish to get a distinct list of source_display_tags by excluding the updateId field, i.e.

{
    "source_display_tags" : {
        "name" : "Hot Toast Cafe",
        "address" : "2 Burnt Street",
        "postal_code" : "HT1 8RT",
        "town" : "Breadville"}
},
{
    "source_display_tags" : {
        "name" : "Banana Grove Restaurant",
         etc...

in some way which does not involve naming any of the other fields. i.e. I don't want to do this:-

db.getCollection('updates').aggregate([
{$unwind:"$source_display_tags"},
{"$project": {_id:0, name: "$source_display_tags.name", address: "$source_display_tags.address", town: "$source_display_tags.town", postal_code: "$source_display_tags.postal_code"}},
{ $group: { _id: { name: "$name", address: "$address", town: "$town", postal_code:"$postal_code"}}}
])

Is there any way to produce this output by only naming the "updateId" field?

Body:
Add another $project to your existing query and that will do the magic for us, In the $project pipeline have a tag named source_display_tags and pass the content of _id (from the previous pipeline result) to this tag and suppress the _id,

here is the query

db.getCollection('updates').aggregate([
     {$unwind:"$source_display_tags"},
     {"$project": { _id:0,
               name: "$source_display_tags.name",
               address: "$source_display_tags.address",
               town: "$source_display_tags.town",
               postal_code: "$source_display_tags.postal_code"
     }},
     { "$group": {
                _id: {
                        name: "$name",
                        address: "$address",
                        town: "$town",
                        postal_code:"$postal_code"
                }}
      },
      {"$project":{source_display_tags: "$_id", "_id":0}}
])

If there is no need of grouping we can simply use the below find query

db.so.find( {},
            {
             "source_display_tags.name":1,
              "source_display_tags.address":1,
              "source_display.tags.postal_code":1,
              "source_display_tags.town":1,
              _id:0
            }
);


问:
Datagridview checkboxcolumn validation
In a DatagridView I have databound checkboxcolumns. But if I check or uncheck multiple checkboxes, not all changes are saved. (It doesn't trigger the property Set method on all, maybe on every 2nd). However if I after each checkbox-click, click on another cell (column) before the next checkbox, then all actions will trigger the Set methods.  So it seems the cell validation does not work on a per-cell basis, but on a per column basis (For the checkboxcolumn).  So how do you solve this?

答:
Found the answer: DataGridView with CheckBox cell problem

But probably easier alternative is to put in the save button method:

```<code>DataGridView.EndEdit();
</code>```

Title: Datagridview checkboxcolumn validation

Body:
Found the answer: DataGridView with CheckBox cell problem

But probably easier alternative is to put in the save button method:

DataGridView.EndEdit();


问:
EmptyError: no elements in sequence
I'm upgrading my Angular2 app from 2.0.0 to 2.3.0, and I'm running into the following error.  Any ideas as to why?  I saw this other post (Angular 2.0.1 Router EmptyError: no elements in sequence), but after trying this, the issue still remains.  What causes this error?

```<code>Error: Uncaught (in promise): EmptyError: no elements in sequence
Error: no elements in sequence
    at EmptyError.ZoneAwareError (zone.js:672)
    at new EmptyError (EmptyError.ts:13)
    at FirstSubscriber._complete (first.ts:161)
    at FirstSubscriber.Subscriber.complete (Subscriber.ts:122)
    at Subject._subscribe (Subject.ts:109)
    at Subject.Observable.subscribe (Observable.ts:98)
    at Observable._subscribe (Observable.ts:158)
    at Observable.subscribe (Observable.ts:98)
    at Observable._subscribe (Observable.ts:158)
    at FirstOperator.call (first.ts:82)
    at Observable.subscribe (Observable.ts:96)
    at Object.subscribeToResult (subscribeToResult.ts:32)
    at MergeAllSubscriber._next (mergeAll.ts:82)
    at MergeAllSubscriber.Subscriber.next (Subscriber.ts:95)
    at MapSubscriber._next (map.ts:80)
    at resolvePromise (zone.js:475) [angular]
    at resolvePromise (zone.js:460) [angular]
    at /libs/zone.js/dist/zone.js:509:17 [angular]
    at Object.onInvokeTask (core.umd.min.js:32) [angular]
    at ZoneDelegate.invokeTask (zone.js:261) [angular]
    at Zone.runTask (zone.js:151) [<root> => angular]
    at drainMicroTaskQueue (zone.js:405) [<root>]
    at ZoneTask.invoke (zone.js:336) [<root>]ErrorHandler.handleError @ core.umd.min.js:31next @ core.umd.min.js:32generatorOrNext.object.schedulerFn @ core.umd.min.js:32SafeSubscriber.__tryOrUnsub @ Subscriber.ts:238SafeSubscriber.next @ Subscriber.ts:190Subscriber._next @ Subscriber.ts:135Subscriber.next @ Subscriber.ts:95Subject.next @ Subject.ts:61EventEmitter.emit @ core.umd.min.js:32NgZone.triggerError @ core.umd.min.js:32onHandleError @ core.umd.min.js:32ZoneDelegate.handleError @ zone.js:233Zone.runGuarded @ zone.js:129_loop_1 @ zone.js:416drainMicroTaskQueue @ zone.js:425ZoneTask.invoke @ zone.js:336
</code>```

I've also noticed that a NavigationError object is thrown when I try to change to a route that uses Guards.  But only the error above is what is shown in the console.

NavigationError {id: 2, url: "/home", error: EmptyError}

I'm kind of at a loss and would appreciate any help.

答:
Add this property to your route.

```<code>pathMatch: 'full
</code>```

for eg.

```<code>{ pathMatch: 'full', path: "", component: HomeComponent }
</code>```

It worked for me.

Title: EmptyError: no elements in sequence

Body:
I'm upgrading my Angular2 app from 2.0.0 to 2.3.0, and I'm running into the following error.  Any ideas as to why?  I saw this other post (Angular 2.0.1 Router EmptyError: no elements in sequence), but after trying this, the issue still remains.  What causes this error?

Error: Uncaught (in promise): EmptyError: no elements in sequence
Error: no elements in sequence
    at EmptyError.ZoneAwareError (zone.js:672)
    at new EmptyError (EmptyError.ts:13)
    at FirstSubscriber._complete (first.ts:161)
    at FirstSubscriber.Subscriber.complete (Subscriber.ts:122)
    at Subject._subscribe (Subject.ts:109)
    at Subject.Observable.subscribe (Observable.ts:98)
    at Observable._subscribe (Observable.ts:158)
    at Observable.subscribe (Observable.ts:98)
    at Observable._subscribe (Observable.ts:158)
    at FirstOperator.call (first.ts:82)
    at Observable.subscribe (Observable.ts:96)
    at Object.subscribeToResult (subscribeToResult.ts:32)
    at MergeAllSubscriber._next (mergeAll.ts:82)
    at MergeAllSubscriber.Subscriber.next (Subscriber.ts:95)
    at MapSubscriber._next (map.ts:80)
    at resolvePromise (zone.js:475) [angular]
    at resolvePromise (zone.js:460) [angular]
    at /libs/zone.js/dist/zone.js:509:17 [angular]
    at Object.onInvokeTask (core.umd.min.js:32) [angular]
    at ZoneDelegate.invokeTask (zone.js:261) [angular]
    at Zone.runTask (zone.js:151) [<root> => angular]
    at drainMicroTaskQueue (zone.js:405) [<root>]
    at ZoneTask.invoke (zone.js:336) [<root>]ErrorHandler.handleError @ core.umd.min.js:31next @ core.umd.min.js:32generatorOrNext.object.schedulerFn @ core.umd.min.js:32SafeSubscriber.__tryOrUnsub @ Subscriber.ts:238SafeSubscriber.next @ Subscriber.ts:190Subscriber._next @ Subscriber.ts:135Subscriber.next @ Subscriber.ts:95Subject.next @ Subject.ts:61EventEmitter.emit @ core.umd.min.js:32NgZone.triggerError @ core.umd.min.js:32onHandleError @ core.umd.min.js:32ZoneDelegate.handleError @ zone.js:233Zone.runGuarded @ zone.js:129_loop_1 @ zone.js:416drainMicroTaskQueue @ zone.js:425ZoneTask.invoke @ zone.js:336

I've also noticed that a NavigationError object is thrown when I try to change to a route that uses Guards.  But only the error above is what is shown in the console.

NavigationError {id: 2, url: "/home", error: EmptyError}

I'm kind of at a loss and would appreciate any help.

Body:
Add this property to your route.

pathMatch: 'full

for eg.

{ pathMatch: 'full', path: "", component: HomeComponent }

It worked for me.


问:
What should my placeholders be for my TensorFlow regression with multiple features?

Hi, I'm trying to run Linear Regression using TensorFlow so I took this code and wish to fit my own dataset X_train (43, 5) and y_train (43,). Here's my code:

from __future__ import print_function

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
rng = numpy.random

# Parameters
learning_rate = 0.01
training_epochs = 1000
display_step = 50

# Data
train_X = X_train
train_Y = y_train
test_X = X_test
test_Y = y_test

n_samples = train_X.shape[0]
row = train_X.shape[0]
column = train_X.shape[1]

print(row, column)

# tf Graph Input
X = tf.placeholder("float", [row, column])
Y = tf.placeholder("float")

# Set model weights
#W = tf.Variable(rng.randn(), name="weight")
#b = tf.Variable(rng.randn(), name="bias")

W = tf.Variable(tf.zeros([column, 1]), name="weight")
b = tf.Variable(tf.zeros([1]), name="bias")

# Construct a linear model
pred = tf.add(tf.multiply(X, W), b)

# Mean squared error
cost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples)

# Gradient descent
#  Note, minimize() knows to modify W and b because Variable objects are trainable=True by default
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

# Initialize the variables (i.e. assign their default value)
init = tf.global_variables_initializer()

# Start training
with tf.Session() as sess:

    # Run the initializer
    sess.run(init)

    # Fit all training data
    for epoch in range(training_epochs):
        for (x, y) in zip(train_X, train_Y):
            sess.run(optimizer, feed_dict={X: x, Y: y})

        # Display logs per epoch step
        if (epoch+1) % display_step == 0:
            c = sess.run(cost, feed_dict={X: train_X, Y:train_Y})
            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \
                "W=", sess.run(W), "b=", sess.run(b))

    print("Optimization Finished!")
    training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
    print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')

    # Graphic display
    plt.plot(train_X, train_Y, 'ro', label='Original data')
    plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
    plt.legend()
    plt.show()

    print("Testing... (Mean square loss Comparison)")
    testing_cost = sess.run(
        tf.reduce_sum(tf.pow(pred - Y, 2)) / (2 * test_X.shape[0]),
        feed_dict={X: test_X, Y: test_Y})  # same function as cost above
    print("Testing cost=", testing_cost)
    print("Absolute mean square loss difference:", abs(
        training_cost - testing_cost))

    plt.plot(test_X, test_Y, 'bo', label='Testing data')
    plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
    plt.legend()
    plt.show()```

I tried to follow this to match the dimensions

But I keep getting this error: ValueError: Dimensions must be equal, but are 43 and 5 for 'Mul_18' (op: 'Mul') with input shapes: [43,5], [5,1]. Setting the placeholders to random solves this issue but then triggers another dimensional error at any of the lines: sess.run(cost, feed_dict={X: train_X, Y:train_Y}). Some one please help!?

答:
You are trying to do matrix multiplication. So you should make use of tf.matmul.

The operation of tf.multiply does elementwise multiplication for which both the tensor's shapes must be same.

Body:
Hi, I'm trying to run Linear Regression using TensorFlow so I took this code and wish to fit my own dataset X_train (43, 5) and y_train (43,). Here's my code:

from __future__ import print_function

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
rng = numpy.random

# Parameters
learning_rate = 0.01
training_epochs = 1000
display_step = 50

# Data
train_X = X_train
train_Y = y_train
test_X = X_test
test_Y = y_test

n_samples = train_X.shape[0]
row = train_X.shape[0]
column = train_X.shape[1]

print(row, column)

# tf Graph Input
X = tf.placeholder("float", [row, column])
Y = tf.placeholder("float")

# Set model weights
#W = tf.Variable(rng.randn(), name="weight")
#b = tf.Variable(rng.randn(), name="bias")

W = tf.Variable(tf.zeros([column, 1]), name="weight")
b = tf.Variable(tf.zeros([1]), name="bias")

# Construct a linear model
pred = tf.add(tf.multiply(X, W), b)

# Mean squared error
cost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples)

# Gradient descent
#  Note, minimize() knows to modify W and b because Variable objects are trainable=True by default
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

# Initialize the variables (i.e. assign their default value)
init = tf.global_variables_initializer()

# Start training
with tf.Session() as sess:

    # Run the initializer
    sess.run(init)

    # Fit all training data
    for epoch in range(training_epochs):
        for (x, y) in zip(train_X, train_Y):
            sess.run(optimizer, feed_dict={X: x, Y: y})

        # Display logs per epoch step
        if (epoch+1) % display_step == 0:
            c = sess.run(cost, feed_dict={X: train_X, Y:train_Y})
            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \
                "W=", sess.run(W), "b=", sess.run(b))

    print("Optimization Finished!")
    training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
    print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')

    # Graphic display
    plt.plot(train_X, train_Y, 'ro', label='Original data')
    plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
    plt.legend()
    plt.show()

    print("Testing... (Mean square loss Comparison)")
    testing_cost = sess.run(
        tf.reduce_sum(tf.pow(pred - Y, 2)) / (2 * test_X.shape[0]),
        feed_dict={X: test_X, Y: test_Y})  # same function as cost above
    print("Testing cost=", testing_cost)
    print("Absolute mean square loss difference:", abs(
        training_cost - testing_cost))

    plt.plot(test_X, test_Y, 'bo', label='Testing data')
    plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
    plt.legend()
    plt.show()

I tried to follow this to match the dimensions

But I keep getting this error: ValueError: Dimensions must be equal, but are 43 and 5 for 'Mul_18' (op: 'Mul') with input shapes: [43,5], [5,1]. Setting the placeholders to random solves this issue but then triggers another dimensional error at any of the lines: sess.run(cost, feed_dict={X: train_X, Y:train_Y}). Some one please help!?


问:
MongoDB: Find array element which having some value?
```<code>{
"_id" : ObjectId("55caf0298c1c44740469306c"),
"data" : {
    "field" : {
        "fields" : [
            {
                "name" : "demo",
                "type" : "data",
                "value" : "A"
            }
        ]
    }
}
</code>```

}

I want Only those Array element should come where value=A, rest is blank so it should not show.

Desire Output:

```<code>{
    "_id" : ObjectId("55caef098c1c447404693064"),
    "data" : {
        "field" : {
            "fields" : [
                {
                    "value" : "A"
                }
            ]
        }
    }
}
</code>```

And also after finding all values in document I want to modify those values.

Note: value=A is not always first element ,it can be 2nd 3rd element.And in each document "value" : "A" is not not fixed it can be different like "value" : "B", only i want those document where value key is having value and where its blank it should not show.

Query:

```<code>db.getCollection('collection').aggregate([
    {$match: {'data.field.fields.name': 'demo'}},
    { "$project": {
        "_id": 0,
        "value": { "$arrayElemAt": ["$data.field.fields.value", 0] }

    }}
])
</code>```

Now i want to update the value .How can I update?

答:
If your mongodb version higher than 3.2 you can using $filter for projection https://docs.mongodb.com/master/reference/operator/aggregation/filter/#exp._S_filter

Hope this help

```<code>        db.yourtable.aggregate([
        {$project: {
            "data.field.fields": {$filter: {
                                    input: '$data.field.fields',
                                    as: 'fields',
                                    cond: {$ne: ['$$fields.value', '']}
            }}
        }}
    ])
</code>```

Body:
{
"_id" : ObjectId("55caf0298c1c44740469306c"),
"data" : {
    "field" : {
        "fields" : [
            {
                "name" : "demo",
                "type" : "data",
                "value" : "A"
            }
        ]
    }
}

}

I want Only those Array element should come where value=A, rest is blank so it should not show.

Desire Output:

{
    "_id" : ObjectId("55caef098c1c447404693064"),
    "data" : {
        "field" : {
            "fields" : [
                {
                    "value" : "A"
                }
            ]
        }
    }
}

And also after finding all values in document I want to modify those values.

Note: value=A is not always first element ,it can be 2nd 3rd element.And in each document "value" : "A" is not not fixed it can be different like "value" : "B", only i want those document where value key is having value and where its blank it should not show.

Query:

db.getCollection('collection').aggregate([
    {$match: {'data.field.fields.name': 'demo'}},
    { "$project": {
        "_id": 0,
        "value": { "$arrayElemAt": ["$data.field.fields.value", 0] }

    }}
])

Now i want to update the value .How can I update?

Body:
If your mongodb version higher than 3.2 you can using $filter for projection https://docs.mongodb.com/master/reference/operator/aggregation/filter/#exp._S_filter

Hope this help

        db.yourtable.aggregate([
        {$project: {
            "data.field.fields": {$filter: {
                                    input: '$data.field.fields',
                                    as: 'fields',
                                    cond: {$ne: ['$$fields.value', '']}
            }}
        }}
    ])


问:
I want to Block url in webview
Heres the acitivity of my code I want to like to block external link like if someone click on another webpage he or she cannot go to that webpage.

```<code>public class NewsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        String url = "https://www.example.com";
        WebView web = (WebView) findViewById(R.id.webView4);
        web.loadUrl(url);

        final WebView mWebView = (WebView) findViewById(R.id.webView4);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.getSettings().setSavePassword(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setSaveFormData(true);
        mWebView.getSettings().setSupportZoom(false);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setSupportMultipleWindows(false);
        mWebView.getSettings().setLightTouchEnabled(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                mWebView.loadUrl("javascript:(function() { " +

                        "document.getElementsByClassName('header_wrapper')[0].style.display='none'; " +
                        "document.getElementsByClassName('footer-contact')[0].style.display='none'; " +
                        "document.getElementsByClassName('navbar-header')[0].style.display='none'; " +
                        "document.getElementsByClassName('footer-social')[0].style.display='none'; " +
                        "document.getElementById('footer_bottom').style.display='none'; " +
                        "document.getElementById('footer_content').style.display='none'; " +
                        "document.getElementById('core_mobile_menu').style.display='none'; " +
                        "document.getElementById('catapult-cookie-bar').style.display='none'; " +

                        "})()");
            }
        });
        mWebView.loadUrl("https://www.example.com");

    }
}
</code>```

答:
Try this as per your code  </p>

```<code> public class NewsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        String url = "https://www.example.com";
        WebView web = (WebView) findViewById(R.id.webView4);
        web.loadUrl(url);

        final WebView mWebView = (WebView) findViewById(R.id.webView4);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.getSettings().setSavePassword(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setSaveFormData(true);
        mWebView.getSettings().setSupportZoom(false);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setSupportMultipleWindows(false);
        mWebView.getSettings().setLightTouchEnabled(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);

  webview.setWebViewClient(new WebViewClient() {
      public boolean shouldOverrideUrlLoading (WebView view, String url){

       return true;
   }
     });
        mWebView.loadUrl("https://www.example.com");

    }
}
</code>```

Title: I want to Block url in webview

Body:
Heres the acitivity of my code I want to like to block external link like if someone click on another webpage he or she cannot go to that webpage.

public class NewsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        String url = "https://www.example.com";
        WebView web = (WebView) findViewById(R.id.webView4);
        web.loadUrl(url);

        final WebView mWebView = (WebView) findViewById(R.id.webView4);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.getSettings().setSavePassword(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setSaveFormData(true);
        mWebView.getSettings().setSupportZoom(false);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setSupportMultipleWindows(false);
        mWebView.getSettings().setLightTouchEnabled(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                mWebView.loadUrl("javascript:(function() { " +

                        "document.getElementsByClassName('header_wrapper')[0].style.display='none'; " +
                        "document.getElementsByClassName('footer-contact')[0].style.display='none'; " +
                        "document.getElementsByClassName('navbar-header')[0].style.display='none'; " +
                        "document.getElementsByClassName('footer-social')[0].style.display='none'; " +
                        "document.getElementById('footer_bottom').style.display='none'; " +
                        "document.getElementById('footer_content').style.display='none'; " +
                        "document.getElementById('core_mobile_menu').style.display='none'; " +
                        "document.getElementById('catapult-cookie-bar').style.display='none'; " +

                        "})()");
            }
        });
        mWebView.loadUrl("https://www.example.com");

    }
}

Body:
Try this as per your code

 public class NewsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        String url = "https://www.example.com";
        WebView web = (WebView) findViewById(R.id.webView4);
        web.loadUrl(url);

        final WebView mWebView = (WebView) findViewById(R.id.webView4);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.getSettings().setSavePassword(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setSaveFormData(true);
        mWebView.getSettings().setSupportZoom(false);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setSupportMultipleWindows(false);
        mWebView.getSettings().setLightTouchEnabled(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);

  webview.setWebViewClient(new WebViewClient() {
      public boolean shouldOverrideUrlLoading (WebView view, String url){

       return true;
   }
     });
        mWebView.loadUrl("https://www.example.com");

    }
}


问:
How to expand allocated memory in place
Is there something like std::realloc but do nothing if it fails to expand the existing memory (of course it will let you know it failed)?

I mean truly expand in place. Not copy to a newly created memory chunk.

答:
truly expand in place. Not copy to a newly created memory chunk.

This is impossible because of how virtual address space works on direct-addressing (non-segmented) instruction set architectures like x86-64 (or ARM, MIPS, RISCV, etc....).

(so that strong limitation is mostly not from software, but from your hardware, in the previous century some segmented architectures like iAPX432 or Rekursiv have been proposed, but failed)

Let's suppose you want to realloc a pointer zone of one megabytes to get four megabytes of more memory. But the virtual address space of your process could contain some other data -for some other malloc-ed zone or something else like a code segment, a call stack, etc...- used two megabytes ahead. So you need to move your (growing) zone -by asking your OS for some fresh 4 megabyte zone- and copy from the previous one.

On Linux, look into proc(5) (e.g. type man 5 proc in a terminal) and into mmap(2). Run the cat /proc/self/maps and cat /proc/$$/maps commands in some terminal to get a better intuition about virtual address space. Be aware that all memory management is done above such mmap and related (sometimes, old sbrk) system calls. So your malloc or operator new is (sometimes) using them (most of the time, reusing previously free-d zone is preferable). Use strace(1) to explore the system calls done by existing programs.

BTW, on Linux, both your C standard library and your C++ standard library are free software. You could study their source code.

Read also Operating Systems: Three Easy Pieces to understand more how OSes work. Consider reading some book on Computer Architecture (or at least some slides on the simplified Y86 architecture). You've got some deep misunderstanding about how your computer works.

Title: How to expand allocated memory in place


答:
There is multiple solutions to do this.

1- You on click of div element you can check if clicked element is exactly the div element or not:

```<code>if(event.target.tagName == 'DIV'){
    // then redirect to target page
}
</code>```

2- Or you can stop your select element from propagating event to upper level parents, as you did, but you didn't bind event handler to correct event on select element. You've used keypress on select but you have to use click event:

Fiddle: https://jsfiddle.net/hk7861es/6/

Title: How can HTML <select/> prevent click through parent's div

Body:
I'm creating shopping cart page that there's a div have a click listener for redirecting to the product page, but you also can select qty on the div. How can I prevent the redirection when selecting from <select/>

I've tried event.stopPropagation() / e.preventDefault() on select but not working

Here's the sample code.

https://jsfiddle.net/hk7861es/2/

Body:
There is multiple solutions to do this.

1- You on click of div element you can check if clicked element is exactly the div element or not:

if(event.target.tagName == 'DIV'){
    // then redirect to target page
}

2- Or you can stop your select element from propagating event to upper level parents, as you did, but you didn't bind event handler to correct event on select element. You've used keypress on select but you have to use click event:

Fiddle: https://jsfiddle.net/hk7861es/6/


问:
How can I get Location Specific time and date using angular?
All,

I found getLocaleDateFormat via angular.io. But, I have no idea how to use it.

This the link- https://angular.io/api/common/getLocaleDateFormat.

Has anyone here used this function? If so, please help me.

答:
Normal date function in javascript itself will give the location specific date and time

```<code>    date : Date = new Date();
    today = Date.now();
</code>```

You can also use date pipes in angular to format the date and time

```<code><!--output 'Monday, June 15, 2015'-->
    <p>Or if you prefer, {{today | date:'fullDate'}}</p>

    <!--output '9:43 AM'-->
    <p>The time is {{today | date:'shortTime'}}</p>
</code>```

You can also display the date in french and other languages by importing and registering locale in app.module.ts

app.module.ts

```<code>import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';

registerLocaleData(localeFr);
</code>```

Template to display date in french

```<code><!--output 'Lundi 15 Juin 2015 à 09:03:01 GMT+01:00'-->
    <p>The full date/time in french is: {{today | date:'full':'':'fr'}}</p>
</code>```

Working demo

Body:
Normal date function in javascript itself will give the location specific date and time

    date : Date = new Date();
    today = Date.now();

You can also use date pipes in angular to format the date and time

<!--output 'Monday, June 15, 2015'-->
    <p>Or if you prefer, {{today | date:'fullDate'}}</p>

    <!--output '9:43 AM'-->
    <p>The time is {{today | date:'shortTime'}}</p>

You can also display the date in french and other languages by importing and registering locale in app.module.ts

app.module.ts

import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';

registerLocaleData(localeFr);

Template to display date in french

<!--output 'Lundi 15 Juin 2015 à 09:03:01 GMT+01:00'-->
    <p>The full date/time in french is: {{today | date:'full':'':'fr'}}</p>

Working demo


问:
Angular2 [selected] does not work to set up the default value?
I'm trying to set up default value for my selection so I tried

```<code>[selected]= "selected_choice == 'one'"
</code>```

something like this

but this didn't work.

People said [selected] no longer works so I also tried [attr.selected] but didn't work as well..

this is my whole code for one select tag

```<code>  <select (change)="passValue3()" formControlName="school" class="form-control" required [(ngModel)]="selected_student" class="selectionbox">
    <option *ngIf="selected_student == undefined">학년 선택</option>
    <option *ngFor="let gradetype of gradeTypes" [ngValue]="gradetype" [attr.selected] = "gradetype.gradeType === 'Middle'">{{gradetype.gradeName}}</option>
</select>
</code>```

How can I set up the default option for the select?

答:
you compare options to select by compareWith property, If you are using angular 4, may be it will not working on angular 2.

HTML File :

```<code><select [compareWith]="byAnimal" [(ngModel)]="selectedAnimal">
  <option *ngFor="let animal of animals" [ngValue]="animal">
    {{animal.type}}
  </option>
</select>
</code>```

TS File

```<code>byAnimal(item1,item2){
  return item1.type == item2.type;
}
</code>```

One of the best solution from this link

Body:
I'm trying to set up default value for my selection so I tried

[selected]= "selected_choice == 'one'"

something like this

but this didn't work.

People said [selected] no longer works so I also tried [attr.selected] but didn't work as well..

this is my whole code for one select tag

  <select (change)="passValue3()" formControlName="school" class="form-control" required [(ngModel)]="selected_student" class="selectionbox">
    <option *ngIf="selected_student == undefined">학년 선택</option>
    <option *ngFor="let gradetype of gradeTypes" [ngValue]="gradetype" [attr.selected] = "gradetype.gradeType === 'Middle'">{{gradetype.gradeName}}</option>
</select>

How can I set up the default option for the select?

Body:
you compare options to select by compareWith property, If you are using angular 4, may be it will not working on angular 2.

HTML File :

<select [compareWith]="byAnimal" [(ngModel)]="selectedAnimal">
  <option *ngFor="let animal of animals" [ngValue]="animal">
    {{animal.type}}
  </option>
</select>

TS File

byAnimal(item1,item2){
  return item1.type == item2.type;
}

One of the best solution from this link


问:
WinAPI - Problem to append text to an editbox
I created a simple window with a multiline Edit Control:

```<code>Edit = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), NULL,
                    WS_CHILD | WS_VISIBLE | ES_MULTILINE,
                    20, 200, 200, 200,
                    hWnd, (HMENU)EDIT, GetModuleHandle(NULL), NULL);
</code>```

If I set text using a WM_SETTEXT message, I don't get errorrs, but if I use EM_REPLACESEL
I get Error 5 (ERROR_ACCESS_DENIED):

```<code>SendMessage(GetDlgItem(hWnd, EDIT), EM_REPLACESEL, 0, (LPARAM)TEXT("\r\nSome text"));
if (GetLastError()) {
    /* Error 5 ERROR_ACCESS_DENIED */
}
</code>```

Same problem with EM_SETSEL:

```<code>SendMessage(GetDlgItem(hWnd, EDIT), EM_SETSEL, (WPARAM)(0),(LPARAM)(-1));
SendMessage(GetDlgItem(hWnd, EDIT), EM_REPLACESEL, 0, (LPARAM)TEXT("\r\nSome text"));
if (GetLastError()) {
    /* Error 5 ERROR_ACCESS_DENIED */
}
</code>```

I noticed that if I send a WM_SETFOCUS message before the EM_REPLACESEL there are no error:

```<code>SendMessage(GetDlgItem(hWnd, EDIT), WM_SETFOCUS, (WPARAM)GetDlgItem(hWnd, EDIT), 0);
SendMessage(GetDlgItem(hWnd, EDIT), EM_REPLACESEL, 0, (LPARAM)TEXT("\r\nSome text"));
if (GetLastError()) {
    /* NO ERRORS */
}
</code>```

How can I resolve this problem?
Do I have to send a WM_SETFOCUS message before the EM_REPLACESEL one every time I want to append some text to my Editbox?

Thanks for help!

答: You might need to use SendDlgItemMessage instead of SendMessage.</p>

Body:
I created a simple window with a multiline Edit Control:

Edit = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), NULL,
                    WS_CHILD | WS_VISIBLE | ES_MULTILINE,
                    20, 200, 200, 200,
                    hWnd, (HMENU)EDIT, GetModuleHandle(NULL), NULL);

If I set text using a WM_SETTEXT message, I don't get errorrs, but if I use EM_REPLACESEL
I get Error 5 (ERROR_ACCESS_DENIED):

SendMessage(GetDlgItem(hWnd, EDIT), EM_REPLACESEL, 0, (LPARAM)TEXT("\r\nSome text"));
if (GetLastError()) {
    /* Error 5 ERROR_ACCESS_DENIED */
}

Same problem with EM_SETSEL:

SendMessage(GetDlgItem(hWnd, EDIT), EM_SETSEL, (WPARAM)(0),(LPARAM)(-1));
SendMessage(GetDlgItem(hWnd, EDIT), EM_REPLACESEL, 0, (LPARAM)TEXT("\r\nSome text"));
if (GetLastError()) {
    /* Error 5 ERROR_ACCESS_DENIED */
}

I noticed that if I send a WM_SETFOCUS message before the EM_REPLACESEL there are no error:

SendMessage(GetDlgItem(hWnd, EDIT), WM_SETFOCUS, (WPARAM)GetDlgItem(hWnd, EDIT), 0);
SendMessage(GetDlgItem(hWnd, EDIT), EM_REPLACESEL, 0, (LPARAM)TEXT("\r\nSome text"));
if (GetLastError()) {
    /* NO ERRORS */
}

How can I resolve this problem?
Do I have to send a WM_SETFOCUS message before the EM_REPLACESEL one every time I want to append some text to my Editbox?

Thanks for help!


问:
deleting all documents with out dropping index in elasticsearch java API
Is there any simple Java API to delete all the documents from elastic search with out dropping the index.

I know that we could get all the ids and delete each document one by one

```<code>DeleteResponse response = _client.prepareDelete(INDEX, TYPE, id)
            .setRefresh(true)
            .execute()
            .actionGet();
</code>```

But I was looking for TRUNCATE kind of scenario.

At present I am deleting the index and recreating the mapping in unit tests.

答:
You could find elaseticsearchservice.functioncall - it is because i have written all es operation in a separate class

Async way --

```<code>          DeleteByQueryRequestBuilder deleteByQueryRequestBuilder = elasticsearchService.deleteAllDocument(PRODUCTSINDEX);
            deleteByQueryRequestBuilder.execute(new ActionListener<BulkIndexByScrollResponse>() {
                @Override
                public void onResponse(BulkIndexByScrollResponse bulkIndexByScrollResponse) {
                    if (bulkIndexByScrollResponse.getDeleted() == 0) {

                    } else if (bulkIndexByScrollResponse.getDeleted() > 0) {
                       // getDeleted() gives you how many docs in that index have been deleted
                    }
                }

                @Override
                public void onFailure(Exception e) {
                   //reason like no index exists, improper connection etc
                }
            });

  ------------------------------------------------------------------
      public DeleteByQueryRequestBuilder deleteAllDocument(String indexName) {
            DeleteByQueryRequestBuilder DeleteByQueryRequestBuilder = DeleteByQueryAction.INSTANCE.newRequestBuilder(client)
                    .filter(QueryBuilders.matchAllQuery())
                    .source(indexName);
            return DeleteByQueryRequestBuilder;

        }
</code>```

Normal way--

```<code>public void deleteAllProduct(RoutingContext routingContext) {
        long starttime = System.currentTimeMillis();
       elasticsearchService.deleteAllDocument1(PRODUCTSINDEX);

    }
--------------------------------------------------------------

  public void deleteAllDocument1(String indexName) {
        ListenableActionFuture<BulkIndexByScrollResponse> execute = DeleteByQueryAction.INSTANCE.newRequestBuilder(client)
                .filter(QueryBuilders.matchAllQuery())
                .source(indexName).execute();

        try {
            BulkIndexByScrollResponse   bulkIndexByScrollResponse = execute.get();
            if (bulkIndexByScrollResponse.getDeleted()>0)
            {
                System.out.println(bulkIndexByScrollResponse.getDeleted());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }
</code>```

Body:
Is there any simple Java API to delete all the documents from elastic search with out dropping the index.

I know that we could get all the ids and delete each document one by one

DeleteResponse response = _client.prepareDelete(INDEX, TYPE, id)
            .setRefresh(true)
            .execute()
            .actionGet();

But I was looking for TRUNCATE kind of scenario.

At present I am deleting the index and recreating the mapping in unit tests.

Body:
You could find elaseticsearchservice.functioncall - it is because i have written all es operation in a separate class

Async way --

          DeleteByQueryRequestBuilder deleteByQueryRequestBuilder = elasticsearchService.deleteAllDocument(PRODUCTSINDEX);
            deleteByQueryRequestBuilder.execute(new ActionListener<BulkIndexByScrollResponse>() {
                @Override
                public void onResponse(BulkIndexByScrollResponse bulkIndexByScrollResponse) {
                    if (bulkIndexByScrollResponse.getDeleted() == 0) {

                    } else if (bulkIndexByScrollResponse.getDeleted() > 0) {
                       // getDeleted() gives you how many docs in that index have been deleted
                    }
                }

                @Override
                public void onFailure(Exception e) {
                   //reason like no index exists, improper connection etc
                }
            });

  ------------------------------------------------------------------
      public DeleteByQueryRequestBuilder deleteAllDocument(String indexName) {
            DeleteByQueryRequestBuilder DeleteByQueryRequestBuilder = DeleteByQueryAction.INSTANCE.newRequestBuilder(client)
                    .filter(QueryBuilders.matchAllQuery())
                    .source(indexName);
            return DeleteByQueryRequestBuilder;

        }

Normal way--

public void deleteAllProduct(RoutingContext routingContext) {
        long starttime = System.currentTimeMillis();
       elasticsearchService.deleteAllDocument1(PRODUCTSINDEX);

    }
--------------------------------------------------------------

  public void deleteAllDocument1(String indexName) {
        ListenableActionFuture<BulkIndexByScrollResponse> execute = DeleteByQueryAction.INSTANCE.newRequestBuilder(client)
                .filter(QueryBuilders.matchAllQuery())
                .source(indexName).execute();

        try {
            BulkIndexByScrollResponse   bulkIndexByScrollResponse = execute.get();
            if (bulkIndexByScrollResponse.getDeleted()>0)
            {
                System.out.println(bulkIndexByScrollResponse.getDeleted());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }


问:
ion-select select/unselect all options
How to provide an option to select all the option at once in an ion-select element. Below is my code.</p>

```<code> <ion-item>
      <ion-label>Primary Data</ion-label>
      <ion-select [(ngModel)]="primaryData">
        <ion-option>10</ion-option>
        <ion-option>11</ion-option>
        <ion-option>13</ion-option>
      </ion-select>
    </ion-item>
</code>```

答:
Why not just do the following:

```<code><ion-item>
    <ion-label>Primary Data</ion-label>
    <ion-select [(ngModel)]="primaryData">
        <ion-option value="All">All</ion-option>
        <ion-option value="10">10</ion-option>
        <ion-option value="11">11</ion-option>
        <ion-option value="13">13</ion-option>
    </ion-select>
</ion-item>
</code>```

Then inside your component.ts file just check which option is selected.

Title: ion-select select/unselect all options

Body:
How to provide an option to select all the option at once in an ion-select element. Below is my code.

 <ion-item>
      <ion-label>Primary Data</ion-label>
      <ion-select [(ngModel)]="primaryData">
        <ion-option>10</ion-option>
        <ion-option>11</ion-option>
        <ion-option>13</ion-option>
      </ion-select>
    </ion-item>

Body:
Why not just do the following:

<ion-item>
    <ion-label>Primary Data</ion-label>
    <ion-select [(ngModel)]="primaryData">
        <ion-option value="All">All</ion-option>
        <ion-option value="10">10</ion-option>
        <ion-option value="11">11</ion-option>
        <ion-option value="13">13</ion-option>
    </ion-select>
</ion-item>

Then inside your component.ts file just check which option is selected.