问:
jQuery slide is jumpy
I tried to slide in and out a DIV with the toggle function of jQuery but the result is always jumpy at the start and/or end of the animation. Here's the js code that I use:

```<code>$(document).ready(function(){
    $('#link1').click(
        function() {
            $('#note_1').parent().slideToggle(5000);
        }
);
</code>```

And the HTML:

```<code><div class="notice">
    <p>Here's some text. And more text. <span id="link1">Test1</span></p>
    <div class="wrapper">
        <div id="note_1">
            <p>Some content</p>
            <p>More blalba</p>
        </div>
    </div>
</div>
</code>```

You can also see the complete example here: jQuery Slide test

I usually use Mootools and I can do this slide without any problems with it. But I'm starting a new project in Django and most app in Django use jQuery. So for that and after reading this jQuery vs Mootools I decided that will be a good occasion to start using jQuery. So my first need was to slide this DIV. And it didn't work properly.

I did more search and I found that's an old bug in jQuery with margin and padding applied to the DIV. The solution is to wrap the DIV in another DIV. It didn't fix the thing in my case.

Searching further I found this post Slidedown animation jumprevisited. It fix a jump at one end but not at the other (Test2 in jQuery Slide test).

On Stack Overflow I found this jQuery IE jerky slide animation. In the comments I saw that the problem is with the P tag inside the DIV. If I replace the P tags with DIV tags that fix the problem but that's not a proper solution.

Lastly I found this Weird jQuery behavior slide. Reading it I understood that the problem resolved by switching from P tag to DIV was with the margins of the P (not present in the DIV) and the collapsing of margins between elements. So if I switch the margins to paddings it fix the problem. But I loose the collapsing behavior of margins, collapsing that I want.

Honestly I can say that my first experience with jQuery is not really good. If I want to use one of the simplest effect in jQuery I have to not use the proper function (slideToggle) but instead use some hand made code AND wrap the DIV in another DIV AND switch margins to paddings, messing my layout.

Did I miss a simpler solution ?

As krdluzni suggest, I tried to write as custom script with the animate method. Here's my code:

```<code>var $div = $('#note_2').parent();
var height = $div.height();

$('#link2').click(
    function () {
        if ( $div.height() > 0 ) {
            $div.animate({ height: 0 }, { duration: 5000 }).css('overflow', 'hidden');
        } else {
            $div.animate({ height : height }, { duration: 5000 });
        }

        return false;
});
</code>```

But that doesn't work either because jQuery always set the overflow to visible at the end of the animation. So the DIV is reapearing at the end of the animation but overlaid on the rest of the content.

I tried also with UI.Slide (and Scale and Size). It works but the content below the DIV doesn't move with the animation. It only jump at the end/start of the animation to fill the gap. I don't want that.

UPDATE:

One part of the solution is to set the height of the container DIV dynamically before anything. This solve one jumping. But not the one cause by collapsing margin. Here's the code:

```<code>var parent_div = $("#note_1").parent();
parent_div.css("height", parent_div.height()+"px");
parent_div.hide();
</code>```

SECOND UPDATE:

You can see the bug on the jQuery own site at this page (Example B):
Tutorials:Live Examples of jQuery

THIRD UPDATE:

Tried with jQuery 1.4, no more chance :-(

答:
For me the solution was, that i had a CSS style definition like following:

```<code>* {
    transition: all .3s;
}
</code>```

Removing this was the solution!

Title: jQuery slide is jumpy

Body:
I tried to slide in and out a DIV with the toggle function of jQuery but the result is always jumpy at the start and/or end of the animation. Here's the js code that I use:

$(document).ready(function(){
    $('#link1').click(
        function() {
            $('#note_1').parent().slideToggle(5000);
        }
);

And the HTML:

Here's some text. And more text. Test1

Some content

More blalba

You can also see the complete example here: jQuery Slide test

I usually use Mootools and I can do this slide without any problems with it. But I'm starting a new project in Django and most app in Django use jQuery. So for that and after reading this jQuery vs Mootools I decided that will be a good occasion to start using jQuery. So my first need was to slide this DIV. And it didn't work properly.

I did more search and I found that's an old bug in jQuery with margin and padding applied to the DIV. The solution is to wrap the DIV in another DIV. It didn't fix the thing in my case.

Searching further I found this post Slidedown animation jumprevisited. It fix a jump at one end but not at the other (Test2 in jQuery Slide test).

On Stack Overflow I found this jQuery IE jerky slide animation. In the comments I saw that the problem is with the P tag inside the DIV. If I replace the P tags with DIV tags that fix the problem but that's not a proper solution.

Lastly I found this Weird jQuery behavior slide. Reading it I understood that the problem resolved by switching from P tag to DIV was with the margins of the P (not present in the DIV) and the collapsing of margins between elements. So if I switch the margins to paddings it fix the problem. But I loose the collapsing behavior of margins, collapsing that I want.

Honestly I can say that my first experience with jQuery is not really good. If I want to use one of the simplest effect in jQuery I have to not use the proper function (slideToggle) but instead use some hand made code AND wrap the DIV in another DIV AND switch margins to paddings, messing my layout.

Did I miss a simpler solution ?

As krdluzni suggest, I tried to write as custom script with the animate method. Here's my code:

var $div = $('#note_2').parent();
var height = $div.height();

$('#link2').click(
    function () {
        if ( $div.height() > 0 ) {
            $div.animate({ height: 0 }, { duration: 5000 }).css('overflow', 'hidden');
        } else {
            $div.animate({ height : height }, { duration: 5000 });
        }

        return false;
});

But that doesn't work either because jQuery always set the overflow to visible at the end of the animation. So the DIV is reapearing at the end of the animation but overlaid on the rest of the content.

I tried also with UI.Slide (and Scale and Size). It works but the content below the DIV doesn't move with the animation. It only jump at the end/start of the animation to fill the gap. I don't want that.

UPDATE:

One part of the solution is to set the height of the container DIV dynamically before anything. This solve one jumping. But not the one cause by collapsing margin. Here's the code:

var parent_div = $("#note_1").parent();
parent_div.css("height", parent_div.height()+"px");
parent_div.hide();

SECOND UPDATE:

You can see the bug on the jQuery own site at this page (Example B):
Tutorials:Live Examples of jQuery

THIRD UPDATE:

Tried with jQuery 1.4, no more chance :-(

Body:
For me the solution was, that i had a CSS style definition like following:

* {
    transition: all .3s;
}

Removing this was the solution!


来源: stackexchange

问:
Max difference between two adjacent values in an array, C
I want to find the max difference between two adjacent values in an array.For instance, for array int tab[6] = {1,2,8,4,5,6}; the maximum difference is 6, because of the difference between 8 and 2. Remaining differences are equal to 1. So, the result of my program should be 6. However, my program prints 1 and I do not know where's the problem:

```<code>#include <stdio.h>

int main(int argc, char **argv)
{
    int n = 6;
    int tab[6] = {1,2,8,4,5,6};
    int diff = tab[1] - tab[0], maxdiff = diff, i;

    for(i=2; i<n-1; i++)
    {
        if(diff > maxdiff)
            maxdiff = diff;

        diff = tab[i] - tab[i-1];
    }

    printf("%d\n", diff);

    return 0;
}
</code>```

答:
There's two problems. First, you're printing diff instead of maxdiff. So you're getting the result of the last diff, not the max.

Second, you're not taking the absolute value. That means {8,2,4} would result in 2, not 6.

Finally, though this isn't a bug, a bunch of duplication can be removed by starting with maxdiff = 0.

And a style note: declaring multiple variables on one line is hard to read. Declaring and initializing them on one line is very hard to read. Don't do it.

```<code>#include <stdio.h>
#include <stdlib.h>

int main() {
    int n = 6;
    int tab[] = {1,2,8,4,5,6};
    int maxdiff = 0;

    for(int i=1; i < n; i++) {
        int diff = abs(tab[i] - tab[i-1]);
        if(diff > maxdiff) {
            maxdiff = diff;
        }
    }

    printf("%d\n", maxdiff);

    return 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to find the max difference between two adjacent values in an array.For instance, for array int tab[6] = {1,2,8,4,5,6}; the maximum difference is 6, because of the difference between 8 and 2. Remaining differences are equal to 1. So, the result of my program should be 6. However, my program prints 1 and I do not know where's the problem:

#include <stdio.h>

int main(int argc, char **argv)
{
    int n = 6;
    int tab[6] = {1,2,8,4,5,6};
    int diff = tab[1] - tab[0], maxdiff = diff, i;

    for(i=2; i<n-1; i++)
    {
        if(diff > maxdiff)
            maxdiff = diff;

        diff = tab[i] - tab[i-1];
    }

    printf("%d\n", diff);

    return 0;
}

Body:
There's two problems. First, you're printing diff instead of maxdiff. So you're getting the result of the last diff, not the max.

Second, you're not taking the absolute value. That means {8,2,4} would result in 2, not 6.

Finally, though this isn't a bug, a bunch of duplication can be removed by starting with maxdiff = 0.

And a style note: declaring multiple variables on one line is hard to read. Declaring and initializing them on one line is very hard to read. Don't do it.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int n = 6;
    int tab[] = {1,2,8,4,5,6};
    int maxdiff = 0;

    for(int i=1; i < n; i++) {
        int diff = abs(tab[i] - tab[i-1]);
        if(diff > maxdiff) {
            maxdiff = diff;
        }
    }

    printf("%d\n", maxdiff);

    return 0;
}


问:
Convert data with one column and multiple rows into multi column multi row data
I have an output of web scraped data in R which looks as follows

```<code>Name1
Email: email1@xyz.com
City/Town: Location1
Name2
Email: email2@abc.com
City/Town: Location2
Name3
Email: email3@pqr.com
City/Town: Location3
</code>```

Some names may not have email or location. I want convert above data into tabular format. The output should look like

```<code>Name      Email           City/Town
Name1   email1@xyz.com  Location1
Name2   email2@abc.com  Location2
Name3   email3@pqr.com  Location3
Name4                   Location4
Name5   email5@abc.com
</code>```

答:
Benchmarks:

Code:

```<code>txt2 <- c("John Doe", "Email: email1@xyz.com", "Email: email1@abc.com", "City/Town: Location1", "Save the World Fund",
          "Email: email2@abc.com", "City/Town: Location2", "Best Shoes Ltd.", "Email: email3@pqr.com",
          "City/Town: Location3", "Mother", "City/Town: Location4", "City/Town: everywhere", "Jane",
          "Email: email5@abc.com")

library(microbenchmark)
library(data.table)
library(dplyr)
library(tidyr)

microbenchmark(ans.uwe = data.table(text = txt2)[, tstrsplit(text, ": ")
                                                 ][is.na(V2), Name := V1
                                                   ][, Name := zoo::na.locf(Name)
                                                     ][!is.na(V2), dcast(.SD, Name ~ V1, fun = toString, value.var = "V2")],
               ans.zx8754 = data_frame(txt = txt2) %>%
                 mutate(txt = ifelse(grepl(":", txt), txt, paste("Name:", txt)),
                        rn = row_number()) %>%
                 separate(txt, into = c("mytype", "mytext"), sep = ":") %>%
                 spread(key = mytype, value = mytext) %>%
                 select(-rn) %>%
                 fill(Name) %>%
                 group_by(Name) %>%
                 fill(1:2, .direction = "down") %>%
                 fill(1:2, .direction = "up") %>%
                 unique() %>%
                 ungroup() %>%
                 select(3:1),
               ans.jaap = data.table(txt = txt2)[!grepl(':', txt), name := txt
                                                 ][, name := zoo::na.locf(name)
                                                   ][grepl('^Email:', txt), email := sub('Email: ','',txt)
                                                     ][grepl('^City/Town:', txt), city_town := sub('City/Town: ','',txt)
                                                       ][txt != name, lapply(.SD, function(x) toString(na.omit(x))), by = name, .SDcols = c('email','city_town')],
               ans.G.Grothendieck = {
                 L <- trimws(readLines(textConnection(txt2)))
                 ix <- !grepl(":", L)
                 L[ix] <- paste("\nName:", L[ix])
                 read.dcf(textConnection(L))},
               times = 1000)
</code>```

Result:

```<code>Unit: microseconds
               expr       min         lq       mean     median        uq        max neval  cld
            ans.uwe  4243.754  4885.4765  5305.8688  5139.0580  5390.360  92604.820  1000   c
         ans.zx8754 39683.911 41771.2925 43940.7646 43168.4870 45291.504 130965.088  1000    d
           ans.jaap  2153.521  2488.0665  2788.8250  2640.1580  2773.150  91862.177  1000  b
 ans.G.Grothendieck   266.268   304.0415   332.6255   331.8375   349.797    721.261  1000 a
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an output of web scraped data in R which looks as follows

Name1
Email: email1@xyz.com
City/Town: Location1
Name2
Email: email2@abc.com
City/Town: Location2
Name3
Email: email3@pqr.com
City/Town: Location3

Some names may not have email or location. I want convert above data into tabular format. The output should look like

Name      Email           City/Town
Name1   email1@xyz.com  Location1
Name2   email2@abc.com  Location2
Name3   email3@pqr.com  Location3
Name4                   Location4
Name5   email5@abc.com

Body:
Benchmarks:

Code:

txt2 <- c("John Doe", "Email: email1@xyz.com", "Email: email1@abc.com", "City/Town: Location1", "Save the World Fund",
          "Email: email2@abc.com", "City/Town: Location2", "Best Shoes Ltd.", "Email: email3@pqr.com",
          "City/Town: Location3", "Mother", "City/Town: Location4", "City/Town: everywhere", "Jane",
          "Email: email5@abc.com")

library(microbenchmark)
library(data.table)
library(dplyr)
library(tidyr)

microbenchmark(ans.uwe = data.table(text = txt2)[, tstrsplit(text, ": ")
                                                 ][is.na(V2), Name := V1
                                                   ][, Name := zoo::na.locf(Name)
                                                     ][!is.na(V2), dcast(.SD, Name ~ V1, fun = toString, value.var = "V2")],
               ans.zx8754 = data_frame(txt = txt2) %>%
                 mutate(txt = ifelse(grepl(":", txt), txt, paste("Name:", txt)),
                        rn = row_number()) %>%
                 separate(txt, into = c("mytype", "mytext"), sep = ":") %>%
                 spread(key = mytype, value = mytext) %>%
                 select(-rn) %>%
                 fill(Name) %>%
                 group_by(Name) %>%
                 fill(1:2, .direction = "down") %>%
                 fill(1:2, .direction = "up") %>%
                 unique() %>%
                 ungroup() %>%
                 select(3:1),
               ans.jaap = data.table(txt = txt2)[!grepl(':', txt), name := txt
                                                 ][, name := zoo::na.locf(name)
                                                   ][grepl('^Email:', txt), email := sub('Email: ','',txt)
                                                     ][grepl('^City/Town:', txt), city_town := sub('City/Town: ','',txt)
                                                       ][txt != name, lapply(.SD, function(x) toString(na.omit(x))), by = name, .SDcols = c('email','city_town')],
               ans.G.Grothendieck = {
                 L <- trimws(readLines(textConnection(txt2)))
                 ix <- !grepl(":", L)
                 L[ix] <- paste("\nName:", L[ix])
                 read.dcf(textConnection(L))},
               times = 1000)

Result:

Unit: microseconds
               expr       min         lq       mean     median        uq        max neval  cld
            ans.uwe  4243.754  4885.4765  5305.8688  5139.0580  5390.360  92604.820  1000   c
         ans.zx8754 39683.911 41771.2925 43940.7646 43168.4870 45291.504 130965.088  1000    d
           ans.jaap  2153.521  2488.0665  2788.8250  2640.1580  2773.150  91862.177  1000  b
 ans.G.Grothendieck   266.268   304.0415   332.6255   331.8375   349.797    721.261  1000 a


问:
Apollo GraphQL server: In resolvers, get variables from several levels higher
Say in my resolvers I have the following:

```<code>Query: {
  author: (root, args) => API.getAuthor(args.authorId),
},
Author: {
  book: (author, args) => API.getBook(author.id, args.bookId),
},
Book: {
  // Here, I can't get the author ID
  chapter: (book, args) => API.getChapter(authorId???, book.id, args.chapterId),
}
</code>```

My problem is pretty clear from the above example, how can I access variables from several levels higher?
I'd like to be able to make a request like the following:

```<code>author(authorId: 1) {
  id
  book(bookId: 31) {
    id
    chapter(chapterId: 3) {
      content
    }
  }
}
</code>```

And my connector to get a specific chapter also need the author's ID.

答:
You can't access variables from levels higher in GraphQL.

This is intended : because the Book entity can also be included in others objects. Right now, you have author { book { chapter } }, but you could also have library { book { chapter } }, where the author field would not present in the query, thus making the author.id variable inaccessible.

Each object is responsible for fetching his fields with his own data, which makes the whole thing composable.

What you could do, though, is extending the response of the API.getBooks function, to add the author_id field to the returned object. This way, you will be able to access it inside your Book entity : book.authorId.

```<code>function myGetBook(authorId, bookId) {
  return API.getBook(authorId, bookId)
    .then(book => {
      return Object.assign(
        {},
        theBook,
        { authorId }
      );
    });
}
</code>```

And then:

```<code>Author: {
  book: (author, args) => myGetBook(author.id, args.bookId),
},
Book: {
  chapter: (book, args) => API.getChapter(book.authorId, book.id, args.chapterId),
}
</code>```

Body:
Say in my resolvers I have the following:

Query: {
  author: (root, args) => API.getAuthor(args.authorId),
},
Author: {
  book: (author, args) => API.getBook(author.id, args.bookId),
},
Book: {
  // Here, I can't get the author ID
  chapter: (book, args) => API.getChapter(authorId???, book.id, args.chapterId),
}

My problem is pretty clear from the above example, how can I access variables from several levels higher?
I'd like to be able to make a request like the following:

author(authorId: 1) {
  id
  book(bookId: 31) {
    id
    chapter(chapterId: 3) {
      content
    }
  }
}

And my connector to get a specific chapter also need the author's ID.

Body:
You can't access variables from levels higher in GraphQL.

This is intended : because the Book entity can also be included in others objects. Right now, you have author { book { chapter } }, but you could also have library { book { chapter } }, where the author field would not present in the query, thus making the author.id variable inaccessible.

Each object is responsible for fetching his fields with his own data, which makes the whole thing composable.

What you could do, though, is extending the response of the API.getBooks function, to add the author_id field to the returned object. This way, you will be able to access it inside your Book entity : book.authorId.

function myGetBook(authorId, bookId) {
  return API.getBook(authorId, bookId)
    .then(book => {
      return Object.assign(
        {},
        theBook,
        { authorId }
      );
    });
}

And then:

Author: {
  book: (author, args) => myGetBook(author.id, args.bookId),
},
Book: {
  chapter: (book, args) => API.getChapter(book.authorId, book.id, args.chapterId),
}


问:
Increase or decrease parent div height based on the changes in the children element
https://jsfiddle.net/9b90twgf/15/

 $("#add").on("click",function(){
var top = parseInt($("#parentDiv .childDiv:last").css("top").split("px")[0])+90;

$("#parentDiv").append("
divvvvvv
");
});

 $("#remove").on("click",function(){
$("#parentDiv .childDiv:last").remove();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  #parentDiv
     {
      background: antiquewhite;
      }
     .childDiv
     {
     background: yellow;
      width: 700px;
      height: 50px;
      }</code>```

<button id="add">add</button><button id="remove">remove</button>

    Div one

    div two

   div three

```

I have one parent div, under this I will append and remove HTML elements as children, if I remove children element parent div have to shrink its height automatically and if I add it have to expand automatically, my requirement is both parent and children must have position absolute(style="position:absolute")

答:
$("#add").on("click", function() {
  addChild();
  calculateParentHeight();
});

$("#remove").on("click", function() {
  $(".parent .child:last").remove();
  calculateParentHeight();
});

function calculateParentHeight() {
  var height = 0;

  $('.parent .child').each(function() {
    height = height + $(this).height();
  });

  $('.parent').css('height', height + 20 + 'px');
}

calculateParentHeight();

function addChild() {
  var top = 0;

  $('.parent .child').each(function() {
    top = top + $(this).height();
  });

  $(".parent").append("
divvvvvv
");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
}

.parent {
  position: absolute;
  background: antiquewhite;
  width: 300px;
}

.child {
  position: absolute;
  background: yellow;
  width: calc(100% - 20px);
  height: 50px;
  margin: 10px;
}</code>```

<button id="add">add</button>
<button id="remove">remove</button>

    Div one

    div two

    div three

```

Body:
https://jsfiddle.net/9b90twgf/15/

 $("#add").on("click",function(){
var top = parseInt($("#parentDiv .childDiv:last").css("top").split("px")[0])+90;

$("#parentDiv").append("
divvvvvv
");
});

 $("#remove").on("click",function(){
$("#parentDiv .childDiv:last").remove();
});

  #parentDiv
     {
      background: antiquewhite;
      }
     .childDiv
     {
     background: yellow;
      width: 700px;
      height: 50px;
      }

<button id="add">add</button><button id="remove">remove</button>

    Div one

    div two

   div three

I have one parent div, under this I will append and remove HTML elements as children, if I remove children element parent div have to shrink its height automatically and if I add it have to expand automatically, my requirement is both parent and children must have position absolute(style="position:absolute")

Body:
$("#add").on("click", function() {
  addChild();
  calculateParentHeight();
});

$("#remove").on("click", function() {
  $(".parent .child:last").remove();
  calculateParentHeight();
});

function calculateParentHeight() {
  var height = 0;

  $('.parent .child').each(function() {
    height = height + $(this).height();
  });

  $('.parent').css('height', height + 20 + 'px');
}

calculateParentHeight();

function addChild() {
  var top = 0;

  $('.parent .child').each(function() {
    top = top + $(this).height();
  });

  $(".parent").append("<div class='child' style='top:" + top + "px;'>divvvvvv</div>");
}

* {
  box-sizing: border-box;
}

.parent {
  position: absolute;
  background: antiquewhite;
  width: 300px;
}

.child {
  position: absolute;
  background: yellow;
  width: calc(100% - 20px);
  height: 50px;
  margin: 10px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="add">add</button>
<button id="remove">remove</button>

<div class="parent">
  <div class="child" style="position: absolute;">
    Div one
  </div>

  <div class="child" style="position: absolute; top: 50px;">
    div two
  </div>
  <div class="child" style="position: absolute; top: 100px;">
    div three
  </div>
</div>


问:
Pigeon function: where to insert x into a sorted list
Suppose I have a sorted list of things

```<code>{thing1, thing2, thing3, ...}
</code>```

and a binary comparison function that says whether one thing should come before another in that sort order.  (I say "things" because they need not be numbers; they can be arbitrary data structures.)

I now seek a function that takes

a sorted list of things,

a comparison function, and

a thing

and returns the first pair of adjacent things in the list that the new thing should be inserted between.
That is, return the first adjacent pair {a,b} such that comp(a,x) and comp(x,b) are true, where comp() is the comparison function.

For example,

```<code>pigeon[{1,3,5,7}, Less, 4]
</code>```

should return

```<code>{3,5}
</code>```

(EDIT: If the given thing is less than the first element, a, of the list, then return {Null, a}.  Likewise, if it's greater than the last element, z, then return {z, Null}.  Additionally, we need to either assume that the comparison function returns true for two identical elements (ie, it's like LessEqual rather than Less) or that the list of things doesn't contain the thing being pigeoned.  Thanks to High Performance Mark for catching that!)

My first thought was to use Split and then take the Last and First, respectively, of the resulting two sublists.
I'll post that as an answer (or feel free to beat me to it) but I imagine there's a more efficient or elegant way.

答:
Here's a solution using Select (note the third argument) that takes at most one pass through the list, stopping when it finds the pigeonhole:

```<code>pigeon[l_, f_, x_] := Module[{p, r},
  p = Null;
  r = Select[l, If[f[x,#], True, p = #; False]&, 1];
  If[r==={}, {Last@l, Null}, {p, First@r}]]
</code>```

Examples:

```<code>> pigeon[{1,3,5,7}, LessEqual, 4]
{3, 5}

> pigeon[{1,3,5,7}, LessEqual, 0]
{Null, 1}

> pigeon[{1,3,5,7}, LessEqual, 9]
{7, Null}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Suppose I have a sorted list of things

{thing1, thing2, thing3, ...}

and a binary comparison function that says whether one thing should come before another in that sort order.  (I say "things" because they need not be numbers; they can be arbitrary data structures.)

I now seek a function that takes

a sorted list of things,

a comparison function, and

a thing

and returns the first pair of adjacent things in the list that the new thing should be inserted between.
That is, return the first adjacent pair {a,b} such that comp(a,x) and comp(x,b) are true, where comp() is the comparison function.

For example,

pigeon[{1,3,5,7}, Less, 4]

should return

{3,5}

(EDIT: If the given thing is less than the first element, a, of the list, then return {Null, a}.  Likewise, if it's greater than the last element, z, then return {z, Null}.  Additionally, we need to either assume that the comparison function returns true for two identical elements (ie, it's like LessEqual rather than Less) or that the list of things doesn't contain the thing being pigeoned.  Thanks to High Performance Mark for catching that!)

My first thought was to use Split and then take the Last and First, respectively, of the resulting two sublists.
I'll post that as an answer (or feel free to beat me to it) but I imagine there's a more efficient or elegant way.

Body:
Here's a solution using Select (note the third argument) that takes at most one pass through the list, stopping when it finds the pigeonhole:

pigeon[l_, f_, x_] := Module[{p, r},
  p = Null;
  r = Select[l, If[f[x,#], True, p = #; False]&, 1];
  If[r==={}, {Last@l, Null}, {p, First@r}]]

Examples:

> pigeon[{1,3,5,7}, LessEqual, 4]
{3, 5}

> pigeon[{1,3,5,7}, LessEqual, 0]
{Null, 1}

> pigeon[{1,3,5,7}, LessEqual, 9]
{7, Null}


问:
@HostListener cause change detection triggers too many times when I'm listening for outside click
I have next template of root component, that draws 9 tiles:

```<code><ul>
  <li *ngFor="let x of [0,1,2,3,4,5,6,7,8]">
    <tile></tile>
  </li>
</ul>
</code>```

and next tile component, where I added HostListener for document click:

```<code>import {AfterViewChecked, Component, HostListener} from '@angular/core';

@Component({
  selector: 'tile',
  template: '<p>tile works!</p>'
})
export class TileComponent implements AfterViewChecked {

  ngAfterViewChecked(): void {
    console.log('checked');
  }

  @HostListener('document:click', ['$event'])
  onOutsideClick(event: any): void {
      // do nothing ...
  }

}
</code>```

Plunker: http://plnkr.co/edit/7wvon25LhXkHQiMcwh48?p=preview

When I run this I see that on each click change detection was called 9^2 times:

I can't understand why.

Can somebody explain to me why change detection triggers n^2 times in this case?

答:
Short answer - That is by design.

Since we have a click handler, angular triggers change detection after handler been called.

So, when the first component handles click it cause change detection. Then all the components print "checked".

And that repeated for each component, so I've got 9^2 prints "checked."

And one additional note that OnPush strategy will not help to reduce an amount of prints.

Body:
I have next template of root component, that draws 9 tiles:

    <tile></tile>

and next tile component, where I added HostListener for document click:

import {AfterViewChecked, Component, HostListener} from '@angular/core';

@Component({
  selector: 'tile',
  template: '
tile works!
'
})
export class TileComponent implements AfterViewChecked {

  ngAfterViewChecked(): void {
    console.log('checked');
  }

  @HostListener('document:click', ['$event'])
  onOutsideClick(event: any): void {
      // do nothing ...
  }

}

Plunker: http://plnkr.co/edit/7wvon25LhXkHQiMcwh48?p=preview

When I run this I see that on each click change detection was called 9^2 times:

I can't understand why.

Can somebody explain to me why change detection triggers n^2 times in this case?


问:
Listing files from folder and creating data frame
HI i am trying to combine data frames one after other

```<code>df1                                df1
name    address                     age        Gender
A         NY                         23        M
B         CA                         22        F
                                     33        M
                                     39        F
</code>```

I am trying to combine both the data frames with below code which is not giving required output

```<code>folder <- "path/"      # path to folder shows multiple .csv files
file_list <- list.files(path=folder, pattern="*.csv") # create list of all .csv files in folder

all_df <-
  do.call("cbind",
          lapply(file_list, function(x)  read.csv(paste(folder, x, sep=''), stringsAsFactors = FALSE)))
</code>```

O/p

```<code>all_df
 name    address   age        Gender
    A         NY    23        M
    B         CA    22        F
                    33        M
                    39        F
</code>```

答:
We can use cbind.fill from rowr

```<code>library(rowr)
cbind.fill(df1, df2, fill="")
#   name address age Gender
#1    A      NY  23      M
#2    B      CA  22      F
#3               33      M
#4               39      F
</code>```

If we want to modify the original code of the OP

```<code>do.call(cbind.fill,
      lapply(file_list, function(x)  read.csv(paste(folder, x, sep=''), stringsAsFactors = FALSE)))
</code>```

Body:
HI i am trying to combine data frames one after other

df1                                df1
name    address                     age        Gender
A         NY                         23        M
B         CA                         22        F
                                     33        M
                                     39        F

I am trying to combine both the data frames with below code which is not giving required output

folder <- "path/"      # path to folder shows multiple .csv files
file_list <- list.files(path=folder, pattern="*.csv") # create list of all .csv files in folder

all_df <-
  do.call("cbind",
          lapply(file_list, function(x)  read.csv(paste(folder, x, sep=''), stringsAsFactors = FALSE)))

O/p

all_df
 name    address   age        Gender
    A         NY    23        M
    B         CA    22        F
                    33        M
                    39        F

Body:
We can use cbind.fill from rowr

library(rowr)
cbind.fill(df1, df2, fill="")
#   name address age Gender
#1    A      NY  23      M
#2    B      CA  22      F
#3               33      M
#4               39      F

If we want to modify the original code of the OP

do.call(cbind.fill,
      lapply(file_list, function(x)  read.csv(paste(folder, x, sep=''), stringsAsFactors = FALSE)))


问:
Php and SQL issued with foreach
I have this following warning :

Warning: Invalid argument supplied for foreach()

Because my function return false , but i don't understand why it returns false

There is the function :

```<code>function getPlayerId($pseudo){

    $bdd=getBDD();

    $thisPlayerId= $bdd->query('SELECT users.id FROM users WHERE users.pseudo='.$pseudo);

    return $thisPlayerId;

}
</code>```

and there is the call :

```<code>$thisPlayerID = getPlayerId("test");

//var_dump(isset($thisPlayerID));

foreach ($thisPlayerID as $r3){
    echo $r['id'].'<br>';
}
</code>```

答:
Your function returns false because the query is invalid and fails:

```<code>'SELECT users.id FROM users WHERE users.pseudo='.$pseudo
</code>```

$pseudo is a string so it should have been escaped and quoted. Before PDO and mysqli.

Now you should use a prepared statement:

```<code>'SELECT users.id FROM users WHERE users.pseudo=?'
</code>```

and bind your value to the placeholder.

As both mysqli and PDO return objects that implement Traversable, you can loop over the resulting object without any problems to get your rows.

Title: Php and SQL issued with foreach

Body:
I have this following warning :

Warning: Invalid argument supplied for foreach()

Because my function return false , but i don't understand why it returns false

There is the function :

function getPlayerId($pseudo){

    $bdd=getBDD();

    $thisPlayerId= $bdd->query('SELECT users.id FROM users WHERE users.pseudo='.$pseudo);

    return $thisPlayerId;

}

and there is the call :

$thisPlayerID = getPlayerId("test");

//var_dump(isset($thisPlayerID));

foreach ($thisPlayerID as $r3){
    echo $r['id'].'
';
}

Body:
Your function returns false because the query is invalid and fails:

'SELECT users.id FROM users WHERE users.pseudo='.$pseudo

$pseudo is a string so it should have been escaped and quoted. Before PDO and mysqli.

Now you should use a prepared statement:

'SELECT users.id FROM users WHERE users.pseudo=?'

and bind your value to the placeholder.

As both mysqli and PDO return objects that implement Traversable, you can loop over the resulting object without any problems to get your rows.


问:
Converting a code from dplyr to base R
I have to convert a two sets of code designed for dplyr into base R code as a package I use does not support dplyr. My code is below. Could anybody help converting it? I am not very experienced with base R. </p>

```<code>#Annual average
riverObs %>%
  filter(!is.na(Qobs)) %>%
  mutate(year = lubridate::year(date)) %>%
  group_by(year) %>%
  mutate(s1 = Qsim-Qobs,
         s2 = abs(s1),
         s3 = sum(s2),
         s4 = sum(Qobs),
         s5 = s3/s4,
         s6 = 1-s5) %>%
  summarise(AAVE = mean(s6))

#Annual peak error, Qobs
riverObs %>%
  filter(!is.na(Qobs)) %>%
  mutate(year = lubridate::year(date)) %>%
  group_by(year) %>%
  filter(Qobs == max(Qobs)) %>%
  select(year, Qobs) %>%
  ungroup
</code>```

答:
From your comments, I assume that the following is your problem: You can't use dplyr together with hydromad because there are collisions between the two packages. E.g. there are functions with the same name in both packages.

One way to work around this issue is to, instead of loading dplyr, call its functions as follows: dplyr::filter, dplyr::select, etc. One thing you do have to account for is that to use the pipe %>% you would have to load the magrittr package.

Title: Converting a code from dplyr to base R

Body:
I have to convert a two sets of code designed for dplyr into base R code as a package I use does not support dplyr. My code is below. Could anybody help converting it? I am not very experienced with base R.

#Annual average
riverObs %>%
  filter(!is.na(Qobs)) %>%
  mutate(year = lubridate::year(date)) %>%
  group_by(year) %>%
  mutate(s1 = Qsim-Qobs,
         s2 = abs(s1),
         s3 = sum(s2),
         s4 = sum(Qobs),
         s5 = s3/s4,
         s6 = 1-s5) %>%
  summarise(AAVE = mean(s6))

#Annual peak error, Qobs
riverObs %>%
  filter(!is.na(Qobs)) %>%
  mutate(year = lubridate::year(date)) %>%
  group_by(year) %>%
  filter(Qobs == max(Qobs)) %>%
  select(year, Qobs) %>%
  ungroup


问:
Can I define System Properties within Spring Boot configuration files?
I have a single application.yml configuration file for my Spring Boot app that defines two profiles (as described in the documentation).

When the production profile is enabled, I would like to set the http.maxConnections system property to a custom value, e.g.

```<code>spring:
    profiles:
        active: dev
---
spring:
    profiles: dev
---
spring:
    profiles: production
http:
    maxConnections: 15
</code>```

But this doesn't actually set the system level property; it appears to just create an application-level property. I've verified this through both http://locahost:8080/env and a JMX Console when comparing launching by

```<code>java -jar -Dspring.profiles.active=production myapp.jar
</code>```

versus

```<code>java -Dhttp.maxConnections=15 myapp.jar
</code>```

I suppose I could create a bean that's @Conditional on the "production" profile that programmatically callsSystem.setProperty based on my application.yml-defined property, but is there a simpler way through configuration files alone?

答:
You can inject the environment into the constructor of the class that specifies the beans. This allows you to write application properties to the system properties before the beans are being created.</p>

```<code>@Configuration
public class ApplicationBeans {

   @Autowired
   public ApplicationBeans(Environment environment) {
      // set system properties before the beans are being created.
      String property = "com.application.property";
      System.getProperties().setProperty(property, environment.getProperty(property));
   }

   /**
    * Bean that depends on the system properties
    */
   @Bean
   public SomeBean someBean() {
      return new SomeBean();
   }
}
</code>```

Body:
I have a single application.yml configuration file for my Spring Boot app that defines two profiles (as described in the documentation).

When the production profile is enabled, I would like to set the http.maxConnections system property to a custom value, e.g.

spring:
    profiles:
        active: dev
---
spring:
    profiles: dev
---
spring:
    profiles: production
http:
    maxConnections: 15

But this doesn't actually set the system level property; it appears to just create an application-level property. I've verified this through both http://locahost:8080/env and a JMX Console when comparing launching by

java -jar -Dspring.profiles.active=production myapp.jar

versus

java -Dhttp.maxConnections=15 myapp.jar

I suppose I could create a bean that's @Conditional on the "production" profile that programmatically callsSystem.setProperty based on my application.yml-defined property, but is there a simpler way through configuration files alone?

Body:
You can inject the environment into the constructor of the class that specifies the beans. This allows you to write application properties to the system properties before the beans are being created.

@Configuration
public class ApplicationBeans {

   @Autowired
   public ApplicationBeans(Environment environment) {
      // set system properties before the beans are being created.
      String property = "com.application.property";
      System.getProperties().setProperty(property, environment.getProperty(property));
   }

   /**
    * Bean that depends on the system properties
    */
   @Bean
   public SomeBean someBean() {
      return new SomeBean();
   }
}


问:
VSCode how to import css snippets into less/sass/postcss
So, I have a css.json with couple of css snippets and sass.json with some sass snippets. Is there any way to use both css and sass snippets when I'm working on with sass files? Maybe use some kind of import, or set filetype of the file something like .css.sass (like in vim)?

答:
at right bottom click on sass and then select configure file association for scss and then select css,

-

then you can use css snippets in your sass file


问:
Eclipse & angularjs validation error: Unexpected token for import and export
I started to learn angular.js and build the hello world app according to the official angular site.

I'm working with Spring Tool Suite 3.8.4 and installed the AngularJS Eclipse 1.2.0 plugin and the test project was working fine without any validation errors.

After finishing this tutorial I made a git clone from this demo application, did all the installation steps, imported it as a project into Eclipse and configured it as an angular project (nature).

After all validation was done Eclipse showed me about 2500 errors with the message Unexpected token. I opened some files and it seems that the import and export keyword isn't recognized properly.

As the hello world app uses also these keywords and didn't have any validation errors I assume the reason could be a configuration problem. If i compare them in my project explorer i was wondering why in my hello world app was only a folder "TypeScript Resources (2.2.2)" and in this imported project there is also one folder/lib called "Javascript Resources". Might be ok, just something i noticed.

As im totally new to angular I have no clue what I could check. I read that the angular js support for the Eclipse IDE isn't perfect but these articles have been partly outdated as they were using Angular 1.x and 2.x.

Running the application with npm start in a terminal or "Run as" ==> ng serve" works fine without any problem.

Both applications (hello world and the cloned one) use Angular 4.x.
Does anybody have an idea? Do I need to provide more information?

答:
At first just to clarify things, you have installed Angular2 Eclipse which is for Angular2, Angular4 and where you develop with TypeScript. AngularJS Eclipse is for Angular1 where you develop with JavaScript.

You error is a JavaScript Problem which comes from the JSDT plugins. It seems that you have added JSDT nature. I suggest you to remove JSDT nature from your project because you develop with TypeScript and not with JavaScript.

To do that you can edit your .project file and remove this line:

```<code><nature>org.eclipse.wst.jsdt.core.jsNature</nature>
</code>```

If you need to open JavaScript file in an editor with validation, completion, etc, TypeScript IDE provide a JavaScript (Salsa) Editor which does that. You open your JS file with JavaScript (Salsa) Editor:

and after you benefit from the same feature than TypeScript editor:

Body:
At first just to clarify things, you have installed Angular2 Eclipse which is for Angular2, Angular4 and where you develop with TypeScript. AngularJS Eclipse is for Angular1 where you develop with JavaScript.

You error is a JavaScript Problem which comes from the JSDT plugins. It seems that you have added JSDT nature. I suggest you to remove JSDT nature from your project because you develop with TypeScript and not with JavaScript.

To do that you can edit your .project file and remove this line:

<nature>org.eclipse.wst.jsdt.core.jsNature</nature>

If you need to open JavaScript file in an editor with validation, completion, etc, TypeScript IDE provide a JavaScript (Salsa) Editor which does that. You open your JS file with JavaScript (Salsa) Editor:

and after you benefit from the same feature than TypeScript editor:


问:
How to update a global variable inside RDD map operation
I have RDD[(Int, Array[Double])] and after that, I called a classFunction

```<code>val rdd = spark.sparkContext.parallelize(Seq(
        (1, Array(2.0,5.0,6.3)),
        (5, Array(1.0,3.3,9.5)),
        (1, Array(5.0,4.2,3.1)),
        (2, Array(9.6,6.3,2.3)),
        (1, Array(8.5,2.5,1.2)),
        (5, Array(6.0,2.4,7.8)),
        (2, Array(7.8,9.1,4.2))
      )
    )
 val new_class = new ABC
 new_class.demo(data)
</code>```

Inside class, declared a global variable value =0. Inside the demo() the new variable  new_value = 0 is declared. After the map operation, the new_value get updated and it prints the updated value inside the map.

```<code>class ABC extends Serializable {
        var value  = 0
        def demo(data_new : RDD[(Int ,Array[Double])]): Unit ={
            var new_value = 0
            data_new.coalesce(1).map(x => {
                if(x._1 == 1)
                    new_value = new_value + 1
                println(new_value)
                value = new_value
            }).count()
            println("Outside-->" +value)
        }
    }
</code>```

OUTPUT:-

```<code>1
1
2
2
3
3
3
Outside-->0
</code>```

How can I update the global variable value after the map operation?.

答:
I'm not sure about what is it you are doing but you need to use Accumulators to perform the type of operations where you need to add values like this.

Here is an example :

```<code>scala> val rdd = spark.sparkContext.parallelize(Seq(
     |         (1, Array(2.0,5.0,6.3)),
     |         (5, Array(1.0,3.3,9.5)),
     |         (1, Array(5.0,4.2,3.1)),
     |         (2, Array(9.6,6.3,2.3)),
     |         (1, Array(8.5,2.5,1.2)),
     |         (5, Array(6.0,2.4,7.8)),
     |         (2, Array(7.8,9.1,4.2))
     |       )
     | )
rdd: org.apache.spark.rdd.RDD[(Int, Array[Double])] = ParallelCollectionRDD[83] at parallelize at <console>:24

scala> val accum = sc.longAccumulator("My Accumulator")
accum: org.apache.spark.util.LongAccumulator = LongAccumulator(id: 46181, name: Some(My Accumulator), value: 0)

scala> rdd.foreach { x => if(x._1 == 1) accum.add(1) }

scala> accum.value
res38: Long = 3
</code>```

And as mentioned by @philantrovert, if you wish to count the number of occurrences of each key, you can do the following :

```<code>scala> rdd.mapValues(_ => 1L).reduceByKey(_ + _).take(3)
res41: Array[(Int, Long)] = Array((1,3), (2,2), (5,2))
</code>```

You can also use countByKey but it is to be avoided with big datasets.

Body:
I have RDD[(Int, Array[Double])] and after that, I called a classFunction

val rdd = spark.sparkContext.parallelize(Seq(
        (1, Array(2.0,5.0,6.3)),
        (5, Array(1.0,3.3,9.5)),
        (1, Array(5.0,4.2,3.1)),
        (2, Array(9.6,6.3,2.3)),
        (1, Array(8.5,2.5,1.2)),
        (5, Array(6.0,2.4,7.8)),
        (2, Array(7.8,9.1,4.2))
      )
    )
 val new_class = new ABC
 new_class.demo(data)

Inside class, declared a global variable value =0. Inside the demo() the new variable  new_value = 0 is declared. After the map operation, the new_value get updated and it prints the updated value inside the map.

class ABC extends Serializable {
        var value  = 0
        def demo(data_new : RDD[(Int ,Array[Double])]): Unit ={
            var new_value = 0
            data_new.coalesce(1).map(x => {
                if(x._1 == 1)
                    new_value = new_value + 1
                println(new_value)
                value = new_value
            }).count()
            println("Outside-->" +value)
        }
    }

OUTPUT:-

1
1
2
2
3
3
3
Outside-->0

How can I update the global variable value after the map operation?.

Body:
I'm not sure about what is it you are doing but you need to use Accumulators to perform the type of operations where you need to add values like this.

Here is an example :

scala> val rdd = spark.sparkContext.parallelize(Seq(
     |         (1, Array(2.0,5.0,6.3)),
     |         (5, Array(1.0,3.3,9.5)),
     |         (1, Array(5.0,4.2,3.1)),
     |         (2, Array(9.6,6.3,2.3)),
     |         (1, Array(8.5,2.5,1.2)),
     |         (5, Array(6.0,2.4,7.8)),
     |         (2, Array(7.8,9.1,4.2))
     |       )
     | )
rdd: org.apache.spark.rdd.RDD[(Int, Array[Double])] = ParallelCollectionRDD[83] at parallelize at <console>:24

scala> val accum = sc.longAccumulator("My Accumulator")
accum: org.apache.spark.util.LongAccumulator = LongAccumulator(id: 46181, name: Some(My Accumulator), value: 0)

scala> rdd.foreach { x => if(x._1 == 1) accum.add(1) }

scala> accum.value
res38: Long = 3

And as mentioned by @philantrovert, if you wish to count the number of occurrences of each key, you can do the following :

scala> rdd.mapValues(_ => 1L).reduceByKey(_ + _).take(3)
res41: Array[(Int, Long)] = Array((1,3), (2,2), (5,2))

You can also use countByKey but it is to be avoided with big datasets.


问:
Unable to locate element 'Add to Cart ' on Ted Baker ecommerce site
enter image description hereI am not able to locate web Element Add to cart using Xpath as well as classname.
Steps:trying to add product in cart /wishlist but button is not clickable.
 Can anyone please help me to resolve this issue.

    ===========================================================================
    Code>>>

```<code>    package Test;
    import java.util.HashMap;
    import java.util.Map;
    import org.openqa.selenium.By;
    import org.openqa.selenium.JavascriptExecutor;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    import org.openqa.selenium.interactions.Actions;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.Select;
    import org.openqa.selenium.support.ui.WebDriverWait;

    public class tedbak {

        public static void main(String[] args) throws InterruptedException {
            // TODO Auto-generated method stub
            WebDriver driver;

                System.setProperty("webdriver.chrome.driver","C:\\Chrome\\chromedriver_win32\\chromedriver.exe");
                //System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Jdk14Logger");
             Thread.sleep(2000);
            ChromeOptions options = new ChromeOptions();
            Map<String, Object> prefs = new HashMap<String, Object>();
            prefs.put("credentials_enable_service", false);
            prefs.put("password_manager_enabled", false);
              options.setExperimentalOption("prefs", prefs);
            options.addArguments("start-maximized");
            options.addArguments("disable-infobars");
            driver = new ChromeDriver(options);

                driver.get("http://www.tedbaker.com/");

                WebDriverWait wait = new WebDriverWait(driver, 40);
                wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("html/body/div[3]/div[2]/div/div/ul/li[1]/a")));
                        if(driver.findElement(By.xpath("html/body/div[3]/div[2]/div/div/ul/li[1]/a")).isDisplayed())
                            {

                            driver.findElement(By.xpath("html/body/div[3]/div[2]/div/div/ul/li[1]/a")).click();

                            WebElement Search_Item=driver.findElement(By.xpath("html/body/div[2]/header/div/nav[2]/section/ul[2]/li[1]/a/span[1]"));
                            Search_Item.click();
                            WebElement Seacrh_item_message=driver.findElement(By.id("search"));
                            WebElement Search_textbox=driver.findElement(By.xpath("html/body/div[2]/header/div/form/div[1]/ol/li[1]/input"));

                            Search_textbox.sendKeys("Watches");
                            driver.findElement(By.xpath("html/body/div[2]/header/div/form/div[1]/ol/li[2]/input")).click();
                            WebElement SearchResult_pagemessage=driver.findElement(By.xpath("html/body/div[2]/div/div/div[1]/div/h1"));
                            driver.findElement(By.xpath("html/body/div[2]/div/div/div[1]/div/div/div/span[1]")).click();

 WebElement Item_Tobuy = driver.findElement(By.xpath("html/body/div[2]/div/div/div[2]/div[2]/div[1]/article/div[2]/header/div/h4/a"));
                            JavascriptExecutor jse1= (JavascriptExecutor)driver;
                            jse1.executeScript("window.scrollBy(0,400)", "");
                            Item_Tobuy.click();
                                                         driver.findElement(By.xpath("html/body/div[2]/div/div/div[2]/div[1]/section[2]/form/ol/li[2]/span/span/select")).click();
                           Select dropdown1=new Select(driver.findElement(By.id("qty")));
                           dropdown1.selectByVisibleText("5");
                           driver.findElement(By.id("qty")).click();
                           driver.findElement(By.xpath("html/body/div[2]/div/div/div[2]/div[1]/section[2]/form/div[3]/div[2]/a/span[1]/span[1]")).click();
                                                                            }

    }
    }
===========================================================================
    error>>>

    Starting ChromeDriver 2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41) on port 17869
    Only local connections are allowed.
    Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"html/body/div[2]/div/div/div[2]/div[1]/section[2]/form/div[3]/div[2]/a/span[1]/span[1]"}
      (Session info: chrome=59.0.3071.86)
      (Driver info: chromedriver=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41),platform=Windows NT 10.0.14393 x86_64) (WARNING: The server did not provide any stacktrace information)
    Command duration or timeout: 52 milliseconds
    For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
    Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 17:00:58'
    System info: host: 'D90ZC6Q1', ip: '192.168.163.235', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_92'
    Driver info: org.openqa.selenium.chrome.ChromeDriver
    Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41), userDataDir=C:\Users\DAHIBH~1\AppData\Local\Temp\scoped_dir8284_18567}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=59.0.3071.86, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=}]
    Session ID: b48bc601ec61113cfada0c7c2f5f77b8
    *** Element info: {Using=xpath, value=html/body/div[2]/div/div/div[2]/div[1]/section[2]/form/div[3]/div[2]/a/span[1]/span[1]}
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
        at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:500)
        at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
        at Test.tedbak.main(tedbak.java:70)
</code>```

答:
You need to change the last XPath in your code to "//*[@id='add_to_cart_form']/div[2]/div[2]/a/span[1]/span[1]"

```<code>driver.findElement(By.id("qty")).click();
driver.findElement(By.xpath("//*[@id='add_to_cart_form']/div[2]/div[2]/a/span[1]/span[1]")).click();
</code>```

Body:
enter image description hereI am not able to locate web Element Add to cart using Xpath as well as classname.
Steps:trying to add product in cart /wishlist but button is not clickable.
 Can anyone please help me to resolve this issue.

    ===========================================================================
    Code>>>

    package Test;
    import java.util.HashMap;
    import java.util.Map;
    import org.openqa.selenium.By;
    import org.openqa.selenium.JavascriptExecutor;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    import org.openqa.selenium.interactions.Actions;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.Select;
    import org.openqa.selenium.support.ui.WebDriverWait;

    public class tedbak {

        public static void main(String[] args) throws InterruptedException {
            // TODO Auto-generated method stub
            WebDriver driver;

                System.setProperty("webdriver.chrome.driver","C:\\Chrome\\chromedriver_win32\\chromedriver.exe");
                //System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Jdk14Logger");
             Thread.sleep(2000);
            ChromeOptions options = new ChromeOptions();
            Map<String, Object> prefs = new HashMap<String, Object>();
            prefs.put("credentials_enable_service", false);
            prefs.put("password_manager_enabled", false);
              options.setExperimentalOption("prefs", prefs);
            options.addArguments("start-maximized");
            options.addArguments("disable-infobars");
            driver = new ChromeDriver(options);

                driver.get("http://www.tedbaker.com/");

                WebDriverWait wait = new WebDriverWait(driver, 40);
                wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("html/body/div[3]/div[2]/div/div/ul/li[1]/a")));
                        if(driver.findElement(By.xpath("html/body/div[3]/div[2]/div/div/ul/li[1]/a")).isDisplayed())
                            {

                            driver.findElement(By.xpath("html/body/div[3]/div[2]/div/div/ul/li[1]/a")).click();

                            WebElement Search_Item=driver.findElement(By.xpath("html/body/div[2]/header/div/nav[2]/section/ul[2]/li[1]/a/span[1]"));
                            Search_Item.click();
                            WebElement Seacrh_item_message=driver.findElement(By.id("search"));
                            WebElement Search_textbox=driver.findElement(By.xpath("html/body/div[2]/header/div/form/div[1]/ol/li[1]/input"));

                            Search_textbox.sendKeys("Watches");
                            driver.findElement(By.xpath("html/body/div[2]/header/div/form/div[1]/ol/li[2]/input")).click();
                            WebElement SearchResult_pagemessage=driver.findElement(By.xpath("html/body/div[2]/div/div/div[1]/div/h1"));
                            driver.findElement(By.xpath("html/body/div[2]/div/div/div[1]/div/div/div/span[1]")).click();

 WebElement Item_Tobuy = driver.findElement(By.xpath("html/body/div[2]/div/div/div[2]/div[2]/div[1]/article/div[2]/header/div/h4/a"));
                            JavascriptExecutor jse1= (JavascriptExecutor)driver;
                            jse1.executeScript("window.scrollBy(0,400)", "");
                            Item_Tobuy.click();
                                                         driver.findElement(By.xpath("html/body/div[2]/div/div/div[2]/div[1]/section[2]/form/ol/li[2]/span/span/select")).click();
                           Select dropdown1=new Select(driver.findElement(By.id("qty")));
                           dropdown1.selectByVisibleText("5");
                           driver.findElement(By.id("qty")).click();
                           driver.findElement(By.xpath("html/body/div[2]/div/div/div[2]/div[1]/section[2]/form/div[3]/div[2]/a/span[1]/span[1]")).click();
                                                                            }

    }
    }
===========================================================================
    error>>>

    Starting ChromeDriver 2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41) on port 17869
    Only local connections are allowed.
    Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"html/body/div[2]/div/div/div[2]/div[1]/section[2]/form/div[3]/div[2]/a/span[1]/span[1]"}
      (Session info: chrome=59.0.3071.86)
      (Driver info: chromedriver=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41),platform=Windows NT 10.0.14393 x86_64) (WARNING: The server did not provide any stacktrace information)
    Command duration or timeout: 52 milliseconds
    For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
    Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 17:00:58'
    System info: host: 'D90ZC6Q1', ip: '192.168.163.235', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_92'
    Driver info: org.openqa.selenium.chrome.ChromeDriver
    Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41), userDataDir=C:\Users\DAHIBH~1\AppData\Local\Temp\scoped_dir8284_18567}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=59.0.3071.86, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=}]
    Session ID: b48bc601ec61113cfada0c7c2f5f77b8
    *** Element info: {Using=xpath, value=html/body/div[2]/div/div/div[2]/div[1]/section[2]/form/div[3]/div[2]/a/span[1]/span[1]}
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
        at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:500)
        at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
        at Test.tedbak.main(tedbak.java:70)

Body:
You need to change the last XPath in your code to "//*[@id='add_to_cart_form']/div[2]/div[2]/a/span[1]/span[1]"

driver.findElement(By.id("qty")).click();
driver.findElement(By.xpath("//*[@id='add_to_cart_form']/div[2]/div[2]/a/span[1]/span[1]")).click();


问:
Step by Step guide on how to setup CruiseControl.Net + Subversion
I'm looking for a step by step guide (like for dummies guide), to setup CC.NET + Subversion. And I'm wondering if a really need to do Unit testing to use CC.NET? </p>

答:
Google can really be your friend in this case. This was the first result for "Subversion CruiseControl.NET" and things look pretty thorough:

Continuous Integrion + CruiseControl.NET + SubVersion + MSBuild + .NET 2.0


问:
x86 64 Reverse shell shellcode
I am looking a reverse shell shellcode from this link. I am not able to follow the reason for the following instructions in the shellcode:

```<code>4000a3:   4d 31 d2                xor    r10,r10
4000a6:   41 52                   push   r10
4000a8:   c6 04 24 02             mov    BYTE PTR [rsp],0x2
4000ac:   66 c7 44 24 02 7a 69    mov    WORD PTR [rsp+0x2],0x697a
4000b3:   c7 44 24 04 0a 33 35    mov    DWORD PTR [rsp+0x4],0x435330a
4000ba:   04
4000bb:   48 89 e6                mov    rsi,rsp
</code>```

I searched other SO questions, and I find that BYTE/WORD/DWORD PTR would be used to assign a byte/word/dword. Since this x86 64, I'm assuming WORD here means 2 bytes and DWORD means 4 bytes (please correct me if I'm wrong).
The author is pushing zero on the stack. Then he has 3 mov instructions.
Assume RSP initially points to:

```<code>x00 x00 x00 x00 x00 x00 x00 x00
</code>```

1) Is the following the effect of the three mov instructions (assuming little endian) ?

```<code>x04 x35 x33 x0a x7a x69 x00 x02
</code>```

2) If yes, then what is the author achieving by it because isn't the next mov instructions overwriting what's pointed by rsp ?

Thanks

答:
1) Yes

2) Author is saving the sockaddr for the socket connect syscall

```<code>       int connect(int sockfd, const struct sockaddr *addr,
               socklen_t addrlen);
</code>```

In x86-64, the arguments are the registers rdi, rsi and rdx. So, He is moving the pointer addr pointer to rsi register.

```<code> mov    BYTE PTR [rsp],0x2              ; Family Address (PF_INET)
 mov    WORD PTR [rsp+0x2],0x697a       ; port = 27002
 mov    DWORD PTR [rsp+0x4],0x435330a   ; addr = 10.51.53.4 (0a333504)
</code>```

Title: x86 64 Reverse shell shellcode

Body:
I am looking a reverse shell shellcode from this link. I am not able to follow the reason for the following instructions in the shellcode:

4000a3:   4d 31 d2                xor    r10,r10
4000a6:   41 52                   push   r10
4000a8:   c6 04 24 02             mov    BYTE PTR [rsp],0x2
4000ac:   66 c7 44 24 02 7a 69    mov    WORD PTR [rsp+0x2],0x697a
4000b3:   c7 44 24 04 0a 33 35    mov    DWORD PTR [rsp+0x4],0x435330a
4000ba:   04
4000bb:   48 89 e6                mov    rsi,rsp

I searched other SO questions, and I find that BYTE/WORD/DWORD PTR would be used to assign a byte/word/dword. Since this x86 64, I'm assuming WORD here means 2 bytes and DWORD means 4 bytes (please correct me if I'm wrong).
The author is pushing zero on the stack. Then he has 3 mov instructions.
Assume RSP initially points to:

x00 x00 x00 x00 x00 x00 x00 x00

1) Is the following the effect of the three mov instructions (assuming little endian) ?

x04 x35 x33 x0a x7a x69 x00 x02

2) If yes, then what is the author achieving by it because isn't the next mov instructions overwriting what's pointed by rsp ?

Thanks

Body:
1) Yes

2) Author is saving the sockaddr for the socket connect syscall

       int connect(int sockfd, const struct sockaddr *addr,
               socklen_t addrlen);

In x86-64, the arguments are the registers rdi, rsi and rdx. So, He is moving the pointer addr pointer to rsi register.

 mov    BYTE PTR [rsp],0x2              ; Family Address (PF_INET)
 mov    WORD PTR [rsp+0x2],0x697a       ; port = 27002
 mov    DWORD PTR [rsp+0x4],0x435330a   ; addr = 10.51.53.4 (0a333504)


问:
Ctrl Key KeyUp event with Click in table heading
I want to generate keyup event with . If i click in  click event is populating there but my requirement is generate event when i release CTRL key pressed with click in  area I am using the following code

```<code><html>
<head>
<script
 src="https://code.jquery.com/jquery-3.2.1.min.js"
 integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
 crossorigin="anonymous"></script>
</head>
<body>
<table border="2">
<th>rollno</th>
<th>name</th>
<tr>
<td>4567</td>
<td>john</td>
 </tr>
</table>
 </body>
 <script>
 $('th').click(function(){
 alert("yes its working");
 });
 </script>
 <script>
 $('th').on('keyup', function(e) {
 if (e.keyCode ==17)
 {
 alert("OOps! ctr+click release not working");
 }
 });
 </script>

 </html>
</code>```

答:
```<code>$(document).on('keyup',function(event){
 if(event.which=="17"){
    cntrlIsPressed = true;
}
else{cntrllsPressed=false;}
});
 $('th').on('click ', function(e) {
 if (cntrllsPressed==true)
 {
 alert("OOps! ctr+click release not working");
}
});
$(document).on('keydown',function(event){
    cntrlIsPressed =false;
});
</code>```

Body:
I want to generate keyup event with . If i click in  click event is populating there but my requirement is generate event when i release CTRL key pressed with click in  area I am using the following code

rollno
name

4567
john


答:
Change height of parent div on add and remove of children

 $("#add").on("click",function(){
var top = parseInt($("#parentDiv .childDiv:last").css("top").split("px")[0])+90;

$("#parentDiv").append("
divvvvvv
");
$("#parentDiv").css('height', top + 90);
});

 $("#remove").on("click",function(){
$("#parentDiv").css('height',$("#parentDiv .childDiv:last-child").css('top'));
$("#parentDiv .childDiv:last").remove();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  #parentDiv
     {
      background: antiquewhite;
      }
     .childDiv
     {
     background: yellow;
      width: 700px;
      height: 50px;
      }</code>```

<button id="add">add</button><button id="remove">remove</button>

    Div one

    div two

   div three

```

Title: Increase or decrease parent div height based on the changes in the children element

Body:
https://jsfiddle.net/9b90twgf/15/

 $("#add").on("click",function(){
var top = parseInt($("#parentDiv .childDiv:last").css("top").split("px")[0])+90;

$("#parentDiv").append("
divvvvvv
");
});

 $("#remove").on("click",function(){
$("#parentDiv .childDiv:last").remove();
});

  #parentDiv
     {
      background: antiquewhite;
      }
     .childDiv
     {
     background: yellow;
      width: 700px;
      height: 50px;
      }

<button id="add">add</button><button id="remove">remove</button>

    Div one

    div two

   div three

I have one parent div, under this I will append and remove HTML elements as children, if I remove children element parent div have to shrink its height automatically and if I add it have to expand automatically, my requirement is both parent and children must have position absolute(style="position:absolute")

Body:
Change height of parent div on add and remove of children

 $("#add").on("click",function(){
var top = parseInt($("#parentDiv .childDiv:last").css("top").split("px")[0])+90;

$("#parentDiv").append("<div class='childDiv' style='position:absolute; top:"+top+"px;'>divvvvvv</div>");
$("#parentDiv").css('height', top + 90);
});

 $("#remove").on("click",function(){
$("#parentDiv").css('height',$("#parentDiv .childDiv:last-child").css('top'));
$("#parentDiv .childDiv:last").remove();
});

  #parentDiv
     {
      background: antiquewhite;
      }
     .childDiv
     {
     background: yellow;
      width: 700px;
      height: 50px;
      }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="add">add</button><button id="remove">remove</button>
  <div style="position: absolute; width: 700px; height: 210px;" id="parentDiv">
      <div class="childDiv" style="position: absolute;">
    Div one
    </div>

    <div class="childDiv" style="position: absolute; top: 75px;">
    div two
   </div>
   <div class="childDiv" style="position: absolute; top: 140px;">
   div three
  </div>
  </div>


答: try with the xpath //input[contains(@class,'add_to_cart')]

Title: Unable to locate element 'Add to Cart ' on Ted Baker ecommerce site


问:
Can we connect Tableau tool with Adobe Analytics (Omniture) Server?
Can we connect Tableau tool with Adobe Analytics fomerly Omniture Server?</p>

答:
Indeed, there is no direct Tableau integration, but you can automate the fetching of your Adobe Analytics data by using community built connectors.

Here’s an example of a free one that was launched at the Adobe Un-Summit this year:

On Tableau, select the "More..." tab to access the list of connectors

Click on "Web Data Connector"

In the popup window that appears, click on the URL box in the center of the screen and enter tableau.cognetik.com for the Cognetik web data connector. Hit Enter.

I hope this helps, let me know if you have any questions.

(full disclosure, I work for the company that built it, but we’re seeing it used by multiple companies worldwide).


问:
Async calls with new keyword 'await'
I've used async methods today, calling methods asynchronously and using the caller's callback methods.

Recently, I can across this post which talks about the new way to do this using the new await keyword. Other than saving few lines of code, what are the main advantages of this new model?

Does it offer a built in solution for when you make two different async calls but want the control to return to only one of the caller's callback, after both have completed?

What does CTP (Community Technical Preview) mean? Is this new keyword available in next version of C# and VB.NET?

答:
From Eric Lippert's Blog post Asynchrony in C# 5, Part One

The designers of C# 5.0 realized that
  writing asynchronous code is painful,
  in so many ways. Asynchronous code is
  hard to reason about, and as we've
  seen, the transformation into a
  continuation is complex and leads to
  code replete with mechanisms that
  obscure the meaning of the code.

As the article explains like iterator blocks, anonymous methods, query comprehensions and dynamic types the intent is to make something that is hard, easy.

As for Community Technical Preview bit. Typically it means that "await" will be in the next version of C#, but there's no guarantee that something about it won't change. So if you write something (code or blog posts) and its breaks don't blame them.

Title: Async calls with new keyword 'await'


问:
Rename List item when there is the same string multiple time
I have List of names like:

```<code>var list = new List<string> {"Allan", "Michael", "Jhon", "Smith", "George", "Jhon"};
</code>```

and a combobox which itemssource is my list. As you can see in the list there is Jhon 2 times, what I want is when I put those name into combobox add "2" to second Jhon. I mean when I open the combobox names in it shoud look like:

```<code>Allan
Michael
Jhon
Smith
George
Jhon2
</code>```

I have tired linq to do that but I'm quite new to c#/linq. Could someone show me simple way to do that?

答:
Someone might be able to give a more efficient answer, but this does the job.

The dictionary keeps track of how many times a name has been repeated in the list. Each time a new name in the list is encountered, it is added to the dictionary and is added as is to the new list. If the name already exists in the dictionary (with the key check), instead, the count is increased by one in the dictionary and this name is added to the new list with the count (from the dictionary value corresponding to the name as the key) appended to the end of the name.

```<code>var list = new List<string> {"Allan", "Michael", "Jhon", "Smith", "George", "Jhon", "George", "George"};
        Dictionary<string, int> dictionary = new Dictionary<string,int>();
        var newList = new List<string>();
        for(int i=0; i<list.Count();i++){
            if(!dictionary.ContainsKey(list[i])){
                dictionary.Add(list[i], 1);
                newList.Add(list[i]);
            }
            else{
                dictionary[list[i]] += 1;
                newList.Add(list[i] + dictionary[list[i]]);
            }
        }
        for(int i=0; i<newList.Count(); i++){
            Console.WriteLine(newList[i]);
        }
</code>```

Output:

```<code>Allan
Michael
Jhon
Smith
George
Jhon2
George2
George3
</code>```

Body:
I have List of names like:

var list = new List<string> {"Allan", "Michael", "Jhon", "Smith", "George", "Jhon"};

and a combobox which itemssource is my list. As you can see in the list there is Jhon 2 times, what I want is when I put those name into combobox add "2" to second Jhon. I mean when I open the combobox names in it shoud look like:

Allan
Michael
Jhon
Smith
George
Jhon2

I have tired linq to do that but I'm quite new to c#/linq. Could someone show me simple way to do that?

Body:
Someone might be able to give a more efficient answer, but this does the job.

The dictionary keeps track of how many times a name has been repeated in the list. Each time a new name in the list is encountered, it is added to the dictionary and is added as is to the new list. If the name already exists in the dictionary (with the key check), instead, the count is increased by one in the dictionary and this name is added to the new list with the count (from the dictionary value corresponding to the name as the key) appended to the end of the name.

var list = new List<string> {"Allan", "Michael", "Jhon", "Smith", "George", "Jhon", "George", "George"};
        Dictionary<string, int> dictionary = new Dictionary<string,int>();
        var newList = new List<string>();
        for(int i=0; i<list.Count();i++){
            if(!dictionary.ContainsKey(list[i])){
                dictionary.Add(list[i], 1);
                newList.Add(list[i]);
            }
            else{
                dictionary[list[i]] += 1;
                newList.Add(list[i] + dictionary[list[i]]);
            }
        }
        for(int i=0; i<newList.Count(); i++){
            Console.WriteLine(newList[i]);
        }

Output:

Allan
Michael
Jhon
Smith
George
Jhon2
George2
George3


问:
AutoMapper requires Get Accessor to Set. CS0154 The property or indexer 'Id' cannot be used in this context because it lacks the get accessor
The Id property in my ViewModel class can be set, but not gotten as the setter encrypts the value.  To get the value I have to use a either GetEncryptedId() or GetDecryptedId().

The ViewModel

```<code>public ViewModel
{
    public int _id;
    public int Id { set { _id = Encrypt(value); }
    public Child ChildProperty {get; set; }
}

public Child
{
    public int Id {get; set;}
    public string Name {get; set; }
}
</code>```

The problem here is that for some reason Auto Mapper wants a get accessor so it can set a value.

```<code>public ViewModelProfile()
{
    CreateMap<Model, ViewModel>().ForMember(vm => vm.Id, opt => opt.MapFrom(m => m.ChildProperty.Id))
}
</code>```

This throws and error stating:

```<code>CS0154 The property or indexer 'Id' cannot be used in this context because it lacks the get accessor.
</code>```

Why does Auto Mapper require a 'Get Accessor' to set a value.

Is there a configuration option to force a set and no get?

As a work around I've added a Get { return -1; }, but that is far from ideal.

答:
This isn't a limitation of AutoMapper as such, but of the way its API is structured. The expression tree vm => vm.Id can't be constructed because this is, you've guessed it, a reference to the property getter, which isn't possible because there is no getter. Passing an expression tree as a strongly typed way of referencing a member is a standard technique; AutoMapper is by far not the only thing that would have problems with this. The fact that AutoMapper would not ultimately call the getter is immaterial in this case.

Fortunately, ForMember has an override that accepts the member name as a string, and using that avoids the problem with the expression tree:

```<code>CreateMap<Model, ViewModel>()
    .ForMember(nameof(ViewModel.Id), opt => opt.MapFrom(m => m.ChildProperty.Id))
</code>```

Body:
The Id property in my ViewModel class can be set, but not gotten as the setter encrypts the value.  To get the value I have to use a either GetEncryptedId() or GetDecryptedId().

The ViewModel

public ViewModel
{
    public int _id;
    public int Id { set { _id = Encrypt(value); }
    public Child ChildProperty {get; set; }
}

public Child
{
    public int Id {get; set;}
    public string Name {get; set; }
}

The problem here is that for some reason Auto Mapper wants a get accessor so it can set a value.

public ViewModelProfile()
{
    CreateMap<Model, ViewModel>().ForMember(vm => vm.Id, opt => opt.MapFrom(m => m.ChildProperty.Id))
}

This throws and error stating:

CS0154 The property or indexer 'Id' cannot be used in this context because it lacks the get accessor.

Why does Auto Mapper require a 'Get Accessor' to set a value.

Is there a configuration option to force a set and no get?

As a work around I've added a Get { return -1; }, but that is far from ideal.

Body:
This isn't a limitation of AutoMapper as such, but of the way its API is structured. The expression tree vm => vm.Id can't be constructed because this is, you've guessed it, a reference to the property getter, which isn't possible because there is no getter. Passing an expression tree as a strongly typed way of referencing a member is a standard technique; AutoMapper is by far not the only thing that would have problems with this. The fact that AutoMapper would not ultimately call the getter is immaterial in this case.

Fortunately, ForMember has an override that accepts the member name as a string, and using that avoids the problem with the expression tree:

CreateMap<Model, ViewModel>()
    .ForMember(nameof(ViewModel.Id), opt => opt.MapFrom(m => m.ChildProperty.Id))


问:
psql "more is not recognized" error
I am using the postgresql (9.4) interactive terminal psql on Windows 8.1 (64 bit). After installing and creating a database and table and inserting data into a row I want to view the data.

However, when I type

```<code>SELECT * FROM my_table;
</code>```

I get an error:

'more' is not recognized as an internal or external command, operable program or batch file.

After adding "C:\Windows\System32;" to my path variable, more works in Powershell (e.g. more hello.txt) but still not in psql.

What else do I need to do to make the SELECT statement work?

答:
Typically this error occurs due to PATH environment variable is not set
properly in your system & it is unable to find the more command from

C:\Windows\System32.

The solution to this is:

(Right Click on)  My Computer -> Properties -> Advanced tab ->
  Environment Variable ->

Then set the PATH in system variables.

Add these to the PATH variable:

%SystemRoot%;

%SystemRoot%\system32;%PROGRAMFILES%\PostgreSQL\9.4\bin

Hope this will solve your problem.

Title: psql "more is not recognized" error

Body:
I am using the postgresql (9.4) interactive terminal psql on Windows 8.1 (64 bit). After installing and creating a database and table and inserting data into a row I want to view the data.

However, when I type

SELECT * FROM my_table;

I get an error:

'more' is not recognized as an internal or external command, operable program or batch file.

After adding "C:\Windows\System32;" to my path variable, more works in Powershell (e.g. more hello.txt) but still not in psql.

What else do I need to do to make the SELECT statement work?


问:
Role based authorisation in Angular Js
I am working on a project that requires multiple roles for which I'm using https://github.com/Narzerus/angular-permission. I need to work with different set of permissions on each of these roles. For example, role admin can have permissions ->PageView, PageEdit, PageCreate, while the role viewer has permissions->PageView only.

The roles associated with each user are stored in the database, I am planning to use the transition objects function to ensure what role is associated with what user.

I am new to angular and can't figure out a way to define a role such that I can,
1. Link multiple permissions with it,
2. Associate it with transition properties (dynamic function).

答:
For Role based authorization, you have to manage your app.config and app.run files. Simply apply the following settings :

In app.config file:

```<code>   $routeProvider.when( '/', {
        templateUrl: 'views/dashboard.html',
        resolve: {
            "currentAuth": [ "authService", function( authService ) {
                var auth = authService.auth();
                return auth;
            }]
        }
    });

 app.run( [ authService, function(authService) {

        if (role === "admin") {
           // Use changeSuccess method on route to redirect.
        }

} ] );
</code>```

And In authService fetch the roles from database. In authservice add method:

```<code>function functionName(user){
if (user) {
    if (!!~this.roles.indexOf('*')) {
        return true;
    } else {
        for (var userRoleIndex in user.roles) {
            for (var roleIndex in this.roles) {
                if (this.roles[roleIndex] === user.roles[userRoleIndex]) {
                    return true;
                }
            }
        }
    }
} else {
    return this;
}
return false;
</code>```

}

Title: Role based authorisation in Angular Js

Body:
For Role based authorization, you have to manage your app.config and app.run files. Simply apply the following settings :

In app.config file:

   $routeProvider.when( '/', {
        templateUrl: 'views/dashboard.html',
        resolve: {
            "currentAuth": [ "authService", function( authService ) {
                var auth = authService.auth();
                return auth;
            }]
        }
    });

 app.run( [ authService, function(authService) {

        if (role === "admin") {
           // Use changeSuccess method on route to redirect.
        }

} ] );

And In authService fetch the roles from database. In authservice add method:

function functionName(user){
if (user) {
    if (!!~this.roles.indexOf('*')) {
        return true;
    } else {
        for (var userRoleIndex in user.roles) {
            for (var roleIndex in this.roles) {
                if (this.roles[roleIndex] === user.roles[userRoleIndex]) {
                    return true;
                }
            }
        }
    }
} else {
    return this;
}
return false;

}


问:
How to give styling for active tab of nav-tab
This is my HTML Code. I want css styling for active nav-tab.Now i want when my page loads Location tab should have blue background how can i get that

```<code><div class="row">
        <div class="col-sm-12 col-xs-12 col-lg-12 col-md-12 welcome">
            <ul class="nav navbar-nav navbar-nav-primary">
                <li class="active">
                    <a href="#one" data-toggle="tab">
                        <i class="fa fa-map-marker" aria-hidden="true"></i>
         <span class="li-text">Location</span>
                    </a>
                </li>
                <li>
                    <a href="#two" data-toggle="tab">
                        <i class="fa fa-heartbeat" aria-hidden="true"></i> <span class="li-text">Heartbeats</span>
                    </a>
                </li>
                <li>
                    <a href="#three" data-toggle="tab">
                        <i class="fa fa-power-off" aria-hidden="true"></i>
                        <span class="li-text">Reboots</span>
                    </a>
                </li>
                <li>
                    <a href="#four" data-toggle="tab">
                        <i class="fa fa-compress" aria-hidden="true"></i>
                        <span class="li-text">Reconnects</span>
                    </a>
                </li>
                <li>
                    <a href="#five" data-toggle="tab">
                        <i class="fa fa-battery-full" aria-hidden="true"></i>
                        <span class="li-text">Charge</span>
                    </a>
                </li>

            </ul>

        </div>
</code>```

Location tab is the active tab

```<code>         <div id="one" class="tab-pane active">

                <div class="row">
                    <div class="col-sm-offset-10 col-md-offset-10 col-xs-offset-10 col-lg-offset-10 col-sm-2 col-md-2 col-xs-2 col-lg-2 searchDiv">
                        <div class="row">
                            <div class="col-sm-1 col-xs-1 col-lg-1 col-md-1">
                                <i class="fa fa-search fa-2x" aria-hidden="true"></i>
                            </div>
                            <div class="col-sm-1 col-md-1 col-lg-1 col-xs-1">

                                <i class="fa fa-ellipsis-v fa-2x" aria-hidden="true"></i>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane active" id="1a">
                    <div ui-grid="gridOptions" class="grid-table" ui-grid-auto-resize ui-grid-cellNav ui-grid-edit ui-grid-resize-columns ui-grid-pinning ng-style="getTableHeight()"></div>
                </div>
            </div>
</code>```

Now i want when my page loads Location tab should have blue background how can i get that.

答:
Try this

CSS

```<code>.nav li.active a,
.nav li a:hover,
.nav li.active a:focus,
.nav li.active a:hover{
  background-color:red;
}
</code>```

Link for reference

hope this helps..

Body:
This is my HTML Code. I want css styling for active nav-tab.Now i want when my page loads Location tab should have blue background how can i get that

         Location

                         Heartbeats

                        Reboots

                        Reconnects

                        Charge

Location tab is the active tab

Now i want when my page loads Location tab should have blue background how can i get that.

Body:
Try this

CSS

.nav li.active a,
.nav li a:hover,
.nav li.active a:focus,
.nav li.active a:hover{
  background-color:red;
}

Link for reference

hope this helps..


问:
Use asp include to include asp.net page
I have an asp page that uses includes to include certain pages depending on the query string.
I have built an addition to this page in asp.net and want to include my new page in the asp page, but i get this error.</p>

```<code>  Active Server Pages error 'ASP 0140'

    Page Command Out Of Order

    /d//Default.aspx, line 1

    The @ command must be the first command within the Active Server Page.
</code>```

答:
You can't include an ASP.NET page in an ASP page. You can't mix them in the same response.

Use Response.Redirect to make a redirect to the ASP.NET page instead.

Note that you are actually not selecting what page to include in your ASP page, you are always including all of the pages, as the include is done before any ASP code starts, and then the conditional statements only decide which of the pages to run.

Title: Use asp include to include asp.net page

Body:
I have an asp page that uses includes to include certain pages depending on the query string.
I have built an addition to this page in asp.net and want to include my new page in the asp page, but i get this error.

  Active Server Pages error 'ASP 0140'

    Page Command Out Of Order

    /d//Default.aspx, line 1

    The @ command must be the first command within the Active Server Page.


问:
Pandas groupby plot with different X-Axis order
I'm working on titanic.csv, and trying to make some plots. Running into one issue. How can I re-organize the x-axis to place the same pclass value next to each other.

my current code:

```<code>titanic.groupby(['Sex', 'Pclass'])['Survived'].mean().plot(kind='bar', color=my_colors)
</code>```

produce the following chart:

I'd like to place the male and female from same class next to each other to show the difference in survival rate. Any suggestion?

答:
Altair can be very handy here. Here are 3 different one-liners to produce three different visualisations of this dataset.

```<code>import seaborn as sns
titanic = sns.load_dataset("titanic")

from altair import *
</code>```

First viz.

```<code>Chart(titanic).mark_bar().encode(x='pclass:O', y='mean(survived)', column='sex').configure_cell(width=200, height=200)
</code>```

Second viz.

```<code>Chart(titanic).mark_bar().encode(x='sex:N', y='mean(survived):Q',  column='pclass:O').configure_facet_cell(
        strokeWidth=0.0).configure_cell(width=200, height=200)
</code>```

Third viz.

```<code>Chart(titanic).mark_bar().encode(x='pclass:O', y='mean(survived):Q',  color='sex:O').configure_cell(width=200, height=200)
</code>```

Body:
I'm working on titanic.csv, and trying to make some plots. Running into one issue. How can I re-organize the x-axis to place the same pclass value next to each other.

my current code:

titanic.groupby(['Sex', 'Pclass'])['Survived'].mean().plot(kind='bar', color=my_colors)

produce the following chart:

I'd like to place the male and female from same class next to each other to show the difference in survival rate. Any suggestion?

Body:
Altair can be very handy here. Here are 3 different one-liners to produce three different visualisations of this dataset.

import seaborn as sns
titanic = sns.load_dataset("titanic")

from altair import *

First viz.

Chart(titanic).mark_bar().encode(x='pclass:O', y='mean(survived)', column='sex').configure_cell(width=200, height=200)

Second viz.

Chart(titanic).mark_bar().encode(x='sex:N', y='mean(survived):Q',  column='pclass:O').configure_facet_cell(
        strokeWidth=0.0).configure_cell(width=200, height=200)

Third viz.

Chart(titanic).mark_bar().encode(x='pclass:O', y='mean(survived):Q',  color='sex:O').configure_cell(width=200, height=200)