问:
What's the main purpose of update()? Why can't my code work without update()?
The code slowly generates columns of randomly selected numbers 1 and 0 on a 1920x1080 canvas

```<code>def matrix():
    c.configure(bg="black")
    numbers=[0,1]
    for i in range(100):
        for j in range(50):
            c.create_text(i*20,j*20,text=random.choice(numbers),fill="green")
            c.after(50)
            c.update() # <code>\<</code>------
matrix()
</code>```

What's the main purpose of update()? Why can't my code work without update()?

I've had a look around but couldn't really understand. You could say I'm stupid.

答:
Your code does work without calling update. It's just that you can't see it working because you don't let tkinter refresh the window.

In order for tkinter (or any GUI toolkit) to function, it must be able to respond to a steady stream of events. Things like button clicks, typing, resizing a window, or drawing to a canvas, all cause events to be added to a queue.

Normally these events are processed by the event loop, which is what mainloop is. It is a loop that simply waits for events to arrive, and then it handles them.

Because tkinter is single-threaded, it can only do one thing at a time. Thus, as long as your code is doing something (eg: your for loop), it is unable to process events. If it can't process events, any changes to the UI (such as drawing on the canvas) won't be visible.

When you call update, you are requesting that tkinter process all pending events that are stuck in the event queue. Note that this processes all events in the queue, so if you clicked in a button, that click will get processed too. This can result in a deeply nested set of calls to update if each time you call, it processes an event that causes it to be called again.

Since what you want is not to process all events, but rather just events related to refreshing the display, you can instead call update_idletasks which only processes "idle" events. "idle" events are events that tkitner processes when it is otherwise idle. One such event is the request to refresh the display.

Body:
The code slowly generates columns of randomly selected numbers 1 and 0 on a 1920x1080 canvas

def matrix():
    c.configure(bg="black")
    numbers=[0,1]
    for i in range(100):
        for j in range(50):
            c.create_text(i*20,j*20,text=random.choice(numbers),fill="green")
            c.after(50)
            c.update() # \<------
matrix()

What's the main purpose of update()? Why can't my code work without update()?

I've had a look around but couldn't really understand. You could say I'm stupid.


来源: stackexchange

问:
Interpreting User Request with Actions On Google
Unless I've done something majorly stupid, it appears I only have one entry point into my Action on Google using Actions SDK and Node.js.

Consequently, I have to work out what the user has said by using some keywords with .indexOf() and then calling the appropriate function.

I thought that would also be simpler and there would be a way I could define an action with several phrases and Google would be intelligent enough to work it all out, even if the user said something slightly differently.

I guess one of the things Im doing wrong/different, is just by having a welcome intent that essentially has a conversation and asks "What would you like to do?" then the user responds, then I have to work out what was said, and follow up an appropriate action.

That seems quite long winded. Any better ways?

答:
The "better way" is to use a tool that is designed for that and has a powerful and flexible Natural Language Processing engine associated with it. Actions directly support both Dialogflow and Converse.AI, and most other NLP engines should be able to provide information about how they work with Actions.

Dialogflow, for example, lets you specify some sample phrases that will meet an Intent, and then supplements that with "similar" phrases to the ones you've specified. Your Node.js webhook gets told which Intent was called, with what parameters you've specified for that Intent, and you can take action based on that information directly.

At this point, the Actions SDK is mostly intended to be used as the base that these and other NLP engines build on top of.

ContentLicense: CC BY-SA 3.0


问:
Commands.Stage() doesn't increment Staged.Count when staging untracked files with LibGit2Sharp
Following block works when I stage at least one tracked file. But when I stage only untracked files, repo.RetrieveStatus().Staged.Count equals to zero (I expect it to be incremented by the number of files staged), thus doesn't satisfy if condition and don't commit.

```<code>using (var repo = new LibGit2Sharp.Repository(RepoPath))
    {
        Commands.Stage("*");
        Signature author = new Signature(username, email, DateTime.Now);
        Signature committer = author;
        if (repo.RetrieveStatus().Staged.Any())
        {
            Commit commit = repo.Commit(CommitMessage, author, committer);
            Console.WriteLine(commit.ToString());
        }
    }
</code>```

Is this a bug, or I am misusing it?

答:
The definition of the Staged collection is:

List of files added to the index, which are already in the current commit with different content

ie, these correspond to the "modified" in the "changes to be committed" area of git-status, or the M status to git-status --short.

These do not, by definition, include newly added files that are staged.  For that, you want to also examine the Added collection, which is:

List of files added to the index, which are not in the current commit

ie, these correspond to the "new files" in the "changes to be committed" area of git-status, or the A status to git status --short.

However, you probably want to also consider all staged changes, which I think is what you're trying to do.  You would want to look at these collections on the status:

Added: List of files added to the index, which are not in the current commit

  Staged: List of files added to the index, which are already in the current commit with different content

  Removed: List of files removed from the index but are existent in the current commit

  RenamedInIndex: List of files that were renamed and staged (if you requested renames).

At the moment there is no function that will return a list of all staged changes, which seems like an oversight (and one that would be easy to correct, if you wanted to submit a pull request to LibGit2Sharp!)

Body:
Following block works when I stage at least one tracked file. But when I stage only untracked files, repo.RetrieveStatus().Staged.Count equals to zero (I expect it to be incremented by the number of files staged), thus doesn't satisfy if condition and don't commit.

using (var repo = new LibGit2Sharp.Repository(RepoPath))
    {
        Commands.Stage("*");
        Signature author = new Signature(username, email, DateTime.Now);
        Signature committer = author;
        if (repo.RetrieveStatus().Staged.Any())
        {
            Commit commit = repo.Commit(CommitMessage, author, committer);
            Console.WriteLine(commit.ToString());
        }
    }

Is this a bug, or I am misusing it?


问:
Set footer on bottom (adapted to content) with Angular 4 and Bootstrap 4
¿How can i make a footer stay on bottom of a website with the following structure?:

```<code><html>
    <head>
    </head>

    <body>
        <app-root></app-root>
    </body>

</html>
</code>```

So, the app-root is the main component in angular, inside this component i have the following structure:

```<code><app-navbar></app-navbar>
<div class="container">
    <div class="row">

        <div class="col-12 p-0">
            <app-information *ngIf="title == 'information'"></app-information>
            <app-form *ngIf="title == 'form'"></app-form>
            <app-proyects *ngIf="title == 'proyects'"></app-proyects>
            <app-blog *ngIf="title == 'blog'"></app-blog>
            <app-courses *ngIf="title == 'coursess'"></cursos>
        </div>

    </div>
</div>
<app-footer></app-footer>
</code>```

So, just for understanding, the divs inside the col-12 div are shown depending on a variable called title setted up by pressing buttons on the navbar.
The case is that not all of those divs have content that exceedes the screen size, and the footer goes upwards.

Inside my footer i have this structure:

```<code><footer class="bg-inf-blue" >
    <div class="container p-0">
        <div class="row text-white py-3">
            <div class="col-6 h6 p-0">Contact</div>
            <div class="col-6 h6">Social Media</div>
            <div class="col-2 p-0">
                <ul class="list-unstyled">
                    <li class="h6">Place 1</li>
                    <li>Place 1 address</li>
                    <li>XXX XXX-XXXX</li>
                </ul>
            </div>
            <div class="col-2">
                <ul class="list-unstyled">
                    <li class="h6">Place 2</li>
                    <li>Place 2 address</li>
                    <li>XXX XXX-XXXX</li>
                </ul>
            </div>
            <div class="col-2">
                <ul class="list-unstyled">
                    <li class="h6">Place 3</li>
                    <li>Place 3 address</li>
                    <li>XXX XXX-XXXX</li>
                </ul>
            </div>
            <div class="col-6 align-items-center">
                <a href="https://www.facebook.com/address/" target="blank"><img src="../assets/facebook-logo-button.png" height="40px"></a>
                <a href="https://twitter.com/address" target="blank"><img src="../assets/twitter-logo-button.png" height="40px"></a>
            </div>
            <div class="col-12 p-0">
                <small>Lorem ipsum dolor sit amet consectetur</small>
            </div>
        </div>
    </div>
</footer>
</code>```

what i need is that the footer to stay on the bottom of the screen when the content between the  and  is too short to fill the screen.

If there's a solution with CSS, i'm working with Twitter Bootstrap 4, if there's a solution with typescript, i'm working with Angular 4.

答:
If I'm understanding correctly, this can usually be achieved with css, traditionally:

```<code>html,body{
    height: 100%
}
</code>```

For your example, you could try:

```<code>.container { height: 100%;}
</code>```

Or even try moving your app-navbar and app-footer into index.html instead of app.component.html

Body:
¿How can i make a footer stay on bottom of a website with the following structure?:

        <app-root></app-root>

So, the app-root is the main component in angular, inside this component i have the following structure:

<app-navbar></app-navbar>

            <app-information *ngIf="title == 'information'"></app-information>
            <app-form *ngIf="title == 'form'"></app-form>
            <app-proyects *ngIf="title == 'proyects'"></app-proyects>
            <app-blog *ngIf="title == 'blog'"></app-blog>
            <app-courses *ngIf="title == 'coursess'"></cursos>

<app-footer></app-footer>

So, just for understanding, the divs inside the col-12 div are shown depending on a variable called title setted up by pressing buttons on the navbar.
The case is that not all of those divs have content that exceedes the screen size, and the footer goes upwards.

Inside my footer i have this structure:

Contact

Social Media

Place 1

Place 1 address

XXX XXX-XXXX

Place 2

Place 2 address

XXX XXX-XXXX

Place 3

Place 3 address

XXX XXX-XXXX

                Lorem ipsum dolor sit amet consectetur

what i need is that the footer to stay on the bottom of the screen when the content between the  and  is too short to fill the screen.

If there's a solution with CSS, i'm working with Twitter Bootstrap 4, if there's a solution with typescript, i'm working with Angular 4.

Body:
If I'm understanding correctly, this can usually be achieved with css, traditionally:

html,body{
    height: 100%
}

For your example, you could try:

.container { height: 100%;}

Or even try moving your app-navbar and app-footer into index.html instead of app.component.html


问:
AWS Athena- reduce scan size
How to reduce to data scanned size for 'select' query in AWS athena. By scanning only one of the column.

Example:
SELECT * FROM TABLE1 WHERE STATUS='Fail';

答:
The simplest way to reduce the scan size would be to partition based on the data by the STATUS value.

See the user guide for information about partitioning.  However, you may want to consider a columnar format such as Apache Parquet as well, which is a columnar data storage and interchange format which is supported by Athena.

Using a columnar format is helpful because Athena will only read the columns it must to satisfy the query. For a SELECT * query it usually won't make much of a difference, but the I/O savings can be substantial if you're only interested in a few columns out of dozens or hundreds. In addition, Parquet (and ORC, a competing columnar format also supported by Athena) support compression, so even when all columns are accessed it's still quite a savings over uncompressed CSV or JSON.

Title: AWS Athena- reduce scan size


问:
Make nested div full screen
Any idea how to stretch the thumbnail div to be full screen? I've tried a couple of methods and the closest I got to my desired output was by setting the innerHTML of the parent div with class container with the contents of the hidden div, but I still have to revert it and add some animations to not have the change so abrupt. Basically I want the Thumbnail div to rotate on Y axis and on its back some info can be found. Upon completion of the Y rotation I want it to go full screen(like a popup) and have a X button to close and get everything back to normal.

Below is the HTML, CSS and JS(didn't add the entire HTML, it would've been redundant)

```<code><div class="container">

    <div class="info-review">
        <p>Latest Version: 6.2.4<br/>
        Catia<br/>
        Last : 02.07.2013</p>
    </div>

    <div class="row flex">

        <div class="col-lg-3 col-md-4 col-sm-6">
            <div class="thumbnail">
                <img src="assets/img/Contact.jpg">
                <p>1<sup>st</sup> level support<div class="boxed-plus" aria-hidden="true"></div></p>
            </div>
        </div>

        <div class="col-lg-3 col-md-4 col-sm-6">
            <div class="thumbnail">
                <img src="assets/img/support.jpg">
                <p>1<sup>st</sup> level support<div class="boxed-plus" aria-hidden="true"></div></p>
            </div>
        </div>

        <div class="col-lg-3 col-md-4 col-sm-6">
            <div class="thumbnail">
                <img src="assets/img/license.jpg">
                    <p>1<sup>st</sup> level support<div class="boxed-plus" aria-hidden="true"></div></p>
            </div>
        </div>

        <div class="col-lg-3 col-md-4 col-sm-6">
            <div class="thumbnail">
                <img src="assets/img/application.jpg">
                <p>1<sup>st</sup> level support<div class="boxed-plus" aria-hidden="true"></div></p>
            </div>
        </div>

    </div> <!-- row -->

</div> <!-- container -->

<div id="info1"><p>         BASE: ENGAGE IN THE HOME CARE-RELATED ACTIVITY  (H_HOMEACTIVITIES=6)16_6. What do you do first in order to...? Select one.Look for inspiration (e.g., for closet organization)ONLY SHOW IF SELECTED AT Q15_6. SHOW IN SAME ORDER.IF ONLY ONE ANSWER SELECTED FOR ITEM/QUESTION AT Q15_6, AUTOCODE THAT OPTION AT HERE AND DO NOT SHOW THIS QUESTION.<div class="boxed-plus" aria-hidden="true"></div>   </p>    </div>
</code>```

CSS:

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

html {
    height: 100%;
    width: 100%;
}

body {
    margin: 0;
    height: 100%;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    padding-top: 115px;
    background: #143872;  /* fallback for old browsers */
    background: -webkit-linear-gradient(#1d355b, #4a83e0, #143872);  /* Chrome 10-25, Safari 5.1-6 */
    background: linear-gradient(#1d355b, #4a83e0, #143872); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}

.container {
    width: 95%;
    margin-left: auto;
    margin-right: auto;
    padding-right: 15px;
    padding-left: 15px;
}

.navbar {
    overflow: hidden;
    background-color: inherit;
    margin-bottom: 20px;
    position: fixed;
    width: 100%;
    top: 0;
    z-index: 1030;
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
    border-top: none;
    background: #143872;  /* fallback for old browsers */
    background: -webkit-linear-gradient(#1d355b, #4a83e0, #143872);  /* Chrome 10-25, Safari 5.1-6 */
    background: linear-gradient(#1d355b, #4a83e0, #143872); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}

@media(max-width: 600px){
    .navbar{
        border-bottom-left-radius: 0;
        border-bottom-right-radius: 0;
    }
}

.navbar a {
    float: left;
    font-size: 15px;
    color: white;
    text-align: center;
    padding: 14px 14px 16px 0;
    text-decoration: none;
    vertical-align: middle;
}

.navbar-header table{
    text-align: left;
    font-size: 18px;
    line-height: 1;
}

.navbar a:hover {
    color: #10203a;
}

.navbar-right{
    float: right;
}

.navbar a img{
    float:left;
}

.dropmenu{
    transition: all .5s ease;
    height: 50px;
    overflow: hidden;
    padding: 0;
    display: inline-block;
}

@media(max-width: 547px){
    .navbar a{
        padding: 0;
    }
    .navbar-right{
        float: none;
    }
    .dropmenu{
        margin: 0;
    }
}

.dropmenu:hover {
    height: 100px;
}

.dropmenu a{
    text-decoration: none;
    color: white;
    padding: 0;
}

.dropmenu table{
    height: 50px;
}

.lang{
    padding-bottom: 10px;
}

.dropmenu li{
    display: block;
    border: none;
    padding: 0;
    height: 50px;
}

.info-review{
    padding: 0 15px;
    text-align: center;
    margin: 0 auto 30px auto;
    border-radius: 6px;
    color: white;
    border: 1px dashed white;
    border-top-left-radius: 85px;
    border-bottom-right-radius: 85px;
}

@media(min-width: 500px){
    .container .info-review{
        width: 40%;
    }
}

.info-review p{
    margin-bottom: 15px;
    font-size: 30px;
    line-height: 1.4;
}

@media(max-width: 900px){
    .info-review p{
        font-size: 25px;
    }
}

.arrow-down {
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 5px solid white;
}

.selection-arrow {
    padding-top: 17px;
}

.thumbnail {
    overflow: auto;
    display: block;
    padding: 4px;
    margin-bottom: 20px;
    border: 1px solid #ddd;
    border-radius: 4px;
    -webkit-transition: border .2s ease-in-out;
         -o-transition: border .2s ease-in-out;
            transition: border .2s ease-in-out;
    -webkit-transform: perspective(500);
    -webkit-transform-style: preserve-3d;
    -webkit-transition: .5s;
}

.thumbnail > img {
    display: block;
    height: auto;
    max-width: 100%;
    margin-left: auto;
    margin-right: auto;
    border-radius: 6px;
}

.thumbnail p{
    color:white;
    margin: 2px 0 0 0;
    float: left;
}

.thumbnail > div{
    max-width: 100%;
}

.row {
    margin-left: -15px;
    margin-right: -15px;
}

.flex {
  display: flex;
  flex-wrap: wrap;
}

.col-md-4, .col-lg-3, .col-sm-6{
    float: left;
    position: relative;
    min-height: 1px;
    padding-left: 15px;
    padding-right: 15px;
}

@media(min-width: 600px){
    .col-sm-6{
        width: 50%;
    }
}

@media(min-width: 900px){
    .col-md-4{
        width: 33.33333333%;
    }
}

@media (min-width: 1200px){
    .col-lg-3{
        width: 25%;
    }
}

.white-popup {
  position: relative;
  background: #FFF;
  padding: 25px;
  width:auto;
  max-width: 400px;
  margin: 0 auto;
}

.active {
    background-color: white;
    -webkit-transform: rotateY(180deg) translateY(-3em) translateZ(3em);
}

.active > p {
    -webkit-transform: rotateY(-180deg);
    color: red;
    -webkit-transition: .5s;
    float: right;
}

img {
    -webkit-transition: .5s;
}
figure:hover img {
    box-shadow: none;
}
figcaption {
    background-color: white;
    visibility: hidden;
    border: 1px dashed white;

    z-index: 99 !important;
}
figure:hover figcaption {
    visibility: visible;
    box-shadow: 0 20px 15px -10px hsla(0,0%,0%,.25);
    margin: 100px auto;
}

.boxed-plus {
    cursor: pointer;
    float: right;
    border-radius: 20%;
    width: 25px;
    height: 25px;
    background: #143872;  /* fallback for old browsers */
    background: -webkit-linear-gradient(#1d355b, #4a83e0, #143872);  /* Chrome 10-25, Safari 5.1-6 */
    background: linear-gradient(#1d355b, #4a83e0, #143872); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
    position: relative;
    display: inline-block;
    margin-top: 1px;
}
.boxed-plus::after {
  content: " ";
  position: absolute;
  display: block;
  background-color: #fff;
  height: 5px;
  margin-top: -2.5px;
  top: 50%;
  left: 5px;
  right: 5px;
  z-index: 9;
}
.boxed-plus::before {
  content: " ";
  position: absolute;
  display: block;
  background-color: #fff;
  width: 5px;
  margin-left: -2.5px;
  left: 50%;
  top: 5px;
  bottom: 5px;
  z-index: 9;
}

.activity {
    -webkit-transform: rotateX(90deg);
}

#info1{
    visibility: hidden;
    background-color: white;
}
</code>```

JS:

```<code>var plus_clicked = document.querySelectorAll('.boxed-plus');
var info_1 = document.getElementById('info1');
var clicked = false;

plus_clicked.forEach(function(e){
    e.addEventListener('click',function(){
        if(clicked === false){
            var previous_html = e.parentNode.parentNode.parentNode.parentNode.innerHTML;
            clicked === true;
            e.classList.add('activity');
            this.parentNode.classList.add('active');

            setTimeout(function(){
                console.log(e.parentNode.innerHTML);
                //e.parentNode.innerHTML = info_1.innerHTML;
                e.parentNode.parentNode.parentNode.parentNode.innerHTML = info_1.innerHTML;
            }, 300);

            console.log(this.parentNode.parentNode.parentNode.parentNode);
    }else{
        e.innerHTML = previous_html;
    }
    });
})
</code>```

答:
TLDR ;)

You can just set the width and height of the element to 100vw and 100vh respectively.

Demo:

document.querySelector("div").addEventListener("click", function(){
  this.classList.toggle("active");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  background-color:aliceblue;
  border:1px solid black;
  box-sizing:border-box;
  position:absolute;
  left:50%;
}

div.active {
  width:100vw;
  height:100vh;
  position:absolute;
  top:0;
  left:0;
}</code>```

Click to Expand
```

Title: Make nested div full screen

Body:
Any idea how to stretch the thumbnail div to be full screen? I've tried a couple of methods and the closest I got to my desired output was by setting the innerHTML of the parent div with class container with the contents of the hidden div, but I still have to revert it and add some animations to not have the change so abrupt. Basically I want the Thumbnail div to rotate on Y axis and on its back some info can be found. Upon completion of the Y rotation I want it to go full screen(like a popup) and have a X button to close and get everything back to normal.

Below is the HTML, CSS and JS(didn't add the entire HTML, it would've been redundant)

Latest Version: 6.2.4

        Catia

        Last : 02.07.2013

1st level support

1st level support

1st level support

1st level support

         BASE: ENGAGE IN THE HOME CARE-RELATED ACTIVITY  (H_HOMEACTIVITIES=6)16_6. What do you do first in order to...? Select one.Look for inspiration (e.g., for closet organization)ONLY SHOW IF SELECTED AT Q15_6. SHOW IN SAME ORDER.IF ONLY ONE ANSWER SELECTED FOR ITEM/QUESTION AT Q15_6, AUTOCODE THAT OPTION AT HERE AND DO NOT SHOW THIS QUESTION.

CSS:

* {
    box-sizing: border-box;
}

html {
    height: 100%;
    width: 100%;
}

body {
    margin: 0;
    height: 100%;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    padding-top: 115px;
    background: #143872;  /* fallback for old browsers */
    background: -webkit-linear-gradient(#1d355b, #4a83e0, #143872);  /* Chrome 10-25, Safari 5.1-6 */
    background: linear-gradient(#1d355b, #4a83e0, #143872); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}

.container {
    width: 95%;
    margin-left: auto;
    margin-right: auto;
    padding-right: 15px;
    padding-left: 15px;
}

.navbar {
    overflow: hidden;
    background-color: inherit;
    margin-bottom: 20px;
    position: fixed;
    width: 100%;
    top: 0;
    z-index: 1030;
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
    border-top: none;
    background: #143872;  /* fallback for old browsers */
    background: -webkit-linear-gradient(#1d355b, #4a83e0, #143872);  /* Chrome 10-25, Safari 5.1-6 */
    background: linear-gradient(#1d355b, #4a83e0, #143872); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}

@media(max-width: 600px){
    .navbar{
        border-bottom-left-radius: 0;
        border-bottom-right-radius: 0;
    }
}

.navbar a {
    float: left;
    font-size: 15px;
    color: white;
    text-align: center;
    padding: 14px 14px 16px 0;
    text-decoration: none;
    vertical-align: middle;
}

.navbar-header table{
    text-align: left;
    font-size: 18px;
    line-height: 1;
}

.navbar a:hover {
    color: #10203a;
}

.navbar-right{
    float: right;
}

.navbar a img{
    float:left;
}

.dropmenu{
    transition: all .5s ease;
    height: 50px;
    overflow: hidden;
    padding: 0;
    display: inline-block;
}

@media(max-width: 547px){
    .navbar a{
        padding: 0;
    }
    .navbar-right{
        float: none;
    }
    .dropmenu{
        margin: 0;
    }
}

.dropmenu:hover {
    height: 100px;
}

.dropmenu a{
    text-decoration: none;
    color: white;
    padding: 0;
}

.dropmenu table{
    height: 50px;
}

.lang{
    padding-bottom: 10px;
}

.dropmenu li{
    display: block;
    border: none;
    padding: 0;
    height: 50px;
}

.info-review{
    padding: 0 15px;
    text-align: center;
    margin: 0 auto 30px auto;
    border-radius: 6px;
    color: white;
    border: 1px dashed white;
    border-top-left-radius: 85px;
    border-bottom-right-radius: 85px;
}

@media(min-width: 500px){
    .container .info-review{
        width: 40%;
    }
}

.info-review p{
    margin-bottom: 15px;
    font-size: 30px;
    line-height: 1.4;
}

@media(max-width: 900px){
    .info-review p{
        font-size: 25px;
    }
}

.arrow-down {
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 5px solid white;
}

.selection-arrow {
    padding-top: 17px;
}

.thumbnail {
    overflow: auto;
    display: block;
    padding: 4px;
    margin-bottom: 20px;
    border: 1px solid #ddd;
    border-radius: 4px;
    -webkit-transition: border .2s ease-in-out;
         -o-transition: border .2s ease-in-out;
            transition: border .2s ease-in-out;
    -webkit-transform: perspective(500);
    -webkit-transform-style: preserve-3d;
    -webkit-transition: .5s;
}

.thumbnail > img {
    display: block;
    height: auto;
    max-width: 100%;
    margin-left: auto;
    margin-right: auto;
    border-radius: 6px;
}

.thumbnail p{
    color:white;
    margin: 2px 0 0 0;
    float: left;
}

.thumbnail > div{
    max-width: 100%;
}

.row {
    margin-left: -15px;
    margin-right: -15px;
}

.flex {
  display: flex;
  flex-wrap: wrap;
}

.col-md-4, .col-lg-3, .col-sm-6{
    float: left;
    position: relative;
    min-height: 1px;
    padding-left: 15px;
    padding-right: 15px;
}

@media(min-width: 600px){
    .col-sm-6{
        width: 50%;
    }
}

@media(min-width: 900px){
    .col-md-4{
        width: 33.33333333%;
    }
}

@media (min-width: 1200px){
    .col-lg-3{
        width: 25%;
    }
}

.white-popup {
  position: relative;
  background: #FFF;
  padding: 25px;
  width:auto;
  max-width: 400px;
  margin: 0 auto;
}

.active {
    background-color: white;
    -webkit-transform: rotateY(180deg) translateY(-3em) translateZ(3em);
}

.active > p {
    -webkit-transform: rotateY(-180deg);
    color: red;
    -webkit-transition: .5s;
    float: right;
}

img {
    -webkit-transition: .5s;
}
figure:hover img {
    box-shadow: none;
}
figcaption {
    background-color: white;
    visibility: hidden;
    border: 1px dashed white;

    z-index: 99 !important;
}
figure:hover figcaption {
    visibility: visible;
    box-shadow: 0 20px 15px -10px hsla(0,0%,0%,.25);
    margin: 100px auto;
}

.boxed-plus {
    cursor: pointer;
    float: right;
    border-radius: 20%;
    width: 25px;
    height: 25px;
    background: #143872;  /* fallback for old browsers */
    background: -webkit-linear-gradient(#1d355b, #4a83e0, #143872);  /* Chrome 10-25, Safari 5.1-6 */
    background: linear-gradient(#1d355b, #4a83e0, #143872); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
    position: relative;
    display: inline-block;
    margin-top: 1px;
}
.boxed-plus::after {
  content: " ";
  position: absolute;
  display: block;
  background-color: #fff;
  height: 5px;
  margin-top: -2.5px;
  top: 50%;
  left: 5px;
  right: 5px;
  z-index: 9;
}
.boxed-plus::before {
  content: " ";
  position: absolute;
  display: block;
  background-color: #fff;
  width: 5px;
  margin-left: -2.5px;
  left: 50%;
  top: 5px;
  bottom: 5px;
  z-index: 9;
}

.activity {
    -webkit-transform: rotateX(90deg);
}

#info1{
    visibility: hidden;
    background-color: white;
}

JS:

var plus_clicked = document.querySelectorAll('.boxed-plus');
var info_1 = document.getElementById('info1');
var clicked = false;

plus_clicked.forEach(function(e){
    e.addEventListener('click',function(){
        if(clicked === false){
            var previous_html = e.parentNode.parentNode.parentNode.parentNode.innerHTML;
            clicked === true;
            e.classList.add('activity');
            this.parentNode.classList.add('active');

            setTimeout(function(){
                console.log(e.parentNode.innerHTML);
                //e.parentNode.innerHTML = info_1.innerHTML;
                e.parentNode.parentNode.parentNode.parentNode.innerHTML = info_1.innerHTML;
            }, 300);

            console.log(this.parentNode.parentNode.parentNode.parentNode);
    }else{
        e.innerHTML = previous_html;
    }
    });
})

Body:
TLDR ;)

You can just set the width and height of the element to 100vw and 100vh respectively.

Demo:

document.querySelector("div").addEventListener("click", function(){
  this.classList.toggle("active");
});

div {
  background-color:aliceblue;
  border:1px solid black;
  box-sizing:border-box;
  position:absolute;
  left:50%;
}

div.active {
  width:100vw;
  height:100vh;
  position:absolute;
  top:0;
  left:0;
}

<div>Click to Expand</div>


问:
How can I loop through a Spark data frame
How can I loop through a Spark data frame?
I have a data frame that consists of:

time, id, direction
10, 4, True  //here 4 enters --> (4,)
20, 5, True  //here 5 enters --> (4,5)
34, 5, False //here 5 leaves --> (4,)
67, 6, True  //here 6 enters --> (4,6)
78, 6, False //here 6 leaves --> (4,)
99, 4, False //here 4 leaves --> ()
```

<p>it is sorted by time and now I would like to step through and accumulate the valid ids. The ids enter on direction==True and exit on direction==False</p>

<p>so the resulting RDD should look like this</p>

<pre class="lang-none prettyprint-override"><code>time, valid_ids
(10, (4,))
(20, (4,5))
(34, (4,))
(67, (4,6))
(78, (4,)
(99, ())
</code>```

I know that this will not parallelize, but the df is not that big. So how could this be done in Spark/Scala?

答:
If data is small ("but the df is not that big") I'd just collect and process using Scala collections. If types are as shown below:

```<code>df.printSchema
root
 |-- time: integer (nullable = false)
 |-- id: integer (nullable = false)
 |-- direction: boolean (nullable = false)
</code>```

you can collect:

```<code>val data = df.as[(Int, Int, Boolean)].collect.toSeq
</code>```

and scanLeft:

```<code>val result = data.scanLeft((-1, Set[Int]())){
  case ((_, acc), (time, value, true)) => (time, acc + value)
  case ((_, acc), (time, value, false))  => (time, acc - value)
}.tail
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I loop through a Spark data frame?
I have a data frame that consists of:

time, id, direction
10, 4, True  //here 4 enters --> (4,)
20, 5, True  //here 5 enters --> (4,5)
34, 5, False //here 5 leaves --> (4,)
67, 6, True  //here 6 enters --> (4,6)
78, 6, False //here 6 leaves --> (4,)
99, 4, False //here 4 leaves --> ()

it is sorted by time and now I would like to step through and accumulate the valid ids. The ids enter on direction==True and exit on direction==False

so the resulting RDD should look like this

time, valid_ids
(10, (4,))
(20, (4,5))
(34, (4,))
(67, (4,6))
(78, (4,)
(99, ())

I know that this will not parallelize, but the df is not that big. So how could this be done in Spark/Scala?

Body:
If data is small ("but the df is not that big") I'd just collect and process using Scala collections. If types are as shown below:

df.printSchema
root
 |-- time: integer (nullable = false)
 |-- id: integer (nullable = false)
 |-- direction: boolean (nullable = false)

you can collect:

val data = df.as[(Int, Int, Boolean)].collect.toSeq

and scanLeft:

val result = data.scanLeft((-1, Set[Int]())){
  case ((_, acc), (time, value, true)) => (time, acc + value)
  case ((_, acc), (time, value, false))  => (time, acc - value)
}.tail


问:
SQL Server 2008 trigger update when specific column changes
Other solutions got me this far, but ultimately things are not working for me.

I have a column in tbl_activity named abstract. When tbl_activity.abstract changes, I want to set tbl_activity.flag = 0.

My 2 versions of the trigger will set flag = 0, but then I cannot set flag back to 1, because changing that flag causes it to trigger, and it keeps setting the flag = 0. I've tried comparing old to new values, deleted to inserted values, and tried INSTEAD OF INSERT.

Can someone please examine this code and tell me what I'm missing?

```<code>ALTER TRIGGER [dbo].[AbstractChange] --trigger name
ON [dbo].[cpy_activity] --table using the trigger
INSTEAD OF UPDATE, DELETE
AS
     UPDATE a
     SET a.flag = 0
     FROM tbl_activity a
     INNER JOIN INSERTED i ON a.activityid = i.activityid
     INNER JOIN DELETED d ON d.activityid = i.activityid
     WHERE d.abstract NOT LIKE i.abstract
</code>```

This results in "Command[s] completed successfully" - but when a column other than abstract changes, the trigger always sets flag = 0. Ideas?

答:
Not sure what the datatype of abstract is - but I'm kinda guessing that the cause of your troubles is using the NOT LIKE operator in your trigger - try this instead:

```<code>ALTER TRIGGER [dbo].[AbstractChange] --trigger name
ON [dbo].[cpy_activity] --table using the trigger
INSTEAD OF UPDATE, DELETE
AS
     UPDATE a
     SET a.flag = 0
     FROM tbl_activity a
     INNER JOIN INSERTED i ON a.activityid = i.activityid
     INNER JOIN DELETED d ON d.activityid = i.activityid
     WHERE d.abstract <> i.abstract   -- use the usual *not equal* operator <> here
</code>```

Does that change anything?

Also: why is the trigger on cpy_activity, but inside the trigger, you're using tbl_activity - seems a bit odd, really .....

Body:
Other solutions got me this far, but ultimately things are not working for me.

I have a column in tbl_activity named abstract. When tbl_activity.abstract changes, I want to set tbl_activity.flag = 0.

My 2 versions of the trigger will set flag = 0, but then I cannot set flag back to 1, because changing that flag causes it to trigger, and it keeps setting the flag = 0. I've tried comparing old to new values, deleted to inserted values, and tried INSTEAD OF INSERT.

Can someone please examine this code and tell me what I'm missing?

ALTER TRIGGER [dbo].[AbstractChange] --trigger name
ON [dbo].[cpy_activity] --table using the trigger
INSTEAD OF UPDATE, DELETE
AS
     UPDATE a
     SET a.flag = 0
     FROM tbl_activity a
     INNER JOIN INSERTED i ON a.activityid = i.activityid
     INNER JOIN DELETED d ON d.activityid = i.activityid
     WHERE d.abstract NOT LIKE i.abstract

This results in "Command[s] completed successfully" - but when a column other than abstract changes, the trigger always sets flag = 0. Ideas?

Body:
Not sure what the datatype of abstract is - but I'm kinda guessing that the cause of your troubles is using the NOT LIKE operator in your trigger - try this instead:

ALTER TRIGGER [dbo].[AbstractChange] --trigger name
ON [dbo].[cpy_activity] --table using the trigger
INSTEAD OF UPDATE, DELETE
AS
     UPDATE a
     SET a.flag = 0
     FROM tbl_activity a
     INNER JOIN INSERTED i ON a.activityid = i.activityid
     INNER JOIN DELETED d ON d.activityid = i.activityid
     WHERE d.abstract <> i.abstract   -- use the usual *not equal* operator <> here

Does that change anything?

Also: why is the trigger on cpy_activity, but inside the trigger, you're using tbl_activity - seems a bit odd, really .....


问:
Japanese Text is not show properly
My collegue wants to use my application in Japan. Therefore I tested the application in Windows 7 and changed the Regional Settings for "non-unicode"-Language to Japanese.

Now I have the problem, that some text are shown right with japanese characters. Other text is displayed with wrong characters (not japanese).

I tested also other languages like Chinese or Taiwanese and every text is right. I have only problems with Japanese.

Has anybody an idea what's wrong?

答:
It is most likely because of the "Unihan" principle being applied by Unicode, which forced similarly-looking Japanese and Chinese letters to be encoded into same Unicode character despite their glyph being difference. Many computer systems would use Chinese font instead of Japanese font by default so the Chinese font would be displayed, hence it would result in wrong glyph. Changing the "non-unicode-language" into Japanese would not solve such a problem.

In order to display the proper Japanese glyph, you need to make sure that your application is going to use a Japanese font. Normally if your program is to run in an entirely Japanese environment which include changing the default language and font of the computer into Japanese then Japanese font would be used. On the other hand, you can also specify or embed a Japanese font for your application to make sure it would work as intended.

Title: Japanese Text is not show properly


问:
Automapper ConfigurationExpression Condition
Quick question - whats the difference in the following?

This one works:

CreateMap<OrderResult, OrderViewModel>()
    .ForMember(x => x.SoldTo, opt => opt.Ignore())
    .ForMember(x => x.ShipTo, opt => opt.Ignore())
    .ForMember(x => x.ShowPlaceOrder, opt => opt.MapFrom(c => c.Messages.Count == 0));
```

<p>I would expect this one to do pretty much the same thing except "Mapper.AssertConfigurationIsValid();" fails on this one saying that "ShowPlaceOrder" is not mapped.</p>

<pre class="lang-cs prettyprint-override"><code>CreateMap<OrderResult, OrderViewModel>()
    .ForMember(x => x.SoldTo, opt => opt.Ignore())
    .ForMember(x => x.ShipTo, opt => opt.Ignore())
    .ForMember(x => x.ShowPlaceOrder, opt => opt.Condition(c => c.Messages.Count == 0));
</code>```

Thanks
Joe

答: You still need to provide a source for ShowPlaceOrder in case the condition is true.  The "Condition" method takes a predicate to decide if the mapping should be done.  I think your first example is more clear.

Body:
Quick question - whats the difference in the following?

This one works:

CreateMap<OrderResult, OrderViewModel>()
    .ForMember(x => x.SoldTo, opt => opt.Ignore())
    .ForMember(x => x.ShipTo, opt => opt.Ignore())
    .ForMember(x => x.ShowPlaceOrder, opt => opt.MapFrom(c => c.Messages.Count == 0));

I would expect this one to do pretty much the same thing except "Mapper.AssertConfigurationIsValid();" fails on this one saying that "ShowPlaceOrder" is not mapped.

CreateMap<OrderResult, OrderViewModel>()
    .ForMember(x => x.SoldTo, opt => opt.Ignore())
    .ForMember(x => x.ShipTo, opt => opt.Ignore())
    .ForMember(x => x.ShowPlaceOrder, opt => opt.Condition(c => c.Messages.Count == 0));

Thanks
Joe

ContentLicense: CC BY-SA 2.5


问:
How get the result of a boolean method in one class into an if statement of another class in Java?
I'm writing a program that gathers a first name, a last name, and the sales figure of an employee. I have all the basics working perfectly but I have an issue. In my while loop I have programmed it so if the user enters "add" then it will call a method I made in a different class and add whatever number they entered to the employees current sales total, same for subtraction. But if I need to write an if statement that checks if the subtraction is unsuccessful and if it is display an "error".

```<code> public class EmployeeInfo
 {
 //class constants

 //class variables
 private String firstName;
 private String lastName;
 private int itemsSold;
 private int employeeTotal;

public EmployeeInfo(String first, String last, int sold)
{

    //local constants

    //local variables

    /********************   Start Constructor  *****************/

    //Calls the first and last name, and the amount of items sold
    firstName = first;
    lastName = last;
    itemsSold = sold;

}//End constructor

 public void addition(int itemsSold)
   {
      //local constants

      //local variables

      /********************   Start main method  *****************/

      //Adds the items sold to the employee total
      employeeTotal = itemsSold + employeeTotal;

}//end addition

 public void subtraction(int itemsSold)
 {
       //local constants

       //local variables

       /********************   Start main method  *****************/

       //Subtracts the items not sold to the employee total
       employeeTotal = (employeeTotal - itemsSold);

}//end subtraction

public boolean booleanMethod(boolean result)
{
       //local constants

       //local variables

       /********************   Start main method  *****************/

       if(employeeTotal < 0)
       {
           result = false;
       }
       else
       {
           result = true;
       }

       return result;

 }//End booleanMethod

   public String toString()
    {
       //local constants

       //local variables

       /******************************************************/

       return String.format(Util.setLeft(45,"Eployee Name and Sales Figures") + "\n\n" + Util.setLeft(40, "First Name: ") + Util.setRight(30, firstName) +
       "\n" + Util.setLeft(40, "Last Name : ") + Util.setRight(30, lastName) + "\n" + Util.setLeft(40, "Items Sold: ") + Util.setRight(30, Integer.toString(employeeTotal)));

   }//end to string

}//end employeeInfo
</code>```

and this is a partial part of the class that uses the booleanMethod, method

```<code>while(soldItems != QUIT)
    {

        //Clear screen then prompt the user to add or subtract
        System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
        System.out.print(Util.setLeft(35, "Add or Subtract: "));
        input = Keyboard.readString();
        System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");

        //if the user enters add the program will add to the employee total
        if(input.equals(ADD))
        {
            info.addition(soldItems);

        }

        //else the program will subtract from the employee total
        else
        {
            info.subtraction(soldItems);

            if (info.booleanMethod(false))
            {
                System.out.print("Error");
                System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
            }
        }
</code>```

the tool completes successfully but it doesn't display the error message it just displays my line asking for another sales figure, how do I get it to actually work?

答:
Change your code to

```<code>if (!info.booleanMethod(false))
</code>```

which means that it's false. Your current code means

```<code>if(true)
</code>```

Actually there is no reason to pass in the boolean at all. The boolean belongs in the booleanMethod() method.

It should look like this:

```<code>public boolean booleanMethod()
{

//local constants

   //local variables

   /********************   Start main method  *****************/

   if(employeeTotal < 0)
   {
       return false;
   }
   else
   {
       return  true;
   }

}
</code>```

and you should call it like this:

```<code>if (!info.booleanMethod())
</code>```

Body:
I'm writing a program that gathers a first name, a last name, and the sales figure of an employee. I have all the basics working perfectly but I have an issue. In my while loop I have programmed it so if the user enters "add" then it will call a method I made in a different class and add whatever number they entered to the employees current sales total, same for subtraction. But if I need to write an if statement that checks if the subtraction is unsuccessful and if it is display an "error".

 public class EmployeeInfo
 {
 //class constants

 //class variables
 private String firstName;
 private String lastName;
 private int itemsSold;
 private int employeeTotal;

public EmployeeInfo(String first, String last, int sold)
{

    //local constants

    //local variables

    /********************   Start Constructor  *****************/

    //Calls the first and last name, and the amount of items sold
    firstName = first;
    lastName = last;
    itemsSold = sold;

}//End constructor

 public void addition(int itemsSold)
   {
      //local constants

      //local variables

      /********************   Start main method  *****************/

      //Adds the items sold to the employee total
      employeeTotal = itemsSold + employeeTotal;

}//end addition

 public void subtraction(int itemsSold)
 {
       //local constants

       //local variables

       /********************   Start main method  *****************/

       //Subtracts the items not sold to the employee total
       employeeTotal = (employeeTotal - itemsSold);

}//end subtraction

public boolean booleanMethod(boolean result)
{
       //local constants

       //local variables

       /********************   Start main method  *****************/

       if(employeeTotal < 0)
       {
           result = false;
       }
       else
       {
           result = true;
       }

       return result;

 }//End booleanMethod

   public String toString()
    {
       //local constants

       //local variables

       /******************************************************/

       return String.format(Util.setLeft(45,"Eployee Name and Sales Figures") + "\n\n" + Util.setLeft(40, "First Name: ") + Util.setRight(30, firstName) +
       "\n" + Util.setLeft(40, "Last Name : ") + Util.setRight(30, lastName) + "\n" + Util.setLeft(40, "Items Sold: ") + Util.setRight(30, Integer.toString(employeeTotal)));

   }//end to string

}//end employeeInfo

and this is a partial part of the class that uses the booleanMethod, method

while(soldItems != QUIT)
    {

        //Clear screen then prompt the user to add or subtract
        System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
        System.out.print(Util.setLeft(35, "Add or Subtract: "));
        input = Keyboard.readString();
        System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");

        //if the user enters add the program will add to the employee total
        if(input.equals(ADD))
        {
            info.addition(soldItems);

        }

        //else the program will subtract from the employee total
        else
        {
            info.subtraction(soldItems);

            if (info.booleanMethod(false))
            {
                System.out.print("Error");
                System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
            }
        }

the tool completes successfully but it doesn't display the error message it just displays my line asking for another sales figure, how do I get it to actually work?

Body:
Change your code to

if (!info.booleanMethod(false))

which means that it's false. Your current code means

if(true)

Actually there is no reason to pass in the boolean at all. The boolean belongs in the booleanMethod() method.

It should look like this:

public boolean booleanMethod()
{

//local constants

   //local variables

   /********************   Start main method  *****************/

   if(employeeTotal < 0)
   {
       return false;
   }
   else
   {
       return  true;
   }

}

and you should call it like this:

if (!info.booleanMethod())


问:
Angular2: res.json is not a function
I am trying to use the following service in my code:

```<code>import {Injectable} from '@angular/core';
import {Http,Response} from "@angular/http";
import 'rxjs/Rx';

@Injectable()
export class HttpService{
    constructor(private http : Http){}

    getData(){
      return  this.http.get("URI")
      .map( (res: Response) => res.json()  );
    }
}
</code>```

The problem is, in run time it complains with:

```<code>res.json is not a function
</code>```

I have defined the datatype of res as Response, but still complains

```<code>.map( (res: Response) => res.json()  )
</code>```

if i replace the map with subscribe it works fine:

```<code>.subscribe( res =>{
                res.json();
                console.log("City is:"+ res.json().city.name)
            });
</code>```

答: For what its worth, in Angular 5 I found that the res.json is not a function error can be fixed by just returning res if the response is pure json.

Title: Angular2: res.json is not a function

Body:
I am trying to use the following service in my code:

import {Injectable} from '@angular/core';
import {Http,Response} from "@angular/http";
import 'rxjs/Rx';

@Injectable()
export class HttpService{
    constructor(private http : Http){}

    getData(){
      return  this.http.get("URI")
      .map( (res: Response) => res.json()  );
    }
}

The problem is, in run time it complains with:

res.json is not a function

I have defined the datatype of res as Response, but still complains

.map( (res: Response) => res.json()  )

if i replace the map with subscribe it works fine:

.subscribe( res =>{
                res.json();
                console.log("City is:"+ res.json().city.name)
            });


问:
Prime number test for numbers 1 - 1000
As a homework I have to write a prime number test, that gives back a "true" or "false" statement. The tricky thing is, I have to write a csv.-file that includes the "true" and "false" statements for the numbers 1 to 1000.
I used this code for the prime number test

```<code>def Primzahl(n):
if n < 2:
    return False
if n == 2:
    return True
if not n & 1:
    return False
for x in range(3, int(n**0.5) + 1, 2):
    if n % x == 0:
        return False
return True
</code>```

and

```<code>for i in range (1,1001):
    Primzahl (i)
    print (i)
</code>```

My for-loop only gives out the numbers 1,1000 but not the true or false statements. Do I have to include if and else in my for loop? Can anyone help?

答:
Currently you're only printing i, and not the return value from your method. You aren't doing anything with the return value from your method. You should assign the result to a variable and print the variable also. (You could also just call the method from within the print statement.)</p>

```<code>for i in range (1,1001):
isPrime = Primzahl(i)
print (i + ": " + isPrime)
</code>```

Title: Prime number test for numbers 1 - 1000

Body:
As a homework I have to write a prime number test, that gives back a "true" or "false" statement. The tricky thing is, I have to write a csv.-file that includes the "true" and "false" statements for the numbers 1 to 1000.
I used this code for the prime number test

def Primzahl(n):
if n < 2:
    return False
if n == 2:
    return True
if not n & 1:
    return False
for x in range(3, int(n**0.5) + 1, 2):
    if n % x == 0:
        return False
return True

and

for i in range (1,1001):
    Primzahl (i)
    print (i)

My for-loop only gives out the numbers 1,1000 but not the true or false statements. Do I have to include if and else in my for loop? Can anyone help?

Body:
Currently you're only printing i, and not the return value from your method. You aren't doing anything with the return value from your method. You should assign the result to a variable and print the variable also. (You could also just call the method from within the print statement.)

for i in range (1,1001):
isPrime = Primzahl(i)
print (i + ": " + isPrime)


问:
Is it possible to have a "loop interrupt" with user input?
This has probably been answered somewhere, I just can seem to find an answer to it. Anyways, I am making a program that loops a certain number for times, however I would like the program to take the input of the user after they have hit a space bar to trigger the fact the user will be inputting something. Now my logic maybe off but this is what I am trying.

```<code>  for ( int i = 0 ; i < length (user input from before); i++){
     do{
        cout << "Hello World" << endl;
     }while(cin.getch() == ' ');
  }
</code>```

From what I see the program doing, it stops each time my iterator is increased. I'm kinda sure the logic on why it's stopping each time but how do I make it so it loops and only stops when the user hits the space key?

答:
getch is a blocking function, i.e if the input buffer is empty, it blocks the current thread and waits for user input. If you like to have something working in the meanwhile, you'd have to spawn a separate thread. See the following code that starts a new thread for the "worker", while the main thread waits for user input. Hope it helps somehow.

```<code>#include <iostream>
#include <thread>

struct Worker {
    Worker() : stopped(false) {};
    void doWork() {
        while (!stopped) {
            cout << "Hello World!" << endl;
        }
        cout << "Stopped!" << endl;
    }
    atomic<bool> stopped;

};

int main(){

    Worker w;
    thread thread1(&Worker::doWork,&w);

    int c;
    while ((c = getchar()) != ' ');

    w.stopped = true;

    thread1.join();  // avoid that main thread ends before the worker thread.
}
</code>```

Body:
This has probably been answered somewhere, I just can seem to find an answer to it. Anyways, I am making a program that loops a certain number for times, however I would like the program to take the input of the user after they have hit a space bar to trigger the fact the user will be inputting something. Now my logic maybe off but this is what I am trying.

  for ( int i = 0 ; i < length (user input from before); i++){
     do{
        cout << "Hello World" << endl;
     }while(cin.getch() == ' ');
  }

From what I see the program doing, it stops each time my iterator is increased. I'm kinda sure the logic on why it's stopping each time but how do I make it so it loops and only stops when the user hits the space key?

Body:
getch is a blocking function, i.e if the input buffer is empty, it blocks the current thread and waits for user input. If you like to have something working in the meanwhile, you'd have to spawn a separate thread. See the following code that starts a new thread for the "worker", while the main thread waits for user input. Hope it helps somehow.

#include <iostream>
#include <thread>

struct Worker {
    Worker() : stopped(false) {};
    void doWork() {
        while (!stopped) {
            cout << "Hello World!" << endl;
        }
        cout << "Stopped!" << endl;
    }
    atomic<bool> stopped;

};

int main(){

    Worker w;
    thread thread1(&Worker::doWork,&w);

    int c;
    while ((c = getchar()) != ' ');

    w.stopped = true;

    thread1.join();  // avoid that main thread ends before the worker thread.
}


问:
Reading from file with fgetc in C
I have a file with more rows, and now, I would like to scan the 3th, from char to char. This is working, but I can't assign the chars with the (onerow) array, only the first one:

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#if defined(WIN32) || defined(_WIN32)
    #include <windows.h>
#endif

int main(void) {
#if defined(WIN32) || defined(_WIN32) //for latin2
    SetConsoleCP(1250);
    SetConsoleOutputCP(1250);
#endif
    //char* onerow=(char*) malloc(num*sizeof(char));
    char* onerow[250];
    char c;
    int row=3, j=0;

    FILE *fp;
    fp = fopen("proba.txt", "r");

    for (int i=0; i<=row; i++) {
        if(i!=row-1) {          //not the row we need, jump over it
            while(c!='\n')
                c=fgetc(fp);
            c='a'; //to make true while next time
        }
        if(i==row-1) {
            while(c!='\n') {    //this is what we need
                //onerow[j]=fgetc(fp);
                //onerow = (char*)realloc(onerow, ++num*sizeof(char));
                c=fgetc(fp);
                printf("%c", c); //this is working well (prints everyth.)
                onerow[j++]=c;
            }
        }
    }
    onerow[j-1]='\0';
    fclose(fp);
    printf("%s", onerow); //prints only the first charachter
    //free(onerow);
}
</code>```

First output (%c) is good, that is the whole row. However the second output (%s) is only the row's first char (which is a number in the file... the file is a latin2 txt.)

答:
You declared onerow as an array of pointers to characters, you can't assign characters directly to the elements.

If you want onerow to be a dynamically-growing string, it should be declared as a pointer, not an array of pointers:

```<code>size_t rowsize = 250;
char *onerow = malloc(rowsize);
</code>```

Then you should call realloc() if you get more than rowsize characters.

```<code>c = fgetc(fp);
if (j >= rowsize-1) {
    rowsize += 250;
    onerow = realloc(onerow, rowsize);
}
onerow[j++] = c;
</code>```

And at the end you shouldn't subtract 1 from j when appending the null byte, it should be:

```<code>onerow[j] = '\0';
</code>```

I used rowsize-1 in the above test before realloc() to ensure that there will be room for the null byte (rather than doing another test here).

Title: Reading from file with fgetc in C

Body:
I have a file with more rows, and now, I would like to scan the 3th, from char to char. This is working, but I can't assign the chars with the (onerow) array, only the first one:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#if defined(WIN32) || defined(_WIN32)
    #include <windows.h>
#endif

int main(void) {
#if defined(WIN32) || defined(_WIN32) //for latin2
    SetConsoleCP(1250);
    SetConsoleOutputCP(1250);
#endif
    //char* onerow=(char*) malloc(num*sizeof(char));
    char* onerow[250];
    char c;
    int row=3, j=0;

    FILE *fp;
    fp = fopen("proba.txt", "r");

    for (int i=0; i<=row; i++) {
        if(i!=row-1) {          //not the row we need, jump over it
            while(c!='\n')
                c=fgetc(fp);
            c='a'; //to make true while next time
        }
        if(i==row-1) {
            while(c!='\n') {    //this is what we need
                //onerow[j]=fgetc(fp);
                //onerow = (char*)realloc(onerow, ++num*sizeof(char));
                c=fgetc(fp);
                printf("%c", c); //this is working well (prints everyth.)
                onerow[j++]=c;
            }
        }
    }
    onerow[j-1]='\0';
    fclose(fp);
    printf("%s", onerow); //prints only the first charachter
    //free(onerow);
}

First output (%c) is good, that is the whole row. However the second output (%s) is only the row's first char (which is a number in the file... the file is a latin2 txt.)

Body:
You declared onerow as an array of pointers to characters, you can't assign characters directly to the elements.

If you want onerow to be a dynamically-growing string, it should be declared as a pointer, not an array of pointers:

size_t rowsize = 250;
char *onerow = malloc(rowsize);

Then you should call realloc() if you get more than rowsize characters.

c = fgetc(fp);
if (j >= rowsize-1) {
    rowsize += 250;
    onerow = realloc(onerow, rowsize);
}
onerow[j++] = c;

And at the end you shouldn't subtract 1 from j when appending the null byte, it should be:

onerow[j] = '\0';

I used rowsize-1 in the above test before realloc() to ensure that there will be room for the null byte (rather than doing another test here).


问:
HTML5 Changing paragraphs background color with button js
I got small troubles with this one:

```<code><style>
p:empty {height:20px};
p:nth-child(4n+3) {background:black};
</style>
</head>

<body>

<button onclick="f()">white</button>
<script>
function f() {
var x = document.getElementsByTagName("p");
x.style.backgroundColor = "white";
}
</script>

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

(there are 20paragraphs)
So every 4th paragraph got black background, and it all works well.
I want this button to switch black back to the white after clicking on it, but it's just not working, what am I doing wrong?

答:
As was stated in the comments, you'll want to iterate through the elements. That's quite simple to do, just use a forEach as shown below.

```<code>function f() {
    var x = document.getElementsByTagName("p");
    Array.from(x).forEach(elem => elem.style.backgroundColor = "white");
}
</code>```

Body:
I got small troubles with this one:

<button onclick="f()">white</button>

....

(there are 20paragraphs)
So every 4th paragraph got black background, and it all works well.
I want this button to switch black back to the white after clicking on it, but it's just not working, what am I doing wrong?

Body:
As was stated in the comments, you'll want to iterate through the elements. That's quite simple to do, just use a forEach as shown below.

function f() {
    var x = document.getElementsByTagName("p");
    Array.from(x).forEach(elem => elem.style.backgroundColor = "white");
}


问:
tensorflow CUDA_ERROR_UNKNOWN error
I downloaded CUDA Toolkit 8.0 GA2, cuDNN v6.0 for CUDA 8 and tensorflow 1.4. I have an Nvidia 740M graphics chip. I tried running this code to test tensorflow:

```<code>import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))
</code>```

This is what it returns:

```<code>2017-11-09 16:25:42.999638: I C:\tf_jenkins\home\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\core\platform\cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compil
ed to use: AVX AVX2
2017-11-09 16:25:43.007712: E C:\tf_jenkins\home\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\stream_executor\cuda\cuda_driver.cc:406] failed call to cuInit: CUDA_ERROR_UNKNOWN
2017-11-09 16:25:43.010457: I C:\tf_jenkins\home\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\stream_executor\cuda\cuda_diagnostics.cc:158] retrieving CUDA diagnostic information for host: DESKTOP-06398IN
2017-11-09 16:25:43.010576: I C:\tf_jenkins\home\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\stream_executor\cuda\cuda_diagnostics.cc:165] hostname: DESKTOP-06398IN
b'Hello, TensorFlow!'
</code>```

What does the error CUDA_ERROR_UNKNOWN mean? How do I fix it? Thanks

答: Updating the graphics driver fixed it.</p>

Title: tensorflow CUDA_ERROR_UNKNOWN error

Body:
I downloaded CUDA Toolkit 8.0 GA2, cuDNN v6.0 for CUDA 8 and tensorflow 1.4. I have an Nvidia 740M graphics chip. I tried running this code to test tensorflow:

import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))

This is what it returns:

2017-11-09 16:25:42.999638: I C:\tf_jenkins\home\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\core\platform\cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compil
ed to use: AVX AVX2
2017-11-09 16:25:43.007712: E C:\tf_jenkins\home\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\stream_executor\cuda\cuda_driver.cc:406] failed call to cuInit: CUDA_ERROR_UNKNOWN
2017-11-09 16:25:43.010457: I C:\tf_jenkins\home\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\stream_executor\cuda\cuda_diagnostics.cc:158] retrieving CUDA diagnostic information for host: DESKTOP-06398IN
2017-11-09 16:25:43.010576: I C:\tf_jenkins\home\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\stream_executor\cuda\cuda_diagnostics.cc:165] hostname: DESKTOP-06398IN
b'Hello, TensorFlow!'

What does the error CUDA_ERROR_UNKNOWN mean? How do I fix it? Thanks

Body: Updating the graphics driver fixed it.


问:
Calls to CouchDB's _session always return 200
Is it right that calls to the CouchDB _session endpoint always seem to return a 200 HTTP status code, even if the cookie I'm passing is absent or wrong?

Passing a wrong cookie or no cookie in my GET request headers always seems to return:

```<code>{
  "ok": true,
  "userCtx": {
    "name": null,
    "roles": []
  },
  "info": {
    "authentication_db": "_users",
    "authentication_handlers": [
      "cookie",
      "default"
    ]
  }
}
</code>```

When passing the correct cookie, I receive a slightly different response:

```<code>{
  "ok": true,
  "userCtx": {
    "name": "jack",
    "roles": []
  },
  "info": {
    "authentication_db": "_users",
    "authentication_handlers": [
      "cookie",
      "default"
    ],
    "authenticated": "cookie"
  }
}
</code>```

Is this standard behaviour? If it is, which key should I rely on to assume a successful authentication? Should it be res.userCtx.name or res.info.authenticated?

答:
This appears to be standard behavior, although it's not explicitly stated in the documentation.

However, you can tell CouchDB to return a 401 response by setting basic=true in the query like this: /_session?basic=true.

It seems to suggest that it's useful for basic authentication, but it also works with a cookie authenticated user. (tested with CouchDB 2.0.0)

Body:
Is it right that calls to the CouchDB _session endpoint always seem to return a 200 HTTP status code, even if the cookie I'm passing is absent or wrong?

Passing a wrong cookie or no cookie in my GET request headers always seems to return:

{
  "ok": true,
  "userCtx": {
    "name": null,
    "roles": []
  },
  "info": {
    "authentication_db": "_users",
    "authentication_handlers": [
      "cookie",
      "default"
    ]
  }
}

When passing the correct cookie, I receive a slightly different response:

{
  "ok": true,
  "userCtx": {
    "name": "jack",
    "roles": []
  },
  "info": {
    "authentication_db": "_users",
    "authentication_handlers": [
      "cookie",
      "default"
    ],
    "authenticated": "cookie"
  }
}

Is this standard behaviour? If it is, which key should I rely on to assume a successful authentication? Should it be res.userCtx.name or res.info.authenticated?


问:
I'm trying to read a text file using Java but it gets erased when the program executes
I'm trying to make two objects that are able to read and write to a text file. The problem happens when I execute the program. The text file gets erased. Why is this happening and how do I fix this?

CODE:

Object to read text files:

```<code>    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;

    public class Reader {

        public static String fromFile;
        public static FileReader fr;
        public static BufferedReader file;

        public Reader(String fileName) throws IOException, FileNotFoundException {
            fr = new FileReader(fileName);
            file = new BufferedReader(fr);
        }

        public void readFile() throws IOException {
            while((fromFile = file.readLine()) != null) {
                System.out.println(fromFile);
            }
        }

    }
</code>```

Object to write to text files:

```<code>    import java.io.BufferedWriter;
    import java.io.FileNotFoundException;
    import java.io.FileWriter;
    import java.io.IOException;

    public class Writer {

        public static FileWriter fw;
        public static BufferedWriter file;

        public Writer(String fileName) throws IOException, FileNotFoundException {
            fw = new FileWriter(fileName);
            file = new BufferedWriter(fw);
        }

    }
</code>```

Main method to create Reader and Writer objects and use the Reader to read the text file:

```<code>    import java.io.IOException;

    public class Main {

        public static Writer toFile;
        public static Reader fromFile;
        public static String fileName = "test123.txt";

        public static void main(String[] args) throws IOException  {

            toFile = new Writer(fileName);
            fromFile = new Reader(fileName);

            fromFile.readFile();
        }

    }
</code>```

答:
This is just my suggestion.</p>

```<code>  import java.io.*;

    public class Main {

        public static void main(String[] args) throws IOException  {
            public static String fileName = "test123.txt";
            Read rd=new Read();
            rd.reader(filename);
        }

    }

public class Read
{
        public void reader(String filename)
       {
        FileReader fr=new FileReader(filename);
        BufferedReader bfr=new BufferedWriter (fr);
        String text="";
        String line=reader.readLine();
        while(line!=null)
        {
            text+=line;
            line=reader.readLine();
        }
        System.out.println(text);

       }
   fr.close();
   bfr.close();
}
</code>```

Body:
I'm trying to make two objects that are able to read and write to a text file. The problem happens when I execute the program. The text file gets erased. Why is this happening and how do I fix this?

CODE:

Object to read text files:

    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;

    public class Reader {

        public static String fromFile;
        public static FileReader fr;
        public static BufferedReader file;

        public Reader(String fileName) throws IOException, FileNotFoundException {
            fr = new FileReader(fileName);
            file = new BufferedReader(fr);
        }

        public void readFile() throws IOException {
            while((fromFile = file.readLine()) != null) {
                System.out.println(fromFile);
            }
        }

    }

Object to write to text files:

    import java.io.BufferedWriter;
    import java.io.FileNotFoundException;
    import java.io.FileWriter;
    import java.io.IOException;

    public class Writer {

        public static FileWriter fw;
        public static BufferedWriter file;

        public Writer(String fileName) throws IOException, FileNotFoundException {
            fw = new FileWriter(fileName);
            file = new BufferedWriter(fw);
        }

    }

Main method to create Reader and Writer objects and use the Reader to read the text file:

    import java.io.IOException;

    public class Main {

        public static Writer toFile;
        public static Reader fromFile;
        public static String fileName = "test123.txt";

        public static void main(String[] args) throws IOException  {

            toFile = new Writer(fileName);
            fromFile = new Reader(fileName);

            fromFile.readFile();
        }

    }

Body:
This is just my suggestion.

  import java.io.*;

    public class Main {

        public static void main(String[] args) throws IOException  {
            public static String fileName = "test123.txt";
            Read rd=new Read();
            rd.reader(filename);
        }

    }

public class Read
{
        public void reader(String filename)
       {
        FileReader fr=new FileReader(filename);
        BufferedReader bfr=new BufferedWriter (fr);
        String text="";
        String line=reader.readLine();
        while(line!=null)
        {
            text+=line;
            line=reader.readLine();
        }
        System.out.println(text);

       }
   fr.close();
   bfr.close();
}


问:
How to set column C value based on a initial column A,B,C value
I have the following table :

```<code>A     B       C
food  fruit   apple
food  fruit
food  drink
food  fruit
car   suv     ford
car   sedan   bmw
car   suv
car   sedan
</code>```

Desired result :

```<code> A     B       C
food  fruit   apple
food  fruit   apple
food  drink
food  fruit   apple
car   suv     ford
car   sedan   bmw
car   suv     ford
car   sedan   bmw
</code>```

How can complete column C based on the values in both Column A, B?  For example, if the value in Column A = food and Column B = fruit, then Column C should be filled with. Ideally, I want to do it without having to manually enter the column A, B pair and the corresponding column C value since my table has thousands of such combinations.

Would appreciate any help!

答:
A solution with fill from tidyr:

```<code>library(dplyr)
library(tidyr)

df %>%
  mutate(C = ifelse(C == "", NA, C)) %>%
  group_by(A, B) %>%
  fill(C)
</code>```

Result:

```<code># A tibble: 8 x 3
# Groups:   A, B [4]
      A     B     C
  <chr> <chr> <chr>
1   car sedan   bmw
2   car sedan   bmw
3   car   suv  ford
4   car   suv  ford
5  food drink  <NA>
6  food fruit apple
7  food fruit apple
8  food fruit apple
</code>```

To get original row order:

```<code>df %>%
  mutate(C = ifelse(C == "", NA, C),
         ID = row_number()) %>%
  group_by(A, B) %>%
  fill(C) %>%
  arrange(ID) %>%
  select(-ID)
</code>```

Result:

```<code># A tibble: 8 x 3
# Groups:   A, B [4]
      A     B     C
  <chr> <chr> <chr>
1  food fruit apple
2  food fruit apple
3  food drink  <NA>
4  food fruit apple
5   car   suv  ford
6   car sedan   bmw
7   car   suv  ford
8   car sedan   bmw
</code>```

Data:

```<code>df = structure(list(A = c("food", "food", "food", "food", "car", "car",
"car", "car"), B = c("fruit", "fruit", "drink", "fruit", "suv",
"sedan", "suv", "sedan"), C = c("apple", "", "", "", "ford",
"bmw", "", "")), .Names = c("A", "B", "C"), class = "data.frame", row.names = c(NA,
-8L))
</code>```

Body:
I have the following table :

A     B       C
food  fruit   apple
food  fruit
food  drink
food  fruit
car   suv     ford
car   sedan   bmw
car   suv
car   sedan

Desired result :

 A     B       C
food  fruit   apple
food  fruit   apple
food  drink
food  fruit   apple
car   suv     ford
car   sedan   bmw
car   suv     ford
car   sedan   bmw

How can complete column C based on the values in both Column A, B?  For example, if the value in Column A = food and Column B = fruit, then Column C should be filled with. Ideally, I want to do it without having to manually enter the column A, B pair and the corresponding column C value since my table has thousands of such combinations.

Would appreciate any help!

Body:
A solution with fill from tidyr:

library(dplyr)
library(tidyr)

df %>%
  mutate(C = ifelse(C == "", NA, C)) %>%
  group_by(A, B) %>%
  fill(C)

Result:

# A tibble: 8 x 3
# Groups:   A, B [4]
      A     B     C
  <chr> <chr> <chr>
1   car sedan   bmw
2   car sedan   bmw
3   car   suv  ford
4   car   suv  ford
5  food drink  <NA>
6  food fruit apple
7  food fruit apple
8  food fruit apple

To get original row order:

df %>%
  mutate(C = ifelse(C == "", NA, C),
         ID = row_number()) %>%
  group_by(A, B) %>%
  fill(C) %>%
  arrange(ID) %>%
  select(-ID)

Result:

# A tibble: 8 x 3
# Groups:   A, B [4]
      A     B     C
  <chr> <chr> <chr>
1  food fruit apple
2  food fruit apple
3  food drink  <NA>
4  food fruit apple
5   car   suv  ford
6   car sedan   bmw
7   car   suv  ford
8   car sedan   bmw

Data:

df = structure(list(A = c("food", "food", "food", "food", "car", "car",
"car", "car"), B = c("fruit", "fruit", "drink", "fruit", "suv",
"sedan", "suv", "sedan"), C = c("apple", "", "", "", "ford",
"bmw", "", "")), .Names = c("A", "B", "C"), class = "data.frame", row.names = c(NA,
-8L))


问:
SQL Assigning a value into table based off another table
I am trying to find a better way to accomplish what I am trying to do.

I have two database tables (Booking and TimeSlots)

Booking is a list of appointments, TimeSlots is a list of time slots.

What I am trying to do is when something gets inserted into Booking, get the first row of TimeSlot that is not marked as taken (no one should have the same TimeSlot) and then mark the TimeSlot as taken, so its not longer the first row that is not marked as taken

I originally had this:

```<code>SELECT TOP 1 @DateSlot = dateSlot, @TimeSlot = timeSlot FROM TimeSlots WHERE taken = 0

UPDATE TimeSlots SET taken = 1 WHERE dateSlot = @DateSlot AND timeSlot = @TimeSlot

INSERT INTO Booking (email, dateSlot, timeSlot, startTime, dateCreated, createdBy, dateModified, modifiedBy, isWaitList) VALUES (@Email, @DateSlot, @TimeSlot, @StartTime, GETDATE(), @Email, GETDATE(), @Email, @IsWaitListed)
</code>```

But the problem with this if two inserts were made at the exact same time, they both with get the same date and time slot.

So I came up with this:

```<code>SELECT @AppointmentAccepted = 1
SELECT @IsWaitListed = 0

//Insert Into the database

INSERT INTO Booking (email, dateSlot, timeSlot, startTime, dateCreated, createdBy, dateModified, modifiedBy, isWaitList) VALUES (@Email, ‘’, '', @StartTime, GETDATE(), @Email, GETDATE(), @Email, @IsWaitListed)

//Get the ID of the new insert

SET @TableA_PK=SCOPE_IDENTITY()

//Get Time Slot Where slotOrder = New Insert ID

SELECT @DateSlot = dateSlot, @TimeSlot = timeSlot FROM TimeSlots WHERE slotOrder = @TableA_PK

//Update The database with Date and Time Slot

UPDATE Booking SET dateSlot = @DateSlot, timeSlot = @TimeSlot WHERE id = @TableA_PK

//Update Time Slot as taken

UPDATE TimeSlots SET taken = 1 WHERE slotOrder = @TableA_PK
</code>```

Which is not bad, I get the ID for the insert grab the time slot based on slotOrder and ID from the insert, then update the time slot as taken and update the appointment with date and time slot.

The issue with this, my database does not always start with 1 and I can’t grab the first Timeslot that is not marked as taken and if a TimeSlot gets deleted, an insert into the appointment table will not have a Time Slot, I don’t like the idea of grabbing another value from another table based off the recent inserted ID

Are there any suggestions on how to improve this where I am not getting a row based off ID, Ideally I would love to get it based off Row Order instead of IDs

答:
Use a transaction to get the timeslot value and then update it to set it to taken.  This will keep other users from getting the same time slot.

```<code>begin transaction
SELECT TOP 1 @DateSlot = dateSlot, @TimeSlot = timeSlot FROM TimeSlots WHERE taken = 0

UPDATE TimeSlots SET taken = 1 WHERE dateSlot = @DateSlot AND timeSlot = @TimeSlot
commit transaction

INSERT INTO Booking (email, dateSlot, timeSlot, startTime, dateCreated, createdBy, dateModified, modifiedBy, isWaitList) VALUES (@Email, @DateSlot, @TimeSlot, @StartTime, GETDATE(), @Email, GETDATE(), @Email, @IsWaitListed)
</code>```

Now no two users will get the same timeslot, even if they submit the request at the same time.  Works for dozens of users too.  Users will be blocked while the transaction isn't committed.  And since you only have 2 lines of SQL inside the transaction, it will be very quick.  I doubt users will even notice (as long as the select top 1 ... query returns fast -- if not, you will need to index that table so it returns instantly).

Also, do you need an order by clause on your select top 1 ... query to ensure that it always returns the available time slots in the same order?

Body:
I am trying to find a better way to accomplish what I am trying to do.

I have two database tables (Booking and TimeSlots)

Booking is a list of appointments, TimeSlots is a list of time slots.

What I am trying to do is when something gets inserted into Booking, get the first row of TimeSlot that is not marked as taken (no one should have the same TimeSlot) and then mark the TimeSlot as taken, so its not longer the first row that is not marked as taken

I originally had this:

SELECT TOP 1 @DateSlot = dateSlot, @TimeSlot = timeSlot FROM TimeSlots WHERE taken = 0

UPDATE TimeSlots SET taken = 1 WHERE dateSlot = @DateSlot AND timeSlot = @TimeSlot

INSERT INTO Booking (email, dateSlot, timeSlot, startTime, dateCreated, createdBy, dateModified, modifiedBy, isWaitList) VALUES (@Email, @DateSlot, @TimeSlot, @StartTime, GETDATE(), @Email, GETDATE(), @Email, @IsWaitListed)

But the problem with this if two inserts were made at the exact same time, they both with get the same date and time slot.

So I came up with this:

SELECT @AppointmentAccepted = 1
SELECT @IsWaitListed = 0

//Insert Into the database

INSERT INTO Booking (email, dateSlot, timeSlot, startTime, dateCreated, createdBy, dateModified, modifiedBy, isWaitList) VALUES (@Email, ‘’, '', @StartTime, GETDATE(), @Email, GETDATE(), @Email, @IsWaitListed)

//Get the ID of the new insert

SET @TableA_PK=SCOPE_IDENTITY()

//Get Time Slot Where slotOrder = New Insert ID

SELECT @DateSlot = dateSlot, @TimeSlot = timeSlot FROM TimeSlots WHERE slotOrder = @TableA_PK

//Update The database with Date and Time Slot

UPDATE Booking SET dateSlot = @DateSlot, timeSlot = @TimeSlot WHERE id = @TableA_PK

//Update Time Slot as taken

UPDATE TimeSlots SET taken = 1 WHERE slotOrder = @TableA_PK

Which is not bad, I get the ID for the insert grab the time slot based on slotOrder and ID from the insert, then update the time slot as taken and update the appointment with date and time slot.

The issue with this, my database does not always start with 1 and I can’t grab the first Timeslot that is not marked as taken and if a TimeSlot gets deleted, an insert into the appointment table will not have a Time Slot, I don’t like the idea of grabbing another value from another table based off the recent inserted ID

Are there any suggestions on how to improve this where I am not getting a row based off ID, Ideally I would love to get it based off Row Order instead of IDs

Body:
Use a transaction to get the timeslot value and then update it to set it to taken.  This will keep other users from getting the same time slot.

begin transaction
SELECT TOP 1 @DateSlot = dateSlot, @TimeSlot = timeSlot FROM TimeSlots WHERE taken = 0

UPDATE TimeSlots SET taken = 1 WHERE dateSlot = @DateSlot AND timeSlot = @TimeSlot
commit transaction

INSERT INTO Booking (email, dateSlot, timeSlot, startTime, dateCreated, createdBy, dateModified, modifiedBy, isWaitList) VALUES (@Email, @DateSlot, @TimeSlot, @StartTime, GETDATE(), @Email, GETDATE(), @Email, @IsWaitListed)

Now no two users will get the same timeslot, even if they submit the request at the same time.  Works for dozens of users too.  Users will be blocked while the transaction isn't committed.  And since you only have 2 lines of SQL inside the transaction, it will be very quick.  I doubt users will even notice (as long as the select top 1 ... query returns fast -- if not, you will need to index that table so it returns instantly).

Also, do you need an order by clause on your select top 1 ... query to ensure that it always returns the available time slots in the same order?


问:
Python 3.4: py2exe not compiling program with tkinter
I was trying to compile my program using py2exe with the setup.py and all but whenever I try the console gives me this:

```<code>Traceback (most recent call last):
  File "setup.py", line 10, in <module>
zipfile = None)
  File "C:\Python34\lib\distutils\core.py", line 149, in setup
dist.run_commands()
  File "C:\Python34\lib\distutils\dist.py", line 955, in run_commands
self.run_command(cmd)
  File "C:\Python34\lib\distutils\dist.py", line 974, in run_command
cmd_obj.run()
  File "C:\Python34\lib\site-packages\py2exe\distutils_buildexe.py", line 188, in run
self._run()
  File "C:\Python34\lib\site-packages\py2exe\distutils_buildexe.py", line 267, in _run
builder.analyze()
  File "C:\Python34\lib\site-packages\py2exe\runtime.py", line 164, in analyze
mf.import_hook(modname)
  File "C:\Python34\lib\site-packages\py2exe\mf3.py", line 120, in import_hook
    module = self._gcd_import(name)
  File "C:\Python34\lib\site-packages\py2exe\mf3.py", line 274, in _gcd_import
    return self._find_and_load(name)
  File "C:\Python34\lib\site-packages\py2exe\mf3.py", line 337, in
_find_and_load
    raise ImportError(name)
ImportError: Tkinter
</code>```

I run this via the console using python.exe setup.py py2exe

The setup.py looks something like so:

from distutils.core import setup
import py2exe

```<code>setup(window=[{'script': 'filename.py'}], \
            options={"py2exe": {"includes": ["decimal", "Tkinter", \
            "tkFileDialog", "csv", "xml.dom.minidom", "os"], \
            'bundle_files': 3, 'compressed': False}}, \
            zipfile = None)

excludes = ["pywin", "pywin.debugger", "pywin.debugger.dbgcon",
             "pywin.dialogs", "pywin.dialogs.list",
             "Tkconstants","Tkinter","tcl", "_imagingtk", "PIL._imagingtk",
             "ImageTk", "PIL.ImageTk", "FixTk"
               ]
</code>```

Please help, I do not know what I am doing.

Thank you

答: I don't have enough reputation to add a comment, but the tkFiledialog error is similar to the Tkinter <--> tkinter error. In Python 3, you use import tkinter.filedialog as opposed to import tkFileDialog as in python 2.7

Body:
I was trying to compile my program using py2exe with the setup.py and all but whenever I try the console gives me this:

Traceback (most recent call last):
  File "setup.py", line 10, in <module>
zipfile = None)
  File "C:\Python34\lib\distutils\core.py", line 149, in setup
dist.run_commands()
  File "C:\Python34\lib\distutils\dist.py", line 955, in run_commands
self.run_command(cmd)
  File "C:\Python34\lib\distutils\dist.py", line 974, in run_command
cmd_obj.run()
  File "C:\Python34\lib\site-packages\py2exe\distutils_buildexe.py", line 188, in run
self._run()
  File "C:\Python34\lib\site-packages\py2exe\distutils_buildexe.py", line 267, in _run
builder.analyze()
  File "C:\Python34\lib\site-packages\py2exe\runtime.py", line 164, in analyze
mf.import_hook(modname)
  File "C:\Python34\lib\site-packages\py2exe\mf3.py", line 120, in import_hook
    module = self._gcd_import(name)
  File "C:\Python34\lib\site-packages\py2exe\mf3.py", line 274, in _gcd_import
    return self._find_and_load(name)
  File "C:\Python34\lib\site-packages\py2exe\mf3.py", line 337, in
_find_and_load
    raise ImportError(name)
ImportError: Tkinter

I run this via the console using python.exe setup.py py2exe

The setup.py looks something like so:

from distutils.core import setup
import py2exe

setup(window=[{'script': 'filename.py'}], \
            options={"py2exe": {"includes": ["decimal", "Tkinter", \
            "tkFileDialog", "csv", "xml.dom.minidom", "os"], \
            'bundle_files': 3, 'compressed': False}}, \
            zipfile = None)

excludes = ["pywin", "pywin.debugger", "pywin.debugger.dbgcon",
             "pywin.dialogs", "pywin.dialogs.list",
             "Tkconstants","Tkinter","tcl", "_imagingtk", "PIL._imagingtk",
             "ImageTk", "PIL.ImageTk", "FixTk"
               ]

Please help, I do not know what I am doing.

Thank you


问:
Scala conditional fold in Tuple(int,int)
I have a list of tuples (int,int) such as

(100,3), (130,3), (160,1), (180,2), (200,2)

I want to foldRight or something efficient where the neighbors are compared. For ((A1,A2),(B1,B2)), we do a merge only when A2 is less than or equal to B2. Otherwise, we do not fold the list at that instance. If we merge, we retain (A1,A2) and add a count field.
The sample output is

(100,3,2) and (160,1,3)

here 2 and 3 are the weight of the observations folded to this one observation.

(100,3), (130,3)

will lead to (100,3,2)

while

(160,1), (180,2), (200,2)

will lead to (160,1,3)

Any idea how to write it in scala functional style?

答:
```<code>scala>def conditionalFold(in: List[(Int, Int)]): List[(Int, Int, Int)] =
 |     in.foldLeft(Nil: List[(Int, Int, Int)]) { (acc, i) =>
 |       acc match {
 |         case Nil =>
 |           (i._1, i._2, 1) :: Nil
 |         case head :: tail =>
 |           if (i._2 >= head._2)
 |             (head._1, head._2, head._3 + 1) :: tail
 |           else
 |             (i._1, i._2, 1) :: head :: tail
 |       }
 |     }.reverse
conditionalFold: (in: List[(Int, Int)])List[(Int, Int, Int)]

scala>   println(conditionalFold(List((100, 3), (130, 3), (160, 1), (180, 2), (200, 2))))
List((100,3,2), (160,1,3))

scala>   println(conditionalFold(List((100,3), (130,3))))
List((100,3,2))

scala>   println(conditionalFold(List((160,1), (180,2), (200,2))))
List((160,1,3))
</code>```


问:
Why can't chef resolve my cookbooks?
Intro
I am learning Chef to automate the server management at work.
I downloaded chefdk 3.0 from  here
and now I am trying to build my first cookbook using chef.

Important
I am using this in a Windows environment for testing purpose, I do expect it to fail since Windows does not have iptables, but I do not expect it to fail saying that it can't find the cookbook. I've tried using Windows cookbook and it works.

The problem
I am able to create the cookbook and run it, but I am not able to reference dependencies from supermarket.

I have tried two alternatives:

Alternative 1

I used the following command to create the cookbook

```<code>chef generate cookbook learn_chef_httpd
</code>```

(from this tutorial)

I was able to complete the tutorial and now I would like to test referencing another cookbook, so I chose simple_iptables

I added this line

```<code>cookbook 'simple_iptables', '~> 0.7.0'
</code>```

To my Berksfile, as described in the Supermarket.

Then I added these lines to my default.rb file:

```<code>include_recipe 'simple_iptables'

# Allow HTTP, HTTPS
simple_iptables_rule "http" do
  rule [ "--proto tcp --dport 80",
         "--proto tcp --dport 443" ]
  jump "ACCEPT"
end
</code>```

And I run the cookbook using:

```<code>chef-client --local-mode --runlist 'recipe[learn_chef_httpd]'
</code>```

The problem is that Chef doesn't find the cookbook

```<code>Chef::Exceptions::CookbookNotFound
----------------------------------
Cookbook simple_iptables not found. If you're loading simple_iptables from anoth er cookbook, make sure you configure the dependency in your metadata
</code>```

I tried adding it to the metadata:

```<code>depends 'simple_iptables', '~> 0.7.0'
</code>```

But I still get an error:

```<code>Error Resolving Cookbooks for Run List:
Missing Cookbooks:

No such cookbook: simple_iptables
</code>```

Alternative 2

I am still trying to make it work so I also tried making it "the berkshelf way", so I created a new cookbook.

```<code>berks cookbook test
</code>```

And I added this line

```<code>cookbook 'simple_iptables', '~> 0.7.0'
</code>```

To my Berksfile, as described in the Supermarket.

Then I added these lines to my default.rb file:

```<code>include_recipe 'simple_iptables'

# Allow HTTP, HTTPS
simple_iptables_rule "http" do
  rule [ "--proto tcp --dport 80",
         "--proto tcp --dport 443" ]
  jump "ACCEPT"
end
</code>```

Executed berks install:

berks install

and ran it:

```<code>cookbook 'simple_iptables', '~> 0.7.0'
</code>```0

The same error came back

```<code>cookbook 'simple_iptables', '~> 0.7.0'
</code>```1

I tried adding it to the metadata:

```<code>cookbook 'simple_iptables', '~> 0.7.0'
</code>```2

But I still get an error:

```<code>Error Resolving Cookbooks for Run List:
Missing Cookbooks:

No such cookbook: simple_iptables
</code>```

I looked at the ~/berkshelf folder and the cookbooks are there.

** Alternative 3 **

I started a CentOS 6.5 EC2 instance on Amazon, installed Ruby 2.1.3 and Chef.
created a ~/chef-repo/cookbooks folder

I created a cookbook using berkshelf, ran

```<code>bundle install
</code>```

added the reference/code as in the other alterantives
then

```<code>berks install
</code>```

and ran the same way I did last time.

I got the same issues.

What am I missing? What do I need to make it work?

答:
While looking to run locally for testing I ran into the same "cannot resolve cookbook" error. Since I potentially want to run cookbooks without a Chef server but also without ChefDK installed for non-Chef developers to do a simple one time workstation setup, I put together the following workflow.

Your cookbook needs to live in a folder under a folder called cookbooks, this appears to be hardcoded "magic", but it seems to be able to live anywhere, eg userdir/projects/cookbooks/my_cookbook_name/.

If you have a Berksfile for the dependencies you need to get them locally before you can run chef-client -z -o my_cookbook_name so run berks vendor to pull the dependencies into a cookbooks directory in the current folder.

The berks vendor command pulls your other dependencies into the cookbooks directory so chef-zero/chef-solo can find them. Run the following in an Administrator PowerShell prompt, it may be Command Prompt compatible but I try not to encourage using cmd.exe.

cd /path/to/cookbooks/my_cookbook_name
berks vendor .
chef-client -z -o my_cookbook_name

The beauty of using the new chef-zero built into the client is you don't necessarily need the full ChefDK to test, though you will need berkshelf for the berks command on at least 1 machine as getting that installed without the ChefDK is a nightmare. Once you have berks you can run berks package and copy the file it creates to a machine with just the chef-client and extra it somewhere and then run the chef-client -z -o your_cookbook in the directory containing the cookbooks folder.

To get just chef use the omnibus installer and you have enough to bootstrap a node or run the recipe.

. { iwr -useb https://omnitruck.chef.io/install.ps1 } | iex; install -channel stable -project chef

If you need your berks and want a quick way to get the ChefDK, this will do the trick.

. { iwr -useb https://omnitruck.chef.io/install.ps1 } | iex; install -channel stable -project chefdk

Title: Why can't chef resolve my cookbooks?

Body:
Intro
I am learning Chef to automate the server management at work.
I downloaded chefdk 3.0 from  here
and now I am trying to build my first cookbook using chef.

Important
I am using this in a Windows environment for testing purpose, I do expect it to fail since Windows does not have iptables, but I do not expect it to fail saying that it can't find the cookbook. I've tried using Windows cookbook and it works.

The problem
I am able to create the cookbook and run it, but I am not able to reference dependencies from supermarket.

I have tried two alternatives:

Alternative 1

I used the following command to create the cookbook

chef generate cookbook learn_chef_httpd

(from this tutorial)

I was able to complete the tutorial and now I would like to test referencing another cookbook, so I chose simple_iptables

I added this line

cookbook 'simple_iptables', '~> 0.7.0'

To my Berksfile, as described in the Supermarket.

Then I added these lines to my default.rb file:

include_recipe 'simple_iptables'

# Allow HTTP, HTTPS
simple_iptables_rule "http" do
  rule [ "--proto tcp --dport 80",
         "--proto tcp --dport 443" ]
  jump "ACCEPT"
end

And I run the cookbook using:

chef-client --local-mode --runlist 'recipe[learn_chef_httpd]'

The problem is that Chef doesn't find the cookbook

Chef::Exceptions::CookbookNotFound
----------------------------------
Cookbook simple_iptables not found. If you're loading simple_iptables from anoth er cookbook, make sure you configure the dependency in your metadata

I tried adding it to the metadata:

depends 'simple_iptables', '~> 0.7.0'

But I still get an error:

Error Resolving Cookbooks for Run List:
Missing Cookbooks:

No such cookbook: simple_iptables

Alternative 2

I am still trying to make it work so I also tried making it "the berkshelf way", so I created a new cookbook.

berks cookbook test

And I added this line

cookbook 'simple_iptables', '~> 0.7.0'

To my Berksfile, as described in the Supermarket.

Then I added these lines to my default.rb file:

include_recipe 'simple_iptables'

# Allow HTTP, HTTPS
simple_iptables_rule "http" do
  rule [ "--proto tcp --dport 80",
         "--proto tcp --dport 443" ]
  jump "ACCEPT"
end

Executed berks install:

berks install

and ran it:

chef-client --local-mode --runlist 'recipe[test]'

The same error came back

Chef::Exceptions::CookbookNotFound
----------------------------------
Cookbook simple_iptables not found. If you're loading simple_iptables from anoth er cookbook, make sure you configure the dependency in your metadata

I tried adding it to the metadata:

depends 'simple_iptables', '~> 0.7.0'

But I still get an error:

Error Resolving Cookbooks for Run List:
Missing Cookbooks:

No such cookbook: simple_iptables

I looked at the ~/berkshelf folder and the cookbooks are there.

** Alternative 3 **

I started a CentOS 6.5 EC2 instance on Amazon, installed Ruby 2.1.3 and Chef.
created a ~/chef-repo/cookbooks folder

I created a cookbook using berkshelf, ran

bundle install

added the reference/code as in the other alterantives
then

berks install

and ran the same way I did last time.

I got the same issues.

What am I missing? What do I need to make it work?


问:
MFC dialog window does not appear
I am just learning to create MFC applications in visual studio 2017. I have made a new default project of MFC dialog based application. After completing the steps of MFC application wizard, visual studio shows up to this:

.

At this point I have not changed any of the code or settings.

Now how do I get the dialog window as shown in:

I have tried rebuilding the solution, but it does not work.

答:
I am not sure if I am answering correctly.

Click on the View menu.

Then click on Other Views.

Now click Resource View

Or press Ctrl + Shift + E

Now you have the Resource View:

If you click that you see all resources:

That is how you get to your dialogues.

If you have created a secondary dialog and you want that to start instead of the default, then look at my answer here about using InitInstance.

Title: MFC dialog window does not appear