问:
Modify style of a html tag inside of a id-element
On my website I have a style like this:

#titlebar a {
  display: inline-block;
}
```

<p>and html:</p>

```

    test
    test
    test
    test

```

<p>I want to change the style of all the <code><a></code> tags in the <code><div></code> with the id <code>titlebar</code>. <code>display</code> should be changed from <code>inline-block</code> to <code>block</code>. Is this possible with JavaScript or do I have to search a different way to do this?</p>

<p>https://jsfiddle.net/Ln0a235v/2/</p>

<p><strong>Complete Context:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Using Gurvinder's solution.

menu = false;

function toggleMenu() {
  if (menu) {
    document.getElementById("titlebar").style.maxHeight = "4em";
    document.getElementById("fab").style.top = "calc(4em - 32px)";
    document.querySelectorAll("#titlebar a").forEach(function(el) {
      el.style.display = "inline-block";
    });
  } else {
    document.getElementById("titlebar").style.maxHeight = "500px";
    document.getElementById("fab").style.top = "0px";
    document.querySelectorAll("#titlebar a").forEach(function(el) {
      el.style.display = "block";
    });
  }
  menu = !menu;
}</code>```

body {
  background: #ffffff;
  font-family: sans-serif;
}

#titlebar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #3f51b5;
  min-height: 4em;
  max-height: 4em;
  box-shadow: 0px 4px 8px #757575;
  transition: max-height 0.3s;
}

#titlebar a {
  font-variant: small-caps;
  line-height: 4em;
  display: inline-block;
  padding: 0px 16px;
  margin: 0px;
  color: #ffffff;
  text-decoration: none;
  transition: background 0.2s, display 1s;
  outline: none;
}

#titlebar a:hover {
  background: #ff4081;
}

#fab {
  position: fixed;
  width: 64px;
  height: 64px;
  z-index: 100;
  /*right: 64px;*/
  right: 3%;
  top: calc(4em - 32px);
  transition: top 0.3s;
}

.main {
  box-shadow: 0px 4px 8px #757575;
  width: 80%;
  margin: 0 auto;
  margin-bottom: 64px;
}

.content {
  padding: 6em 0;
  margin: 0 10%;
}

hr {
  border: 1px solid #c5cae9;
}

.content img {
  float: right;
  margin-left: 32px;
  margin-bottom: 32px;
  width: 30%;
  min-width: 256px;
  box-shadow: 0px 4px 8px #757575;
  padding: 8px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="titlebar">
  <nav>
    ToggleMenu
    test
    test
    test
  </nav>
</div>

<div class="main">
  <div class="content">
    <h1>Lorem ipsum</h1>
    <p>
      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
      At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore
      eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
      euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate
      velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis
      eleifend option congue nihil imperdiet doming id quod mazim placerat facer
    </p>
    <hr/>
    <h1>Lorem ipsum</h1>
    <p>
      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
      At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore
      eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
      euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate
      velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis
      eleifend option congue nihil imperdiet doming id quod mazim placerat facer
    </p>
  </div>
</div></code>```

答:
Yes, it is possible with JavaScript. A better and unobtrusive way is to use a combination of both JavaScript and CSS:

setTimeout(function () {
  // See from here:
  document.getElementById("titlebar").classList.add("block");
}, 1000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#titlebar a {
  display: inline-block;
  background: #ccf;
}
#titlebar.block a {
  display: block;
}</code>```

    test
    test
    test
    test

```
</div>
</div>
</p>

<p><strong>Update:</strong> Based on the fiddle by OP, I have applied my solution here:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function toggleMenu() {
  document.getElementById("titlebar").classList.toggle("block");
}</code>```

body {
  background: #ffffff;
  font-family: sans-serif;
}

#titlebar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #3f51b5;
  min-height: 4em;
  max-height: 4em;
  box-shadow: 0px 4px 8px #757575;
  transition: max-height 0.3s;
}

#titlebar a {
  font-variant: small-caps;
  line-height: 4em;
  display: inline-block;
  padding: 0px 16px;
  margin: 0px;
  color: #ffffff;
  text-decoration: none;
  transition: background 0.2s, display 1s;
  outline: none;
}

#titlebar a:hover {
  background: #ff4081;
}

#fab {
  position: fixed;
  width: 64px;
  height: 64px;
  z-index: 100;
  /*right: 64px;*/
  right: 3%;
  top: calc(4em - 32px);
  transition: top 0.3s;
}

.main {
  box-shadow: 0px 4px 8px #757575;
  width: 80%;
  margin: 0 auto;
  margin-bottom: 64px;
}

.content {
  padding: 6em 0;
  margin: 0 10%;
}

hr {
  border: 1px solid #c5cae9;
}

.content img {
  float: right;
  margin-left: 32px;
  margin-bottom: 32px;
  width: 30%;
  min-width: 256px;
  box-shadow: 0px 4px 8px #757575;
  padding: 8px;
}

#titlebar.block {
  max-height: none;
}
#titlebar.block a {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="titlebar">
  <nav>
    ToggleMenu
    test
    test
    test
  </nav>
</div>

<div class="main">
  <div class="content">
    <h1>Lorem ipsum</h1>
    <p>
      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
      At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore
      eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
      euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate
      velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis
      eleifend option congue nihil imperdiet doming id quod mazim placerat facer
    </p>
    <hr/>
    <h1>Lorem ipsum</h1>
    <p>
      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
      At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore
      eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
      euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate
      velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis
      eleifend option congue nihil imperdiet doming id quod mazim placerat facer
    </p>
  </div>
</div></code>```

The changed elements are here:

```<code><a onclick="toggleMenu(); return false;" href="#">ToggleMenu</a>
// Added a return false.
</code>```

CSS Addition

#titlebar.block {
  max-height: none;
}
#titlebar.block a {
  display: block;
}
```

Body:
On my website I have a style like this:

#titlebar a {
  display: inline-block;
}

and html:

    test
    test
    test
    test

I want to change the style of all the  tags in the
 with the id titlebar. display should be changed from inline-block to block. Is this possible with JavaScript or do I have to search a different way to do this?

https://jsfiddle.net/Ln0a235v/2/

Complete Context:

// Using Gurvinder's solution.

menu = false;

function toggleMenu() {
  if (menu) {
    document.getElementById("titlebar").style.maxHeight = "4em";
    document.getElementById("fab").style.top = "calc(4em - 32px)";
    document.querySelectorAll("#titlebar a").forEach(function(el) {
      el.style.display = "inline-block";
    });
  } else {
    document.getElementById("titlebar").style.maxHeight = "500px";
    document.getElementById("fab").style.top = "0px";
    document.querySelectorAll("#titlebar a").forEach(function(el) {
      el.style.display = "block";
    });
  }
  menu = !menu;
}

body {
  background: #ffffff;
  font-family: sans-serif;
}

#titlebar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #3f51b5;
  min-height: 4em;
  max-height: 4em;
  box-shadow: 0px 4px 8px #757575;
  transition: max-height 0.3s;
}

#titlebar a {
  font-variant: small-caps;
  line-height: 4em;
  display: inline-block;
  padding: 0px 16px;
  margin: 0px;
  color: #ffffff;
  text-decoration: none;
  transition: background 0.2s, display 1s;
  outline: none;
}

#titlebar a:hover {
  background: #ff4081;
}

#fab {
  position: fixed;
  width: 64px;
  height: 64px;
  z-index: 100;
  /*right: 64px;*/
  right: 3%;
  top: calc(4em - 32px);
  transition: top 0.3s;
}

.main {
  box-shadow: 0px 4px 8px #757575;
  width: 80%;
  margin: 0 auto;
  margin-bottom: 64px;
}

.content {
  padding: 6em 0;
  margin: 0 10%;
}

hr {
  border: 1px solid #c5cae9;
}

.content img {
  float: right;
  margin-left: 32px;
  margin-bottom: 32px;
  width: 30%;
  min-width: 256px;
  box-shadow: 0px 4px 8px #757575;
  padding: 8px;
}

    ToggleMenu
    test
    test
    test

Lorem ipsum

      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
      At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore
      eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
      euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate
      velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis
      eleifend option congue nihil imperdiet doming id quod mazim placerat facer

Lorem ipsum

      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
      At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore
      eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
      euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate
      velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis
      eleifend option congue nihil imperdiet doming id quod mazim placerat facer

Body:
Yes, it is possible with JavaScript. A better and unobtrusive way is to use a combination of both JavaScript and CSS:

setTimeout(function () {
  // See from here:
  document.getElementById("titlebar").classList.add("block");
}, 1000);

#titlebar a {
  display: inline-block;
  background: #ccf;
}
#titlebar.block a {
  display: block;
}

<div id="titlebar">
  <nav>
    <a href="#">test</a>
    <a href="#">test</a>
    <a href="#">test</a>
    <a href="#">test</a>
  </nav>
</div>

Update: Based on the fiddle by OP, I have applied my solution here:

function toggleMenu() {
  document.getElementById("titlebar").classList.toggle("block");
}

body {
  background: #ffffff;
  font-family: sans-serif;
}

#titlebar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #3f51b5;
  min-height: 4em;
  max-height: 4em;
  box-shadow: 0px 4px 8px #757575;
  transition: max-height 0.3s;
}

#titlebar a {
  font-variant: small-caps;
  line-height: 4em;
  display: inline-block;
  padding: 0px 16px;
  margin: 0px;
  color: #ffffff;
  text-decoration: none;
  transition: background 0.2s, display 1s;
  outline: none;
}

#titlebar a:hover {
  background: #ff4081;
}

#fab {
  position: fixed;
  width: 64px;
  height: 64px;
  z-index: 100;
  /*right: 64px;*/
  right: 3%;
  top: calc(4em - 32px);
  transition: top 0.3s;
}

.main {
  box-shadow: 0px 4px 8px #757575;
  width: 80%;
  margin: 0 auto;
  margin-bottom: 64px;
}

.content {
  padding: 6em 0;
  margin: 0 10%;
}

hr {
  border: 1px solid #c5cae9;
}

.content img {
  float: right;
  margin-left: 32px;
  margin-bottom: 32px;
  width: 30%;
  min-width: 256px;
  box-shadow: 0px 4px 8px #757575;
  padding: 8px;
}

#titlebar.block {
  max-height: none;
}
#titlebar.block a {
  display: block;
}

<div id="titlebar">
  <nav>
    <a onclick="toggleMenu(); return false;" href="#">ToggleMenu</a>
    <a href="#">test</a>
    <a href="#">test</a>
    <a href="#">test</a>
  </nav>
</div>

<div class="main">
  <div class="content">
    <h1>Lorem ipsum</h1>
    <p>
      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
      At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore
      eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
      euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate
      velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis
      eleifend option congue nihil imperdiet doming id quod mazim placerat facer
    </p>
    <hr/>
    <h1>Lorem ipsum</h1>
    <p>
      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
      At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore
      eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
      euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate
      velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis
      eleifend option congue nihil imperdiet doming id quod mazim placerat facer
    </p>
  </div>
</div>

The changed elements are here:

<a onclick="toggleMenu(); return false;" href="#">ToggleMenu</a>
// Added a return false.

CSS Addition

#titlebar.block {
  max-height: none;
}
#titlebar.block a {
  display: block;
}


来源: stackexchange

问:
Iterate through every file in one directory
How do I write a loop in ruby so that I can execute a block of code on each file?

I'm new to ruby, and I've concluded that the way to do this is a do each loop.

The ruby file will be executed from a different directory than the directory I want to loop through.

I've tried the Dir.foreach and I couldn't get it to work.

答:
I like this one, that hasn't been mentioned above.

```<code>require 'pathname'

Pathname.new('/my/dir').children.each do |path|
    puts path
end
</code>```

The benefit is that you get a Pathname object instead of a string, that you can do useful stuff with and traverse further.

ContentLicense: CC BY-SA 3.0

Body:
I like this one, that hasn't been mentioned above.

require 'pathname'

Pathname.new('/my/dir').children.each do |path|
    puts path
end

The benefit is that you get a Pathname object instead of a string, that you can do useful stuff with and traverse further.


问:
Remove illegal xml characters from UTF-16LE encoded file
I have a java application that parses an xml file that was encoded in utf-16le. The xml has been erroring out while being parsed due to illegal xml characters. My solution is to read in this file into a java string, then removing the xml characters, so it can be parsed successfully. It works 99% but there are some slight differences in the input output from this process, not caused by the illegal characters being removed, but going from the utf-16le encoding to java string utf-16.. i think

```<code>BufferedReader reader = null;
    String fileText = ""; //stored as UTF-16
    try {
        reader = new BufferedReader(new InputStreamReader(in, "UTF-16LE"));
        for (String line; (line = reader.readLine()) != null; ) {
            fileText += line;
        }
    } catch (Exception ex) {
        logger.log(Level.WARNING, "Error removing illegal xml characters", ex);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }

//code to remove illegal chars from string here, irrelevant to problem

        ByteArrayInputStream inStream = new ByteArrayInputStream(fileText.getBytes("UTF-16LE"));
    Document doc = XmlUtil.openDocument(inStream, XML_ROOT_NODE_ELEM);
</code>```

Do characters get changed/lost when going from UTF-16LE to UTF-16? Is there a way to do this in java and assuring the input is exactly the same as the output?

答:
Certainly one problem is that readLine throws away the line ending.

You would need to do something like:

```<code>       fileText += line + "\r\n";
</code>```

Otherwise XML attributes, DTD entities, or something else could get glued together where at least a space was required. Also you do not want the text content to be altered when it contains a line break.

Performance (speed and memory) can be improved using a

```<code>StringBuilder fileText = new StringBuilder();
... fileText.append(line).append("\n");
... fileText.toString();
</code>```

Then there might be a problem with the first character of the file, which
sometimes redundantly is added: a BOM char.

```<code>line = line.replace("\uFEFF", "");
</code>```

Body:
I have a java application that parses an xml file that was encoded in utf-16le. The xml has been erroring out while being parsed due to illegal xml characters. My solution is to read in this file into a java string, then removing the xml characters, so it can be parsed successfully. It works 99% but there are some slight differences in the input output from this process, not caused by the illegal characters being removed, but going from the utf-16le encoding to java string utf-16.. i think

BufferedReader reader = null;
    String fileText = ""; //stored as UTF-16
    try {
        reader = new BufferedReader(new InputStreamReader(in, "UTF-16LE"));
        for (String line; (line = reader.readLine()) != null; ) {
            fileText += line;
        }
    } catch (Exception ex) {
        logger.log(Level.WARNING, "Error removing illegal xml characters", ex);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }

//code to remove illegal chars from string here, irrelevant to problem

        ByteArrayInputStream inStream = new ByteArrayInputStream(fileText.getBytes("UTF-16LE"));
    Document doc = XmlUtil.openDocument(inStream, XML_ROOT_NODE_ELEM);

Do characters get changed/lost when going from UTF-16LE to UTF-16? Is there a way to do this in java and assuring the input is exactly the same as the output?

Body:
Certainly one problem is that readLine throws away the line ending.

You would need to do something like:

       fileText += line + "\r\n";

Otherwise XML attributes, DTD entities, or something else could get glued together where at least a space was required. Also you do not want the text content to be altered when it contains a line break.

Performance (speed and memory) can be improved using a

StringBuilder fileText = new StringBuilder();
... fileText.append(line).append("\n");
... fileText.toString();

Then there might be a problem with the first character of the file, which
sometimes redundantly is added: a BOM char.

line = line.replace("\uFEFF", "");


问:
How to run the tests of a module along with my application tests
What I am trying to achieve is to run the tests written in my modules along the with tests of the application. When we run gradlew test it runs all the tests of my app and modules, but my app has a lot of flavors and it's really impractical to run tests for all the flavors before building for a specific flavor.

So, I want to be able to run command gradlew TestQADebug and be able to run the tests in my modules along with the tests for the QA flavored debug build.

答:
Try with gradlew -q <task-name> <task-name>.

In your case, try below:
gradlew -q moduleName:testDebugUnitTest app:testQADebugUnitTest

More info there --> http://www.ekiras.com/2016/12/how-to-run-single-or-multiple-gradle-tasks.html


问:
Is there a shorter way for if-else chains?
```<code>if (80 <= m <= 100):
    g = "A"
elif (70 <= m < 80):
    g = "B"
elif (60 <= m < 70):
    g = "C"
elif (50 <= m < 60):
    g = "D"
elif (m < 50):
    g = "U"
</code>```

This is basically a grade measuring piece of code that takes in value m, meaning mark, and obtains grade g. Is there a shorter not necessarily more pythonic way for the same purpose?

Thanks in advance.

答:
Don't change your code. It's readable and easy maintainable. </p>

<p>In general, skip "smart" one-liners, because compilers/interpreters can understand your code easily, but humans can have hard times to understand it. </p>

Body:
if (80 <= m <= 100):
    g = "A"
elif (70 <= m < 80):
    g = "B"
elif (60 <= m < 70):
    g = "C"
elif (50 <= m < 60):
    g = "D"
elif (m < 50):
    g = "U"

This is basically a grade measuring piece of code that takes in value m, meaning mark, and obtains grade g. Is there a shorter not necessarily more pythonic way for the same purpose?

Thanks in advance.

Body:
Don't change your code. It's readable and easy maintainable.

In general, skip "smart" one-liners, because compilers/interpreters can understand your code easily, but humans can have hard times to understand it.


问:
onSelect function in antd calendar component
How to get the selected date inside the onSelect function, after update the selected date in the state and

```<code>onSelect = (cal) => {
      this.setState({  selectedValue: cal   });
      alert(this.state.selectedValue);
</code>```

I got the previous date in the alert but i need the current selected date, how to achieve this...?

答:
Problem here is that this.setState({}) is asynchronous. That means that alert can happen before state gets updated. What you can do is pass a callback.
Check this example which logs state after it has been updated:

```<code>this.setState({ selectedValue: cal }, () =>
      console.log(this.state.selectedValue);
    );
</code>```

Body:
How to get the selected date inside the onSelect function, after update the selected date in the state and

onSelect = (cal) => {
      this.setState({  selectedValue: cal   });
      alert(this.state.selectedValue);

I got the previous date in the alert but i need the current selected date, how to achieve this...?

Body:
Problem here is that this.setState({}) is asynchronous. That means that alert can happen before state gets updated. What you can do is pass a callback.
Check this example which logs state after it has been updated:

this.setState({ selectedValue: cal }, () =>
      console.log(this.state.selectedValue);
    );


问:
trying to modify the js function so that it gives the same output as it was when called the other js function
I am exporting the content on the webpage to the PDF file, for this i have used jsPDF API and i could able to get it work but now i want to use html2PDF as it resolves few issues which were faced when using jsPDF API.

I have written the function $scope.exportUsingJSPDF which is called when the button Export Using JSPDF is clicked. Similarly i want to implement the function $scope.exportUsingHTML2PDF which uses html2PDF API but could not succeed. Any inputs on how to modify  $scope.exportUsingHTML2PDF so that it iterates the divs and shows the div content as shown when invoked using  $scope.exportUsingJSPDF by clicking Export using JSPDF API.

Complete online example: https://plnkr.co/edit/454HUFF3rmLlkXLCQkbx?p=preview

js code:

```<code>    //trying to implement the below function same as $scope.exportUsingJSPDF, so
// that when user click on Export using HTML2PDF button, it exports the content to the PDF and generaes the PDF.
         $scope.exportUsingHTML2PDF = function(){
          var pdf = new jsPDF('l', 'pt', 'a4');
            var pdfName = 'test.pdf';

         pdf.canvas.height = 72 * 11;
         pdf.canvas.width = 72 * 8.5;
         html2pdf(document.getElementByClassName("myDivClass"), pdf, function(pdf){
             pdf.save(pdfName);
         });
         }

        $scope.exportUsingJSPDF = function() {
              var pdf = new jsPDF('p','pt','a4');
                var pdfName = 'test.pdf';

                var options = {   pagesplit: true};

                var $divs = $('.myDivClass')                //jQuery object of all the myDivClass divs
                var numRecursionsNeeded = $divs.length -1;     //the number of times we need to call addHtml (once per div)
                var currentRecursion=0;

                //Found a trick for using addHtml more than once per pdf. Call addHtml in the callback function of addHtml recursively.
                function recursiveAddHtmlAndSave(currentRecursion, totalRecursions){
                    //Once we have done all the divs save the pdf
                    if(currentRecursion==totalRecursions){
                        pdf.save(pdfName);
                    }else{
                        currentRecursion++;
                        pdf.addPage();
                        //$('.myDivClass')[currentRecursion] selects one of the divs out of the jquery collection as a html element
                        //addHtml requires an html element. Not a string like fromHtml.
                        pdf.fromHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
                            console.log(currentRecursion);
                            recursiveAddHtmlAndSave(currentRecursion, totalRecursions)
                        });
                    }
                }

                pdf.fromHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
                    recursiveAddHtmlAndSave(currentRecursion, numRecursionsNeeded);
                });
            }
</code>```

PS: I was trying to modify $scope.exportUsingHTML2PDF so that it gives the same output as generated when clicked on "Export using JSPDF" button which calls the function $scope.exportUsingJSPDF.

答:
With JSPDF and HTML2PDF, you have to get used to two fundamentally different coding styles:

JSPDF: imperative (javascript statements)

HTML2PDF: declarative (directives embedded in HTML)

So for page breaks:

JSPDF: pdf.addPage();

HTML2PDF:

That should work, however HTML2PDF is buggy and gives a "Supplied data is not a JPEG" error when

 is included (at least it does so for me, in Plunkr), despite being totally what the documentation tells us to do.

I haven't got time to debug it. You'll need to do some research. Someone will have posted a solution somewhere on the web.

Body:
I am exporting the content on the webpage to the PDF file, for this i have used jsPDF API and i could able to get it work but now i want to use html2PDF as it resolves few issues which were faced when using jsPDF API.

I have written the function $scope.exportUsingJSPDF which is called when the button Export Using JSPDF is clicked. Similarly i want to implement the function $scope.exportUsingHTML2PDF which uses html2PDF API but could not succeed. Any inputs on how to modify  $scope.exportUsingHTML2PDF so that it iterates the divs and shows the div content as shown when invoked using  $scope.exportUsingJSPDF by clicking Export using JSPDF API.

Complete online example: https://plnkr.co/edit/454HUFF3rmLlkXLCQkbx?p=preview

js code:

    //trying to implement the below function same as $scope.exportUsingJSPDF, so
// that when user click on Export using HTML2PDF button, it exports the content to the PDF and generaes the PDF.
         $scope.exportUsingHTML2PDF = function(){
          var pdf = new jsPDF('l', 'pt', 'a4');
            var pdfName = 'test.pdf';

         pdf.canvas.height = 72 * 11;
         pdf.canvas.width = 72 * 8.5;
         html2pdf(document.getElementByClassName("myDivClass"), pdf, function(pdf){
             pdf.save(pdfName);
         });
         }

        $scope.exportUsingJSPDF = function() {
              var pdf = new jsPDF('p','pt','a4');
                var pdfName = 'test.pdf';

                var options = {   pagesplit: true};

                var $divs = $('.myDivClass')                //jQuery object of all the myDivClass divs
                var numRecursionsNeeded = $divs.length -1;     //the number of times we need to call addHtml (once per div)
                var currentRecursion=0;

                //Found a trick for using addHtml more than once per pdf. Call addHtml in the callback function of addHtml recursively.
                function recursiveAddHtmlAndSave(currentRecursion, totalRecursions){
                    //Once we have done all the divs save the pdf
                    if(currentRecursion==totalRecursions){
                        pdf.save(pdfName);
                    }else{
                        currentRecursion++;
                        pdf.addPage();
                        //$('.myDivClass')[currentRecursion] selects one of the divs out of the jquery collection as a html element
                        //addHtml requires an html element. Not a string like fromHtml.
                        pdf.fromHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
                            console.log(currentRecursion);
                            recursiveAddHtmlAndSave(currentRecursion, totalRecursions)
                        });
                    }
                }

                pdf.fromHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
                    recursiveAddHtmlAndSave(currentRecursion, numRecursionsNeeded);
                });
            }

PS: I was trying to modify $scope.exportUsingHTML2PDF so that it gives the same output as generated when clicked on "Export using JSPDF" button which calls the function $scope.exportUsingJSPDF.

Body:
With JSPDF and HTML2PDF, you have to get used to two fundamentally different coding styles:

JSPDF: imperative (javascript statements)

HTML2PDF: declarative (directives embedded in HTML)

So for page breaks:

JSPDF: pdf.addPage();

HTML2PDF: <div class="html2pdf__page-break"></div>

That should work, however HTML2PDF is buggy and gives a "Supplied data is not a JPEG" error when <div class="html2pdf__page-break"></div> is included (at least it does so for me, in Plunkr), despite being totally what the documentation tells us to do.

I haven't got time to debug it. You'll need to do some research. Someone will have posted a solution somewhere on the web.


问:
How to add a Custom EqualTo To rule in jQuery.validation
I had a problem getting the sum of 2 inputs to be equal to a dynamic value. In my case I needed, 2 fields to be equal to 100. I thought I'd post my solution below for anyone else who may need this as is or to make a new custom validation rule.</p>

答:
Below is the answer I got. Field1 and Field2 must be equal to 100 in the below answer. </p>

```<code>$(document).ready(function(){
var msg;
var dynamicErrorMsg = function () { return msg; }

jQuery.validator.addMethod("equalToValue", function(value, element, param) {
    var target = parseInt($( param[0] ).val());
    var total = parseInt(value) + target;
    msg = " Field 1 and 2 must be equal to " + param[1];
    return this.optional(element) || (total == param[1]);
}, dynamicErrorMsg);

$("form").validate({
    rules: {
         field1: {
             equalToValue: ["#field2", 100]
         }
    }
});
});
</code>```

Body:
Below is the answer I got. Field1 and Field2 must be equal to 100 in the below answer.

$(document).ready(function(){
var msg;
var dynamicErrorMsg = function () { return msg; }

jQuery.validator.addMethod("equalToValue", function(value, element, param) {
    var target = parseInt($( param[0] ).val());
    var total = parseInt(value) + target;
    msg = " Field 1 and 2 must be equal to " + param[1];
    return this.optional(element) || (total == param[1]);
}, dynamicErrorMsg);

$("form").validate({
    rules: {
         field1: {
             equalToValue: ["#field2", 100]
         }
    }
});
});


问:
C++14: Generic lambda with generic std::function as class member
Consider this pseudo-snippet:

```<code>class SomeClass
{
public:
    SomeClass()
    {
        if(true)
        {
            fooCall = [](auto a){ cout << a.sayHello(); };
        }
        else
        {
            fooCall = [](auto b){ cout << b.sayHello(); };
        }
    }
private:
    template<typename T>
    std::function<void(T)> fooCall;
};
</code>```

What I want is a class member fooCall which stores a generic lambda, which in turn is assigned in the constructor.

The compiler complains that fooCall cannot be a templated data member.

Is there any simple solution on how i can store generic lambdas in a class?

答:
There is no way you'll be able to choose between two generic lambdas at run-time, as you don't have a concrete signature to type-erase.

If you can make the decision at compile-time, you can templatize the class itself:

```<code>template <typename F>
class SomeClass
{
private:
    F fooCall;

public:
    SomeClass(F&& f) : fooCall{std::move(f)} { }
};
</code>```

You can then create an helper function to deduce F:

```<code>auto makeSomeClassImpl(std::true_type)
{
    auto l = [](auto a){ cout << a.sayHello(); };
    return SomeClass<decltype(l)>{std::move(l)};
}

auto makeSomeClassImpl(std::false_type)
{
    auto l = [](auto b){ cout << b.sayHello(); };
    return SomeClass<decltype(l)>{std::move(l)};
}

template <bool B>
auto makeSomeClass()
{
    return makeSomeClassImpl(std::bool_constant<B>{});
}
</code>```

Body:
Consider this pseudo-snippet:

class SomeClass
{
public:
    SomeClass()
    {
        if(true)
        {
            fooCall = [](auto a){ cout << a.sayHello(); };
        }
        else
        {
            fooCall = [](auto b){ cout << b.sayHello(); };
        }
    }
private:
    template<typename T>
    std::function<void(T)> fooCall;
};

What I want is a class member fooCall which stores a generic lambda, which in turn is assigned in the constructor.

The compiler complains that fooCall cannot be a templated data member.

Is there any simple solution on how i can store generic lambdas in a class?

Body:
There is no way you'll be able to choose between two generic lambdas at run-time, as you don't have a concrete signature to type-erase.

If you can make the decision at compile-time, you can templatize the class itself:

template <typename F>
class SomeClass
{
private:
    F fooCall;

public:
    SomeClass(F&& f) : fooCall{std::move(f)} { }
};

You can then create an helper function to deduce F:

auto makeSomeClassImpl(std::true_type)
{
    auto l = [](auto a){ cout << a.sayHello(); };
    return SomeClass<decltype(l)>{std::move(l)};
}

auto makeSomeClassImpl(std::false_type)
{
    auto l = [](auto b){ cout << b.sayHello(); };
    return SomeClass<decltype(l)>{std::move(l)};
}

template <bool B>
auto makeSomeClass()
{
    return makeSomeClassImpl(std::bool_constant<B>{});
}


问:
Menu loop in 2 different methods Java program
I am working on a menu program and I want to be able to enter as many selections as I want without the menu looping as well after the input, currently it either infinite-loops, or the program ends after one input, being unable to perform a different selection after the first. Also I want to have a case where I exit the menu if I press 0.</p>

```<code>public void showMenu() {

    System.out.println("Welcome!");
    System.out.println("Select an option:\n" +
            "1. Adunare\n" +
            "2. Scadere\n" +
            "3. Inmultire\n" +
            "4. Impartire\n" +
            "5. Comparare numere\n" +
            "6. List To Hundred\n" +
            "7. Nr to list\n" +
            "8. Contains\n" +
            "9. Even numbers\n" +
            "10. List of Strings\n" +
            "11. Second largest number\n" +
            "12. Second lowest number\n" +
            "13. Number \n" +
            "14. Number 2 \n" +
            "15. Number 3\n" +
            "16. String\n" +
            "17. String 2\n" +
            "18. Amount of snow\n" +
            "19. Eligible to vote test\n" +
            "20. Odd or even\n" +
            "21. Dog\n" +
            "22. Cat\n" +
            "23. Elev");

}

public void runProgram() {
    showMenu();
    int numberFromUser = citire.readNumbers();

    do {
        switch (numberFromUser) {
            case 1:
                addition();
                break;
            case 2:
                subtraction();
                break;
            case 3:
                multiply();
                break;
            case 4:
                divide();
                break;
            case 5:
                comparareNumere();
                break;
            case 6:
                listhundred();
                break;
            case 7:
                setnumbertolist();
                break;
            case 8:
                contain();
                break;
            case 9:
                limit();
                break;
            case 10:
                list();
                break;
            case 11:
                secmax();
                break;
            case 12:
                secmin();
                break;
            case 13:
                nr();
                break;
            case 14:
                nr2();
                break;
            case 15:
                nr3();
                break;
            case 16:
                string();
                break;
            case 17:
                string2();
                break;
            case 18:
                weather();
                break;
            case 19:
                eligible();
                break;
            case 20:
                oddoreven();
                break;
            case 21:
                dog();
                break;
            case 22:
                cat();
                break;
            case 23:
                elev();
                break;
            default:
                break;

        }
    } while (numberFromUser != 0);
}
</code>```

答:
Try changing runProgram to following :

```<code>public void runProgram()
{
int numberFromUser;
showMenu();
while(true)
{
System.out.print("Enter choice: ");
numberFromUser = citire.readNumbers();
switch(NumberFromUser)
{
   // All your case statements
 case 0: System.exit(0);
}
}
}
</code>```

Body:
I am working on a menu program and I want to be able to enter as many selections as I want without the menu looping as well after the input, currently it either infinite-loops, or the program ends after one input, being unable to perform a different selection after the first. Also I want to have a case where I exit the menu if I press 0.

public void showMenu() {

    System.out.println("Welcome!");
    System.out.println("Select an option:\n" +
            "1. Adunare\n" +
            "2. Scadere\n" +
            "3. Inmultire\n" +
            "4. Impartire\n" +
            "5. Comparare numere\n" +
            "6. List To Hundred\n" +
            "7. Nr to list\n" +
            "8. Contains\n" +
            "9. Even numbers\n" +
            "10. List of Strings\n" +
            "11. Second largest number\n" +
            "12. Second lowest number\n" +
            "13. Number \n" +
            "14. Number 2 \n" +
            "15. Number 3\n" +
            "16. String\n" +
            "17. String 2\n" +
            "18. Amount of snow\n" +
            "19. Eligible to vote test\n" +
            "20. Odd or even\n" +
            "21. Dog\n" +
            "22. Cat\n" +
            "23. Elev");

}

public void runProgram() {
    showMenu();
    int numberFromUser = citire.readNumbers();

    do {
        switch (numberFromUser) {
            case 1:
                addition();
                break;
            case 2:
                subtraction();
                break;
            case 3:
                multiply();
                break;
            case 4:
                divide();
                break;
            case 5:
                comparareNumere();
                break;
            case 6:
                listhundred();
                break;
            case 7:
                setnumbertolist();
                break;
            case 8:
                contain();
                break;
            case 9:
                limit();
                break;
            case 10:
                list();
                break;
            case 11:
                secmax();
                break;
            case 12:
                secmin();
                break;
            case 13:
                nr();
                break;
            case 14:
                nr2();
                break;
            case 15:
                nr3();
                break;
            case 16:
                string();
                break;
            case 17:
                string2();
                break;
            case 18:
                weather();
                break;
            case 19:
                eligible();
                break;
            case 20:
                oddoreven();
                break;
            case 21:
                dog();
                break;
            case 22:
                cat();
                break;
            case 23:
                elev();
                break;
            default:
                break;

        }
    } while (numberFromUser != 0);
}

Body:
Try changing runProgram to following :

public void runProgram()
{
int numberFromUser;
showMenu();
while(true)
{
System.out.print("Enter choice: ");
numberFromUser = citire.readNumbers();
switch(NumberFromUser)
{
   // All your case statements
 case 0: System.exit(0);
}
}
}


问:
How to do scp in R?
I was wondering whether scp like:

```<code>scp localmachine/path_to_the_file username@server_ip:/path_to_remote_directory
</code>```

is possible using R code? In other words, for copy a file in local machine in R, one could use file.copy, what are the R possibilities to copy file from local machine to a remote machine?

答:
there is package ssh.utils which wraps ssh commands in R functions.

So your example would become:

```<code>library(ssh.utils)
cp.remote(remote.src = "",
          remote.dest = "username@server_ip",
          path.src = "localmachine/path_to_the_file",
          path.dest = "path_to_remote_directory")
</code>```

EDIT: I could install it  but anyway it's not very flexible as it does not accept options...

With a system command this would be just:

```<code>system("scp localmachine/path_to_the_file username@server_ip:/path_to_remote_directory")
</code>```

Title: How to do scp in R?

Body:
I was wondering whether scp like:

scp localmachine/path_to_the_file username@server_ip:/path_to_remote_directory

is possible using R code? In other words, for copy a file in local machine in R, one could use file.copy, what are the R possibilities to copy file from local machine to a remote machine?

Body:
there is package ssh.utils which wraps ssh commands in R functions.

So your example would become:

library(ssh.utils)
cp.remote(remote.src = "",
          remote.dest = "username@server_ip",
          path.src = "localmachine/path_to_the_file",
          path.dest = "path_to_remote_directory")

EDIT: I could install it  but anyway it's not very flexible as it does not accept options...

With a system command this would be just:

system("scp localmachine/path_to_the_file username@server_ip:/path_to_remote_directory")


问:
asp.net reading asp:textbox values located in modal part after submit
I have modal div in asp.net page. This form has textboxes which I should check before submit. I do not see  the values inside btnReportModal_Click.

Can anyone help?

========= my aspx page ========================================

```<code><div id="modalpopup" style="display: none;">
        <div class="row">
                <div class="input-group">
                    <span class="input-group-addon">Qty 1</span>
                    <asp:TextBox ID="txtQty1" runat="server"></asp:TextBox>
                </div>
                <div class="input-group">
                    <span class="input-group-addon">Qty 2</span>
                    <asp:TextBox ID="txtQty2" runat="server"></asp:TextBox>
                </div>
        </div>
</div>
<asp:Button runat="server" ID="btnReportModal" class="hidden" Text="" OnClick="btnReportModal_Click" />
</code>```

========= script =============================

```<code>function ShowPopup(param) {
    $(function () {
        $("#modalpopup").dialog({
                modal: true,
                buttons: {
                    "Submit": function () {
                        $("[id*=btnReportModal]").click();
                    },

                    "Close": function () {
                        $("#modalpopup").dialog('close');
                    }
                },
                close: function (event, ui) {
                    __doPostBack(this.name, '');
                }
            });
        $("#modalpopup").dialog('open');
    });
};
</code>```

======== code behind ================

```<code>Protected Sub btnReportModal_Click(sender As Object, e As EventArgs) Handles btnReportModal.Click
       dim txt as string  = txtQty1.Text
       'txtQty1.Text  - >> I see empty
End Sub
</code>```

答:
Anton. I have to leave it inside form because i am giving default values to textbox(es) before open  modal. I have got this working using $("#modalpopup").dialog({... }).parent().appendTo("form");
Thank you</p>

Body:
I have modal div in asp.net page. This form has textboxes which I should check before submit. I do not see  the values inside btnReportModal_Click.

Can anyone help?

========= my aspx page ========================================

                    Qty 1
                    <asp:TextBox ID="txtQty1" runat="server"></asp:TextBox>

                    Qty 2
                    <asp:TextBox ID="txtQty2" runat="server"></asp:TextBox>

<asp:Button runat="server" ID="btnReportModal" class="hidden" Text="" OnClick="btnReportModal_Click" />

========= script =============================

function ShowPopup(param) {
    $(function () {
        $("#modalpopup").dialog({
                modal: true,
                buttons: {
                    "Submit": function () {
                        $("[id*=btnReportModal]").click();
                    },

                    "Close": function () {
                        $("#modalpopup").dialog('close');
                    }
                },
                close: function (event, ui) {
                    __doPostBack(this.name, '');
                }
            });
        $("#modalpopup").dialog('open');
    });
};

======== code behind ================

Protected Sub btnReportModal_Click(sender As Object, e As EventArgs) Handles btnReportModal.Click
       dim txt as string  = txtQty1.Text
       'txtQty1.Text  - >> I see empty
End Sub


问:
Map just ONE object to another (DTO) with Java8
can you tell me if exist some pretty way to map one entity object to another dto object? When I needed convert List<ObjEntity> to List<ObjDTO> I created that function:

```<code>public class Converter {
public static Function<ObjEntity, ObjDTO> MYOBJ_ENTITY_TO_DTO = objEntity -> {
    ObjDTO dto = new ObjDTO();

    dto.setId(objEntity.getId());
    dto.setName(objEntity.getName());
    dto.setNote(objEntity.getNote());
    // ...

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

and I use it like this:

```<code>List<ObjDTO> dtos =  objEntitiesList.stream().map(Converter.MYOBJ_ENTITY_TO_DTO).collect(Collectors.toList());
</code>```

But what if I need convert just ONE object? Should I use that function MYOBJ_ENTITY_TO_DTO for that and how? Or what is the best practice? Yes, I can do classical function in Converter class like that:

```<code>public static ObjEntity dtoToEntity(ObjDTO dto) {
   // map here entity to dto and return entity
}
</code>```

but it is old style. Exist some new practice in java 8? Something similar like my example for list by lambda?

答:
```<code>ObjDTO dto = MYOBJ_ENTITY_TO_DTO.apply(entity);
</code>```

I see the other way around more often: instead of MYOBJ_ENTITY_TO_DTO, define entityToDto as a method and use

```<code>List<ObjDTO> dtos =  objEntitiesList.stream().map(Converter::entityToDto).collect(Collectors.toList());
</code>```

for lists.

Body:
can you tell me if exist some pretty way to map one entity object to another dto object? When I needed convert List<ObjEntity> to List<ObjDTO> I created that function:

public class Converter {
public static Function<ObjEntity, ObjDTO> MYOBJ_ENTITY_TO_DTO = objEntity -> {
    ObjDTO dto = new ObjDTO();

    dto.setId(objEntity.getId());
    dto.setName(objEntity.getName());
    dto.setNote(objEntity.getNote());
    // ...

    return dto;
    };
}

and I use it like this:

List<ObjDTO> dtos =  objEntitiesList.stream().map(Converter.MYOBJ_ENTITY_TO_DTO).collect(Collectors.toList());

But what if I need convert just ONE object? Should I use that function MYOBJ_ENTITY_TO_DTO for that and how? Or what is the best practice? Yes, I can do classical function in Converter class like that:

public static ObjEntity dtoToEntity(ObjDTO dto) {
   // map here entity to dto and return entity
}

but it is old style. Exist some new practice in java 8? Something similar like my example for list by lambda?

Body:
ObjDTO dto = MYOBJ_ENTITY_TO_DTO.apply(entity);

I see the other way around more often: instead of MYOBJ_ENTITY_TO_DTO, define entityToDto as a method and use

List<ObjDTO> dtos =  objEntitiesList.stream().map(Converter::entityToDto).collect(Collectors.toList());

for lists.


问:
How to upgrade postgres 9.5 with non default data directory and checksum enabled to 10.1?
I am trying to upgrade postgres 9.5.4 to 10.1 on Ubuntu 14. The data directory for 9.5.4 is /var/lib/postgresql/data/postgresql0

The steps that I have followed

Install postgres 10.1

```<code>ubuntu@van-platform:~/build-target/launcher$sudo add-apt-repository "deb http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg main"
ubuntu@van-platform:~/build-target/launcher$wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
ubuntu@van-platform:~/build-target/launcher$ OK
ubuntu@van-platform:~/build-target/launcher$sudo apt-get update
...
ubuntu@van-platform:~/build-target/launcher$sudo apt-get install postgresql-10
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
  comerr-dev krb5-multidev libgssrpc4 libkadm5clnt-mit9 libkadm5srv-mit9
  libkdb5-7
Use 'apt-get autoremove' to remove them.
The following extra packages will be installed:
  libpq-dev libpq5 postgresql-client-10 postgresql-client-common
  postgresql-common
Suggested packages:
  postgresql-doc-10 locales-all
The following NEW packages will be installed:
  postgresql-10 postgresql-client-10
The following packages will be upgraded:
  libpq-dev libpq5 postgresql-client-common postgresql-common
4 upgraded, 2 newly installed, 0 to remove and 14 not upgraded.
Need to get 6,595 kB of archives.
After this operation, 26.7 MB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Get:1 http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg/main libpq-dev amd64 10.1-1.pgdg14.04+1 [241 kB]
Get:2 http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg/main libpq5 amd64 10.1-1.pgdg14.04+1 [157 kB]
Get:3 http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg/main postgresql-common all 188.pgdg14.04+1 [220 kB]
Get:4 http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg/main postgresql-client-common all 188.pgdg14.04+1 [81.5 kB]
Get:5 http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg/main postgresql-client-10 amd64 10.1-1.pgdg14.04+1 [1,282 kB]
Get:6 http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg/main postgresql-10 amd64 10.1-1.pgdg14.04+1 [4,613 kB]
Fetched 6,595 kB in 4s (1,473 kB/s)
Preconfiguring packages ...
(Reading database ... 102799 files and directories currently installed.)
Preparing to unpack .../libpq-dev_10.1-1.pgdg14.04+1_amd64.deb ...
Unpacking libpq-dev (10.1-1.pgdg14.04+1) over (9.5.4-1.pgdg14.04+1) ...
Preparing to unpack .../libpq5_10.1-1.pgdg14.04+1_amd64.deb ...
Unpacking libpq5:amd64 (10.1-1.pgdg14.04+1) over (9.5.4-1.pgdg14.04+1) ...
Preparing to unpack .../postgresql-common_188.pgdg14.04+1_all.deb ...
Leaving 'diversion of /usr/bin/pg_config to /usr/bin/pg_config.libpq-dev by postgresql-common'
Unpacking postgresql-common (188.pgdg14.04+1) over (175.pgdg14.04+1) ...
Preparing to unpack .../postgresql-client-common_188.pgdg14.04+1_all.deb ...
Unpacking postgresql-client-common (188.pgdg14.04+1) over (175.pgdg14.04+1) ...
Selecting previously unselected package postgresql-client-10.
Preparing to unpack .../postgresql-client-10_10.1-1.pgdg14.04+1_amd64.deb ...
Unpacking postgresql-client-10 (10.1-1.pgdg14.04+1) ...
Selecting previously unselected package postgresql-10.
Preparing to unpack .../postgresql-10_10.1-1.pgdg14.04+1_amd64.deb ...
Unpacking postgresql-10 (10.1-1.pgdg14.04+1) ...
Processing triggers for man-db (2.6.7.1-1ubuntu1) ...
Processing triggers for ureadahead (0.100.0-16) ...
Setting up libpq5:amd64 (10.1-1.pgdg14.04+1) ...
Setting up libpq-dev (10.1-1.pgdg14.04+1) ...
Setting up postgresql-client-common (188.pgdg14.04+1) ...
Installing new version of config file /etc/postgresql-common/user_clusters ...
Setting up postgresql-common (188.pgdg14.04+1) ...

Configuration file '/etc/logrotate.d/postgresql-common'
 ==> File on system created by you or by a script.
 ==> File also in package provided by package maintainer.
   What would you like to do about it ?  Your options are:
    Y or I  : install the package maintainer's version
    N or O  : keep your currently-installed version
      D     : show the differences between the versions
      Z     : start a shell to examine the situation
 The default action is to keep your current version.
*** postgresql-common (Y/I/N/O/D/Z) [default=N] ? Y
Installing new version of config file /etc/logrotate.d/postgresql-common ...
Replacing config file /etc/postgresql-common/createcluster.conf with new version
 * Starting PostgreSQL 9.5 database server                               [ OK ]
Setting up postgresql-client-10 (10.1-1.pgdg14.04+1) ...
Setting up postgresql-10 (10.1-1.pgdg14.04+1) ...
Creating new PostgreSQL cluster 10/main ...
/usr/lib/postgresql/10/bin/initdb -D /var/lib/postgresql/10/main --auth-local peer --auth-host md5
The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.

The database cluster will be initialized with locale "en_US.UTF-8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".

Data page checksums are disabled.

fixing permissions on existing directory /var/lib/postgresql/10/main ... ok
creating subdirectories ... ok
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting dynamic shared memory implementation ... posix
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok

Success. You can now start the database server using:

    /usr/lib/postgresql/10/bin/pg_ctl -D /var/lib/postgresql/10/main -l logfile start

Ver Cluster Port Status Owner    Data directory              Log file
10  main    5433 down   postgres /var/lib/postgresql/10/main /var/log/postgresql/postgresql-10-main.log
 * Starting PostgreSQL 10 database server                                [ OK ]
Processing triggers for libc-bin (2.19-0ubuntu6.13) ...
</code>```

Create the new data directory

```<code>support@vrni-platform:~$ sudo -H -u postgres mkdir -p /var/lib/postgresql/10/data/postgresql0
</code>```

Stop postgres

```<code>ubuntu@vrni-platform:~/build-target/launcher$ sudo service postgresql stop
     * Stopping PostgreSQL 10 database server                                [ OK ]
     * Stopping PostgreSQL 9.5 database server                               [ OK ]
</code>```

Enable Checksum

```<code>support@vrni-platform:/tmp$ sudo -H -u postgres /usr/lib/postgresql/10/bin/pg_ctl -D /var/lib/postgresql/10/data/postgresql0 initdb -o '--data-checksums'
The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.

The database cluster will be initialized with locale "en_US.UTF-8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".

Data page checksums are enabled.

fixing permissions on existing directory /var/lib/postgresql/10/data/postgresql0 ... ok
creating subdirectories ... ok
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting dynamic shared memory implementation ... posix
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok

WARNING: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the option -A, or
--auth-local and --auth-host, the next time you run initdb.

Success. You can now start the database server using:

    /usr/lib/postgresql/10/bin/pg_ctl -D /var/lib/postgresql/10/data/postgresql0 -l logfile start
</code>```

On trying to check for upgrade viability with the below command

```<code>sudo -H -u postgres /usr/lib/postgresql/10/bin/pg_upgrade \
   -b /usr/lib/postgresql/9.5/bin \
   -B /usr/lib/postgresql/10/bin \
   -d /var/lib/postgresql/data/postgresql0 \
   -D /var/lib/postgresql/10/data/postgresql0 \
   -o ' -c config_file=/etc/postgresql/9.5/main/postgresql.conf' \
   -O ' -c config_file=/etc/postgresql/10/main/postgresql.conf' --check
</code>```

It is failing with the below error in pg_upgrade_server.log

```<code>command: "/usr/lib/postgresql/9.5/bin/pg_ctl" -w -l "pg_upgrade_server.log" -D "/var/lib/postgresql/data/postgresql0" -o "-p 50432 -b  -c config_file=/etc/postgresql/9.5/main/postgresql.conf -c listen_addresses='' -c unix_socket_permissions=0700 -c unix_socket_directories='/tmp'" start >> "pg_upgrade_server.log" 2>&1
waiting for server to start....2017-11-14 15:27:31 UTC [16239-1] LOG:  database system was shut down at 2017-11-14 15:16:43 UTC
2017-11-14 15:27:31 UTC [16239-2] LOG:  MultiXact member wraparound protections are now enabled
2017-11-14 15:27:31 UTC [16238-1] LOG:  database system is ready to accept connections
........................................................... stopped waiting
pg_ctl: could not start server
</code>```

Can someone let me know what I am doing wrong and how can I get around this error?

答:
As answered here

Changing data_directory in postgres.conf for both 9.5 & 10 solved the issue

```<code>postgres@me:~$ grep data_dir /etc/postgresql/*/main/postgresql.conf
/etc/postgresql/10/main/postgresql.conf:data_directory = '/var/lib/postgresql/10/data/postgresql0'      # use data in another directory
/etc/postgresql/9.5/main/postgresql.conf:data_directory = '/var/lib/postgresql/data/postgresql0'        # use data in another directory
</code>```

Body:
I am trying to upgrade postgres 9.5.4 to 10.1 on Ubuntu 14. The data directory for 9.5.4 is /var/lib/postgresql/data/postgresql0

The steps that I have followed

Install postgres 10.1

ubuntu@van-platform:~/build-target/launcher$sudo add-apt-repository "deb http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg main"
ubuntu@van-platform:~/build-target/launcher$wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
ubuntu@van-platform:~/build-target/launcher$ OK
ubuntu@van-platform:~/build-target/launcher$sudo apt-get update
...
ubuntu@van-platform:~/build-target/launcher$sudo apt-get install postgresql-10
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
  comerr-dev krb5-multidev libgssrpc4 libkadm5clnt-mit9 libkadm5srv-mit9
  libkdb5-7
Use 'apt-get autoremove' to remove them.
The following extra packages will be installed:
  libpq-dev libpq5 postgresql-client-10 postgresql-client-common
  postgresql-common
Suggested packages:
  postgresql-doc-10 locales-all
The following NEW packages will be installed:
  postgresql-10 postgresql-client-10
The following packages will be upgraded:
  libpq-dev libpq5 postgresql-client-common postgresql-common
4 upgraded, 2 newly installed, 0 to remove and 14 not upgraded.
Need to get 6,595 kB of archives.
After this operation, 26.7 MB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Get:1 http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg/main libpq-dev amd64 10.1-1.pgdg14.04+1 [241 kB]
Get:2 http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg/main libpq5 amd64 10.1-1.pgdg14.04+1 [157 kB]
Get:3 http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg/main postgresql-common all 188.pgdg14.04+1 [220 kB]
Get:4 http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg/main postgresql-client-common all 188.pgdg14.04+1 [81.5 kB]
Get:5 http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg/main postgresql-client-10 amd64 10.1-1.pgdg14.04+1 [1,282 kB]
Get:6 http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg/main postgresql-10 amd64 10.1-1.pgdg14.04+1 [4,613 kB]
Fetched 6,595 kB in 4s (1,473 kB/s)
Preconfiguring packages ...
(Reading database ... 102799 files and directories currently installed.)
Preparing to unpack .../libpq-dev_10.1-1.pgdg14.04+1_amd64.deb ...
Unpacking libpq-dev (10.1-1.pgdg14.04+1) over (9.5.4-1.pgdg14.04+1) ...
Preparing to unpack .../libpq5_10.1-1.pgdg14.04+1_amd64.deb ...
Unpacking libpq5:amd64 (10.1-1.pgdg14.04+1) over (9.5.4-1.pgdg14.04+1) ...
Preparing to unpack .../postgresql-common_188.pgdg14.04+1_all.deb ...
Leaving 'diversion of /usr/bin/pg_config to /usr/bin/pg_config.libpq-dev by postgresql-common'
Unpacking postgresql-common (188.pgdg14.04+1) over (175.pgdg14.04+1) ...
Preparing to unpack .../postgresql-client-common_188.pgdg14.04+1_all.deb ...
Unpacking postgresql-client-common (188.pgdg14.04+1) over (175.pgdg14.04+1) ...
Selecting previously unselected package postgresql-client-10.
Preparing to unpack .../postgresql-client-10_10.1-1.pgdg14.04+1_amd64.deb ...
Unpacking postgresql-client-10 (10.1-1.pgdg14.04+1) ...
Selecting previously unselected package postgresql-10.
Preparing to unpack .../postgresql-10_10.1-1.pgdg14.04+1_amd64.deb ...
Unpacking postgresql-10 (10.1-1.pgdg14.04+1) ...
Processing triggers for man-db (2.6.7.1-1ubuntu1) ...
Processing triggers for ureadahead (0.100.0-16) ...
Setting up libpq5:amd64 (10.1-1.pgdg14.04+1) ...
Setting up libpq-dev (10.1-1.pgdg14.04+1) ...
Setting up postgresql-client-common (188.pgdg14.04+1) ...
Installing new version of config file /etc/postgresql-common/user_clusters ...
Setting up postgresql-common (188.pgdg14.04+1) ...

Configuration file '/etc/logrotate.d/postgresql-common'
 ==> File on system created by you or by a script.
 ==> File also in package provided by package maintainer.
   What would you like to do about it ?  Your options are:
    Y or I  : install the package maintainer's version
    N or O  : keep your currently-installed version
      D     : show the differences between the versions
      Z     : start a shell to examine the situation
 The default action is to keep your current version.
*** postgresql-common (Y/I/N/O/D/Z) [default=N] ? Y
Installing new version of config file /etc/logrotate.d/postgresql-common ...
Replacing config file /etc/postgresql-common/createcluster.conf with new version
 * Starting PostgreSQL 9.5 database server                               [ OK ]
Setting up postgresql-client-10 (10.1-1.pgdg14.04+1) ...
Setting up postgresql-10 (10.1-1.pgdg14.04+1) ...
Creating new PostgreSQL cluster 10/main ...
/usr/lib/postgresql/10/bin/initdb -D /var/lib/postgresql/10/main --auth-local peer --auth-host md5
The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.

The database cluster will be initialized with locale "en_US.UTF-8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".

Data page checksums are disabled.

fixing permissions on existing directory /var/lib/postgresql/10/main ... ok
creating subdirectories ... ok
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting dynamic shared memory implementation ... posix
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok

Success. You can now start the database server using:

    /usr/lib/postgresql/10/bin/pg_ctl -D /var/lib/postgresql/10/main -l logfile start

Ver Cluster Port Status Owner    Data directory              Log file
10  main    5433 down   postgres /var/lib/postgresql/10/main /var/log/postgresql/postgresql-10-main.log
 * Starting PostgreSQL 10 database server                                [ OK ]
Processing triggers for libc-bin (2.19-0ubuntu6.13) ...

Create the new data directory

support@vrni-platform:~$ sudo -H -u postgres mkdir -p /var/lib/postgresql/10/data/postgresql0

Stop postgres

ubuntu@vrni-platform:~/build-target/launcher$ sudo service postgresql stop
     * Stopping PostgreSQL 10 database server                                [ OK ]
     * Stopping PostgreSQL 9.5 database server                               [ OK ]

Enable Checksum

support@vrni-platform:/tmp$ sudo -H -u postgres /usr/lib/postgresql/10/bin/pg_ctl -D /var/lib/postgresql/10/data/postgresql0 initdb -o '--data-checksums'
The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.

The database cluster will be initialized with locale "en_US.UTF-8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".

Data page checksums are enabled.

fixing permissions on existing directory /var/lib/postgresql/10/data/postgresql0 ... ok
creating subdirectories ... ok
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting dynamic shared memory implementation ... posix
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok

WARNING: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the option -A, or
--auth-local and --auth-host, the next time you run initdb.

Success. You can now start the database server using:

    /usr/lib/postgresql/10/bin/pg_ctl -D /var/lib/postgresql/10/data/postgresql0 -l logfile start

On trying to check for upgrade viability with the below command

sudo -H -u postgres /usr/lib/postgresql/10/bin/pg_upgrade \
   -b /usr/lib/postgresql/9.5/bin \
   -B /usr/lib/postgresql/10/bin \
   -d /var/lib/postgresql/data/postgresql0 \
   -D /var/lib/postgresql/10/data/postgresql0 \
   -o ' -c config_file=/etc/postgresql/9.5/main/postgresql.conf' \
   -O ' -c config_file=/etc/postgresql/10/main/postgresql.conf' --check

It is failing with the below error in pg_upgrade_server.log

command: "/usr/lib/postgresql/9.5/bin/pg_ctl" -w -l "pg_upgrade_server.log" -D "/var/lib/postgresql/data/postgresql0" -o "-p 50432 -b  -c config_file=/etc/postgresql/9.5/main/postgresql.conf -c listen_addresses='' -c unix_socket_permissions=0700 -c unix_socket_directories='/tmp'" start >> "pg_upgrade_server.log" 2>&1
waiting for server to start....2017-11-14 15:27:31 UTC [16239-1] LOG:  database system was shut down at 2017-11-14 15:16:43 UTC
2017-11-14 15:27:31 UTC [16239-2] LOG:  MultiXact member wraparound protections are now enabled
2017-11-14 15:27:31 UTC [16238-1] LOG:  database system is ready to accept connections
........................................................... stopped waiting
pg_ctl: could not start server

Can someone let me know what I am doing wrong and how can I get around this error?

Body:
As answered here

Changing data_directory in postgres.conf for both 9.5 & 10 solved the issue

postgres@me:~$ grep data_dir /etc/postgresql/*/main/postgresql.conf
/etc/postgresql/10/main/postgresql.conf:data_directory = '/var/lib/postgresql/10/data/postgresql0'      # use data in another directory
/etc/postgresql/9.5/main/postgresql.conf:data_directory = '/var/lib/postgresql/data/postgresql0'        # use data in another directory


问:
Is gulp made for fast deployment to remote server using the "dist" directory
I have started to learn Gulp.
It is nice, and now I have a dist folder, which is probably useless if I do not have a straight-forward method to put it on server.

Is there a way that Gulp will handle it for me, taking in concern to upload ONLY those files that modified or newly created? (In order to save upload time, sure).

I am working with Node.js.

Thanks.

答:
how do you normally deploy to production? If you use ftp - there is a gulp function for that. If you use AWS S3 - there is a function for that. If you use something like docker or AWS EB, then you will continue to deploy through git etc - there is also likely to be a gulp function for this. Gulp is just a tool to process files and make build/deployment tasks easier.

Pulled straight from gulp website:

gulp is a toolkit for automating painful or time-consuming tasks in your development workflow, so you can stop messing around and build something.


问:
Scala liftweb framework
I have two checkboxes and on submit I want the user to download two different  files, how do I go about this? I need help as am not able to get any online material on this. I am new to this framework.

This is what I've tried so far

```<code>def render = {
 def onSubmit1() : LiftResponse = {
       val userInput1 = S.param("getit").openOr("")
      val userInput2 = S.param("getit2").openOr("")
      val checkbox1 = S.param("yes").openOr("")
      val checkbox2  = S.param("yes").openOr("")
val fileToDownload = funFile(as, art, top)
       val fileName = "My File"
 if (fileToDownload.equals()) {
         return S.redirectTo("/Somewhere")
       } else {
         InMemoryResponse(
          fileToDownload.mkString("\n").getBytes("UTF-8"),
            "Content-Type" -> "text/plain; charset=utf8" ::
             "Content-Disposition" -> s"attachment; filename=$fileName" :: Nil,
           cookies = Nil, code = 200)
       }
"#submitButton" #> SHtml.onSubmitUnit(onSubmit1)
</code>```

答:
I found a way to do that and that is to zip the two files using this function
How do I archive multiple files into a .zip file using scala? , </p>

```<code>if (checkbox1.getOrElse("") == "checked" && checkbox2.getOrElse("") == "checked") {
val checkboxIterable1: Iterable[String] = filegetter1
        val checkboxFile1 = new File("checkboxFile1.csv")
        using(new FileWriter(checkboxFile1))(writer =>
          fileGetter1.foreach { d =>
            writer.write(d)
          })
       fileGetter1

        val checkboxIterable2: Iterable[String] = fileGetter2
        val checkboxFile2 = new File("checkboxFile2.csv")
        using(new FileWriter(checkboxFile2))(writer =>
          fileGetter2.foreach { d =>
            writer.write(d)
          })
        fileGetter2

        val zipFile = zip("Zipped file", List("checkboxFile1.csv", "checkboxFile2.csv"))
        val zipFileName = "Zipped file"

        val zipToBArray = new BufferedInputStream(new FileInputStream(zipFileName))
        val getByteArray = Stream.continually(zipToBArray.read).takeWhile(-1 !=).map(_.toByte).toArray

        InMemoryResponse(
          getByteArray,
          "Content-Type" -> "application/zip; charset=utf8" ::
            "Content-Disposition" -> s"attachment; filename=file.zip" :: Nil,
          cookies = Nil, code = 200)
      }
</code>```

Title: Scala liftweb framework

Body:
I have two checkboxes and on submit I want the user to download two different  files, how do I go about this? I need help as am not able to get any online material on this. I am new to this framework.

This is what I've tried so far

def render = {
 def onSubmit1() : LiftResponse = {
       val userInput1 = S.param("getit").openOr("")
      val userInput2 = S.param("getit2").openOr("")
      val checkbox1 = S.param("yes").openOr("")
      val checkbox2  = S.param("yes").openOr("")
val fileToDownload = funFile(as, art, top)
       val fileName = "My File"
 if (fileToDownload.equals()) {
         return S.redirectTo("/Somewhere")
       } else {
         InMemoryResponse(
          fileToDownload.mkString("\n").getBytes("UTF-8"),
            "Content-Type" -> "text/plain; charset=utf8" ::
             "Content-Disposition" -> s"attachment; filename=$fileName" :: Nil,
           cookies = Nil, code = 200)
       }
"#submitButton" #> SHtml.onSubmitUnit(onSubmit1)

Body:
I found a way to do that and that is to zip the two files using this function
How do I archive multiple files into a .zip file using scala? ,

if (checkbox1.getOrElse("") == "checked" && checkbox2.getOrElse("") == "checked") {
val checkboxIterable1: Iterable[String] = filegetter1
        val checkboxFile1 = new File("checkboxFile1.csv")
        using(new FileWriter(checkboxFile1))(writer =>
          fileGetter1.foreach { d =>
            writer.write(d)
          })
       fileGetter1

        val checkboxIterable2: Iterable[String] = fileGetter2
        val checkboxFile2 = new File("checkboxFile2.csv")
        using(new FileWriter(checkboxFile2))(writer =>
          fileGetter2.foreach { d =>
            writer.write(d)
          })
        fileGetter2

        val zipFile = zip("Zipped file", List("checkboxFile1.csv", "checkboxFile2.csv"))
        val zipFileName = "Zipped file"

        val zipToBArray = new BufferedInputStream(new FileInputStream(zipFileName))
        val getByteArray = Stream.continually(zipToBArray.read).takeWhile(-1 !=).map(_.toByte).toArray

        InMemoryResponse(
          getByteArray,
          "Content-Type" -> "application/zip; charset=utf8" ::
            "Content-Disposition" -> s"attachment; filename=file.zip" :: Nil,
          cookies = Nil, code = 200)
      }


问:
Got the time of day?
I'm stuck in a hole, and I cannot for the life of me dig myself out of it.

This is a highly aesthetics question, but I like to get what I ask for from my code.
I'm trying to parse a string representing time to a DateTime variable that I then send to a textBox as well as to my LINQ query.

I would like to represent my time in this format: "yyyy-MM-dd hh:mm:ss" and that is what i get from my Select query, but as soon a I try to parse what the user has written in the textBox to DateTime it gives me "1/13/2011 12:00:00 AM", even if it was in the format "2011-01-13 00:00:00".

I feel like I've tried everything to make this work, but there must be a solution, can you guys help me find it? What IFormatProvider am I suppose to use?

This is what i tried:

```<code>//textBox1.Text =   "2011-01-13 00:00:00";
DateTime = TimeFrom;
TimeFrom = DateTime.ParseExact(textBox1.Text, "yyyy-MM-dd hh:mm:ss", null);
TimeFrom = DateTime.ParseExact(textBox1.Text, CultureInfo.CurrentCulture.DateTimeFormat.GetAllDateTimePatterns(), new CultureInfo("sv-SE"), DateTimeStyles.None);
TimeFrom = DateTime.ParseExact(textBox1.Text, CultureInfo.CurrentCulture.DateTimeFormat.GetAllDateTimePatterns(), new CultureInfo("sv-SE"),System.Globalization.DateTimeStyles.AssumeUniversal);
TimeFrom = DateTime.ParseExact("2008-10-01 16:44:12.000", "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.CreateSpecificCulture("en-US"));
textBox1.Text = TimeFrom.ToString();
</code>```

But none of it gives me the formatting that I so crave.

UPDATE:

It appears that somehow the Current Culture got changed from the time I declared my DateTime variable to the time I wanted to Parse the textBox1.Text value from "sv-SE" to "en-EN" which is why it decided to change the way my time was formatted. It is not something I'm doing in my code. Any ideas as to why?

Why it decided to ignore my (IFormatProvider) new CultureInfo("sv-SE",true), is something I haven't figured out yet ether.

If you have any suggestions, please let me know.

答:
Hey guys. I just wanted to go public with what caused my problems.

What happened was that when I rendered a report and loaded it into a report viewer the CurrentCulture got changed to en-EN. The report language was set to blank which leads me to believe that the default language is en-EN.

This then changed the way that my time was represented. A DateTime variable does not remember its formatting culture. So any changes in representing a DateTime as a string has to contain the string formatting, like this: dateTimeVariable.toString("yyyy-MM-dd hh:mm:ss")

I hope someone will find this helpfull.

Title: Got the time of day?

Body:
I'm stuck in a hole, and I cannot for the life of me dig myself out of it.

This is a highly aesthetics question, but I like to get what I ask for from my code.
I'm trying to parse a string representing time to a DateTime variable that I then send to a textBox as well as to my LINQ query.

I would like to represent my time in this format: "yyyy-MM-dd hh:mm:ss" and that is what i get from my Select query, but as soon a I try to parse what the user has written in the textBox to DateTime it gives me "1/13/2011 12:00:00 AM", even if it was in the format "2011-01-13 00:00:00".

I feel like I've tried everything to make this work, but there must be a solution, can you guys help me find it? What IFormatProvider am I suppose to use?

This is what i tried:

//textBox1.Text =   "2011-01-13 00:00:00";
DateTime = TimeFrom;
TimeFrom = DateTime.ParseExact(textBox1.Text, "yyyy-MM-dd hh:mm:ss", null);
TimeFrom = DateTime.ParseExact(textBox1.Text, CultureInfo.CurrentCulture.DateTimeFormat.GetAllDateTimePatterns(), new CultureInfo("sv-SE"), DateTimeStyles.None);
TimeFrom = DateTime.ParseExact(textBox1.Text, CultureInfo.CurrentCulture.DateTimeFormat.GetAllDateTimePatterns(), new CultureInfo("sv-SE"),System.Globalization.DateTimeStyles.AssumeUniversal);
TimeFrom = DateTime.ParseExact("2008-10-01 16:44:12.000", "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.CreateSpecificCulture("en-US"));
textBox1.Text = TimeFrom.ToString();

But none of it gives me the formatting that I so crave.

UPDATE:

It appears that somehow the Current Culture got changed from the time I declared my DateTime variable to the time I wanted to Parse the textBox1.Text value from "sv-SE" to "en-EN" which is why it decided to change the way my time was formatted. It is not something I'm doing in my code. Any ideas as to why?

Why it decided to ignore my (IFormatProvider) new CultureInfo("sv-SE",true), is something I haven't figured out yet ether.

If you have any suggestions, please let me know.

ContentLicense: CC BY-SA 2.5


答:
Newer versions of MySQL (5.7.6) (and MariaDB in 5.2 with VIRTUAL columns) have "Generated" columns.  You would create such as (col5+col6), then index this fake column.  Such a column can be STORED in the table our could be VIRTUAL.  Read the docs to get the details.

```<code>col56 GENERATED ALWAYS AS (col5 + col6) VIRTUAL  -- or STORED
</code>```

Title: MySQL create index sum of two columns data in one table

Body:
 >> table1
 -------------------------------------------------------------
 | column1 | column2 | column3 | column4 | column5 | column6 |
 +---------+---------+---------+---------+---------+---------+
 |  data1  |  data2  |  data3  |  data4  |  data5  |  data6  |
 +---------+---------+---------+---------+---------+---------+
 |  data7  |  data8  |  data9  |  data10 |  data11 |  data12 |
 +---------+---------+---------+---------+---------+---------+
                               .
                               .
                               .
 +---------+---------+---------+---------+---------+---------+
 |  data   |  data   |  data   |  data   |  data   |  data   |
 -------------------------------------------------------------

 >> query
 SELECT * FROM table1
     WHERE (column5 + column6) >= 6;

How do I create an index for this query in MySQL?

Body:
Newer versions of MySQL (5.7.6) (and MariaDB in 5.2 with VIRTUAL columns) have "Generated" columns.  You would create such as (col5+col6), then index this fake column.  Such a column can be STORED in the table our could be VIRTUAL.  Read the docs to get the details.

col56 GENERATED ALWAYS AS (col5 + col6) VIRTUAL  -- or STORED