问:
SoundCloud Stream Pause Button not Working
Here's my CodePen: https://codepen.io/tremolocreative/pen/zZJjYN

And the source is below. I just can't seem to get the pause button to work. All it does is restart a duplicate stream on top of the existing.

I've been scratching my head trying to get this to work, any help would be much appreciated.

HTML

```<code><script src="https://connect.soundcloud.com/sdk-2.0.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div id="player">
<button href="#" id="stream"></button>
</div>
</code>```

CSS

```<code>button {
  background: url('//cdn.shopify.com/s/files/1/1055/5530/t/8/assets/play-pause-sprite.svg?2157621096199230646');
  background-size: cover;
  background-position: top left;
  background-repeat: no-repeat;
  width: 20px;
  height: 20px;
  border: 0;
  outline: 0;
  display: block;
}

button.pause-sprite {
  background-position: top right;
}
</code>```

JS

```<code>var client_id = '278594df9a311b2a1a56251b3a2b0fbe';
var track_id = '293605256';
var is_playing = false;
var player;

SC.initialize({
  client_id: client_id
});

$(document).ready(function() {
  $('#stream').on('click', function() {
    $(this).toggleClass('pause-sprite');
    SC.stream('/tracks/' + track_id, function(sound) {
      player = sound;

      if (is_playing === true) {
        player.pause();
        is_playing = false;
        console.log(is_playing);
      } else if (is_playing === false){
        player.play();
        is_playing = true;
        console.log(is_playing);
      }

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

答:
I already posted a link to a codepen of this code (tweaked here to show your bg icon) The toggle icon doesn't work in the fiddle (but i can't spend MORE time on it, I'm on holiday in ~12 hrs).

THe PAUSE works!

/*jquery is the same - answer was too long, see [fiddle][2]*/```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* LAYOUT *
-----------------------------------------------*/

.cf:before,
.cf:after {
  content: " ";
  /* 1 */
  display: table;
  /* 2 */
}

.cf:after {
  clear: both;
}

.cf {
  *zoom: 1;
}

* {
  box-sizing: border-box;
}

@small: ~"screen and (min-width: 20em)";
@medium: ~"screen and (min-width: 38em)";
@large: ~"screen and (min-width: 48em)";
@extra-large: ~"screen and (min-width: 58em)";
@max: ~"screen and (min-width: 68em)";

/* COLORS *
-----------------------------------------------*/

@white: #f8f8f8;
@red: #dd4444;
@red-dark: #bf3d3f;
@red-darker: #9c3538;
@black: #1f1f1f;
@grey: #4d4d4d;
body {
  margin: 0;
  background-color: @grey;
  color: white;
  text-align: center;
  .display;
  @media @medium {
    font-size: 112.5%;
  }
}

.wrapper {
  width: 90%;
  max-width: 1200px;
  margin: 0 auto;
  overflow: hidden;
}

p.small {
  font-size: 0.8em;
}

a {
  color: @red-darker;
  &:hover {
    color: @red-dark
  }
}

a.sc-player,
.button {
  display: inline-block;
  background-image: url('//cdn.shopify.com/s/files/1/1055/5530/t/8/assets/play-pause-sprite.svg?2157621096199230646');
  //background: rgba(19, 19, 19, 0.14);
  border-radius: 4px;
  padding: 0.2em 0.2em;
  text-align: center;
  text-decoration: none;
  color: red;
  font-size: 1.5em;
  .transition;
  &:hover {
    //background: @red-darker;
    background-image: url('//cdn.shopify.com/s/files/1/1055/5530/t/8/assets/play-pause-sprite.svg?2157621096199230646');
    color: red;
  }
}

.main {
  margin-bottom: 4em;
}

.transition {
  transition: all 0.3s ease-out;
}

/* FONTS *
-----------------------------------------------*/

@import url(http://fonts.googleapis.com/css?family=Sacramento|Montserrat);
.display {
  font-family: 'Montserrat', sans-serif;
}

h1 {
  margin-top: 50px;
  .display;
  text-transform: uppercase;
  font-size: 2em;
  line-height: 1;
  -webkit-font-smoothing: antialiased;
  position: relative;
  @media @small {
    font-size: 2.5em;
  }
  @media @medium {
    font-size: 4.5em;
    margin-top: 100px;
  }
  @media @max {
    font-size: 6em;
  }
}

/* SOUNDCLOUD PLAYER *
-----------------------------------------------*/

.sc-player {
  position: relative;
  margin-bottom: 2em;
  .cf;
  a {
    text-decoration: none;
    color: #fff;
  }
  ol,
  li {
    margin: 0;
    padding: 0;
    list-style-position: inside;
  }
}

/* Artworks */

.sc-player .sc-artwork-list {
  display: none;
  float: left;
  width: 40%;
  margin-bottom: 3%;
  background-color: transparent;
  list-style-type: none;
  position: relative;
  height: 100%;
  li {
    list-style-type: none;
    display: none;
  }
  li.active {
    list-style-type: none;
    display: block;
  }
}

.sc-player .sc-artwork-list li img,
.sc-player .sc-artwork-list li div {
  list-style-type: none;
  width: 100%;
  height: auto;
}

/* controls */

.sc-player .sc-controls {
  display: block;
}

.sc-player .sc-controls a {
  text-indent: -9999px;
  content: '';
  display: block;
  background: @red-dark;
  background-image: url('//cdn.shopify.com/s/files/1/1055/5530/t/8/assets/play-pause-sprite.svg?2157621096199230646');
  background-size: cover;
  border-radius: 50%;
  width: 75px;
  height: 75px;
  margin: 0 auto;
  position: relative;
  .transition;
  @media @medium {
    width: 110px;
    height: 110px;
  }
  &:hover {
    background: @red-darker;
    background-image: url('//cdn.shopify.com/s/files/1/1055/5530/t/8/assets/play-pause-sprite.svg?2157621096199230646');
  }
  &:after {
    content: '';
    display: block;
    position: absolute;
    top: 50%;
    margin-top: -50px;
    left: 50%;
    margin-left: -50px;
    z-index: 1;
    //background: url('http://s3-us-west-2.amazonaws.com/s.cdpn.io/35376/play-pause.png');
    background-image: url('//cdn.shopify.com/s/files/1/1055/5530/t/8/assets/play-pause-sprite.svg?2157621096199230646');
    background-position: top right;
    background-size: 100px auto;
    border-radius: 50%;
    width: 100px;
    height: 100px;
    @media @medium {
      width: 90px;
      height: 90px;
      margin-top: -90px;
      margin-left: -90px;
      background-size: 180px auto;
    }
  }
}

.sc-player .sc-controls a.sc-pause:after {
  background-position: bottom;
}

.sc-scrubber .sc-time-indicators {
  background: @red-darker;
  background: rgba(19, 19, 19, 0.22);
  color: #fff;
  border-radius: 4px;
  padding: 7px;
  text-align: right;
}

.sc-player .sc-controls a.sc-pause {
  display: none;
}

.sc-player.playing .sc-controls a.sc-play {
  display: none;
}

.sc-player.playing .sc-controls a.sc-pause {
  display: block;
}

/* scrubber */

.sc-scrubber {
  position: relative;
  float: right;
  width: 100%;
  margin: 0.5em 0;
  border-radius: 4px;
  @media @medium {
    //margin-top: 20px;
  }
  .sc-time-span {
    height: 50px;
    position: relative;
  }
  .sc-buffer,
  .sc-played {
    height: 50px;
    position: absolute;
    top: 0;
  }
  .sc-time-indicators {
    position: absolute;
    right: 0;
    top: -48px;
  }
  .sc-time-span {
    //background-color: #666;
    border-radius: 4px;
    overflow: hidden;
  }
  .sc-volume-slider {
    background-color: @red-dark;
    background-color: rgba(19, 19, 19, 0.12);
    border-radius: 2px;
  }
  .sc-volume-slider .sc-volume-status {
    background-color: @red-darker;
    background-color: rgba(19, 19, 19, 0.22);
    border-right: 1px solid @red-darker;
    border-right: 1px solid rgba(19, 19, 19, 0.22);
    //border-right: 1px solid white;
  }
  .sc-waveform-container {
    z-index: 800;
    width: 50%;
    position: absolute;
  }
  .sc-time-span img {
    height: 50px;
    width: 50%;
    border-radius: 4px;
  }
  .sc-buffer {
    background: @red-dark;
    background: rgba(19, 19, 19, 0.12);
    z-index: 1;
    position: absolute;
  }
  .sc-played {
    background: @red-darker;
    background: rgba(19, 19, 19, 0.22);
    z-index: 799;
  }
}

/* volume control */

.sc-volume-slider {
  top: -35px;
  left: 0px;
  position: absolute;
  width: 75px;
  height: 20px;
  background-color: white;
  .sc-volume-status {
    position: absolute;
    width: 0%;
    height: 10px;
    top: 0;
    left: 0;
  }
}

/* tracks */

/* Track listings*/

.sc-player ol.sc-trackslist {
  position: relative;
  width: 50%;
  overflow: auto;
  li {
    width: 50%;
    cursor: pointer;
    margin-bottom: 0.5em;
    padding: 4%;
    background: @red-dark;
    background: rgba(19, 19, 19, 0.12);
    color: white;
    border-radius: 4px;
    transition: background 0.3s ease-in;
    text-align: left;
    @media @medium {
      padding: 2%;
    }
    &:last-child {
      margin-bottom: 0;
    }
    a {
      font-size: 1.125em;
      @media @small {}
      @media @medium {
        font-size: 2em;
      }
    }
    &:hover {
      background: @red-darker;
      background: rgba(19, 19, 19, 0.22);
    }
    &.active {
      background: @red-darker;
      background: rgba(19, 19, 19, 0.32);
      -moz-border-radius: 4px;
      -webkit-border-radius: 4px;
      a {
        color: #fff;
      }
    }
  }
}

.sc-track-duration {
  float: right;
  margin-top: 0.25em;
  @media @medium {
    margin-top: 0.5em;
  }
}

/* Track info*/

.sc-player .sc-info {
  position: relative;
  margin-bottom: 2em;
  padding: 1% 3%;
  @media @medium {
    margin-top: 1em;
    margin-bottom: 3em;
  }
  h3 {
    font-size: 2em;
    margin-bottom: 0.5em;
  }
  h4 {
    display: none;
  }
  .sc-info a {
    color: #fff;
  }
}

p {
  max-width: 19em;
  max-width: 19rem;
  margin: 0 auto 1em;
  line-height: 1.5;
  text-align: left;
}

.sc-player .sc-info-toggle,
.sc-player .sc-info-close {
  display: none;
}

/* utilities */

.sc-player .hidden {
  //display: none;
}

.sc-player-engine-container {
  width: 1px;
  height: 1px;
  position: fixed;
  top: 2px;
  left: 2px;
}

.sc-player .sc-info-toggle {
  background: #22B573;
  color: #fff;
  border-radius: 1px;
  padding: 4px;
}

.sc-player .sc-info-toggle:hover {
  background: #333;
  color: #fff;
}

.sc-player .sc-info-close {
  background: #22B573;
  border-radius: 4px;
  padding: 2px 4px;
  font-weight: bold;
}</code>```

Soundcloud Player

    Listen

```

Body:
Here's my CodePen: https://codepen.io/tremolocreative/pen/zZJjYN

And the source is below. I just can't seem to get the pause button to work. All it does is restart a duplicate stream on top of the existing.

I've been scratching my head trying to get this to work, any help would be much appreciated.

HTML

<button href="#" id="stream"></button>

CSS

button {
  background: url('//cdn.shopify.com/s/files/1/1055/5530/t/8/assets/play-pause-sprite.svg?2157621096199230646');
  background-size: cover;
  background-position: top left;
  background-repeat: no-repeat;
  width: 20px;
  height: 20px;
  border: 0;
  outline: 0;
  display: block;
}

button.pause-sprite {
  background-position: top right;
}

JS

var client_id = '278594df9a311b2a1a56251b3a2b0fbe';
var track_id = '293605256';
var is_playing = false;
var player;

SC.initialize({
  client_id: client_id
});

$(document).ready(function() {
  $('#stream').on('click', function() {
    $(this).toggleClass('pause-sprite');
    SC.stream('/tracks/' + track_id, function(sound) {
      player = sound;

      if (is_playing === true) {
        player.pause();
        is_playing = false;
        console.log(is_playing);
      } else if (is_playing === false){
        player.play();
        is_playing = true;
        console.log(is_playing);
      }

    });
  });
});

Body:
I already posted a link to a codepen of this code (tweaked here to show your bg icon) The toggle icon doesn't work in the fiddle (but i can't spend MORE time on it, I'm on holiday in ~12 hrs).

THe PAUSE works!

/*jquery is the same - answer was too long, see [fiddle][2]*/

/* LAYOUT *
-----------------------------------------------*/

.cf:before,
.cf:after {
  content: " ";
  /* 1 */
  display: table;
  /* 2 */
}

.cf:after {
  clear: both;
}

.cf {
  *zoom: 1;
}

* {
  box-sizing: border-box;
}

@small: ~"screen and (min-width: 20em)";
@medium: ~"screen and (min-width: 38em)";
@large: ~"screen and (min-width: 48em)";
@extra-large: ~"screen and (min-width: 58em)";
@max: ~"screen and (min-width: 68em)";

/* COLORS *
-----------------------------------------------*/

@white: #f8f8f8;
@red: #dd4444;
@red-dark: #bf3d3f;
@red-darker: #9c3538;
@black: #1f1f1f;
@grey: #4d4d4d;
body {
  margin: 0;
  background-color: @grey;
  color: white;
  text-align: center;
  .display;
  @media @medium {
    font-size: 112.5%;
  }
}

.wrapper {
  width: 90%;
  max-width: 1200px;
  margin: 0 auto;
  overflow: hidden;
}

p.small {
  font-size: 0.8em;
}

a {
  color: @red-darker;
  &:hover {
    color: @red-dark
  }
}

a.sc-player,
.button {
  display: inline-block;
  background-image: url('//cdn.shopify.com/s/files/1/1055/5530/t/8/assets/play-pause-sprite.svg?2157621096199230646');
  //background: rgba(19, 19, 19, 0.14);
  border-radius: 4px;
  padding: 0.2em 0.2em;
  text-align: center;
  text-decoration: none;
  color: red;
  font-size: 1.5em;
  .transition;
  &:hover {
    //background: @red-darker;
    background-image: url('//cdn.shopify.com/s/files/1/1055/5530/t/8/assets/play-pause-sprite.svg?2157621096199230646');
    color: red;
  }
}

.main {
  margin-bottom: 4em;
}

.transition {
  transition: all 0.3s ease-out;
}

/* FONTS *
-----------------------------------------------*/

@import url(http://fonts.googleapis.com/css?family=Sacramento|Montserrat);
.display {
  font-family: 'Montserrat', sans-serif;
}

h1 {
  margin-top: 50px;
  .display;
  text-transform: uppercase;
  font-size: 2em;
  line-height: 1;
  -webkit-font-smoothing: antialiased;
  position: relative;
  @media @small {
    font-size: 2.5em;
  }
  @media @medium {
    font-size: 4.5em;
    margin-top: 100px;
  }
  @media @max {
    font-size: 6em;
  }
}

/* SOUNDCLOUD PLAYER *
-----------------------------------------------*/

.sc-player {
  position: relative;
  margin-bottom: 2em;
  .cf;
  a {
    text-decoration: none;
    color: #fff;
  }
  ol,
  li {
    margin: 0;
    padding: 0;
    list-style-position: inside;
  }
}

/* Artworks */

.sc-player .sc-artwork-list {
  display: none;
  float: left;
  width: 40%;
  margin-bottom: 3%;
  background-color: transparent;
  list-style-type: none;
  position: relative;
  height: 100%;
  li {
    list-style-type: none;
    display: none;
  }
  li.active {
    list-style-type: none;
    display: block;
  }
}

.sc-player .sc-artwork-list li img,
.sc-player .sc-artwork-list li div {
  list-style-type: none;
  width: 100%;
  height: auto;
}

/* controls */

.sc-player .sc-controls {
  display: block;
}

.sc-player .sc-controls a {
  text-indent: -9999px;
  content: '';
  display: block;
  background: @red-dark;
  background-image: url('//cdn.shopify.com/s/files/1/1055/5530/t/8/assets/play-pause-sprite.svg?2157621096199230646');
  background-size: cover;
  border-radius: 50%;
  width: 75px;
  height: 75px;
  margin: 0 auto;
  position: relative;
  .transition;
  @media @medium {
    width: 110px;
    height: 110px;
  }
  &:hover {
    background: @red-darker;
    background-image: url('//cdn.shopify.com/s/files/1/1055/5530/t/8/assets/play-pause-sprite.svg?2157621096199230646');
  }
  &:after {
    content: '';
    display: block;
    position: absolute;
    top: 50%;
    margin-top: -50px;
    left: 50%;
    margin-left: -50px;
    z-index: 1;
    //background: url('http://s3-us-west-2.amazonaws.com/s.cdpn.io/35376/play-pause.png');
    background-image: url('//cdn.shopify.com/s/files/1/1055/5530/t/8/assets/play-pause-sprite.svg?2157621096199230646');
    background-position: top right;
    background-size: 100px auto;
    border-radius: 50%;
    width: 100px;
    height: 100px;
    @media @medium {
      width: 90px;
      height: 90px;
      margin-top: -90px;
      margin-left: -90px;
      background-size: 180px auto;
    }
  }
}

.sc-player .sc-controls a.sc-pause:after {
  background-position: bottom;
}

.sc-scrubber .sc-time-indicators {
  background: @red-darker;
  background: rgba(19, 19, 19, 0.22);
  color: #fff;
  border-radius: 4px;
  padding: 7px;
  text-align: right;
}

.sc-player .sc-controls a.sc-pause {
  display: none;
}

.sc-player.playing .sc-controls a.sc-play {
  display: none;
}

.sc-player.playing .sc-controls a.sc-pause {
  display: block;
}

/* scrubber */

.sc-scrubber {
  position: relative;
  float: right;
  width: 100%;
  margin: 0.5em 0;
  border-radius: 4px;
  @media @medium {
    //margin-top: 20px;
  }
  .sc-time-span {
    height: 50px;
    position: relative;
  }
  .sc-buffer,
  .sc-played {
    height: 50px;
    position: absolute;
    top: 0;
  }
  .sc-time-indicators {
    position: absolute;
    right: 0;
    top: -48px;
  }
  .sc-time-span {
    //background-color: #666;
    border-radius: 4px;
    overflow: hidden;
  }
  .sc-volume-slider {
    background-color: @red-dark;
    background-color: rgba(19, 19, 19, 0.12);
    border-radius: 2px;
  }
  .sc-volume-slider .sc-volume-status {
    background-color: @red-darker;
    background-color: rgba(19, 19, 19, 0.22);
    border-right: 1px solid @red-darker;
    border-right: 1px solid rgba(19, 19, 19, 0.22);
    //border-right: 1px solid white;
  }
  .sc-waveform-container {
    z-index: 800;
    width: 50%;
    position: absolute;
  }
  .sc-time-span img {
    height: 50px;
    width: 50%;
    border-radius: 4px;
  }
  .sc-buffer {
    background: @red-dark;
    background: rgba(19, 19, 19, 0.12);
    z-index: 1;
    position: absolute;
  }
  .sc-played {
    background: @red-darker;
    background: rgba(19, 19, 19, 0.22);
    z-index: 799;
  }
}

/* volume control */

.sc-volume-slider {
  top: -35px;
  left: 0px;
  position: absolute;
  width: 75px;
  height: 20px;
  background-color: white;
  .sc-volume-status {
    position: absolute;
    width: 0%;
    height: 10px;
    top: 0;
    left: 0;
  }
}

/* tracks */

/* Track listings*/

.sc-player ol.sc-trackslist {
  position: relative;
  width: 50%;
  overflow: auto;
  li {
    width: 50%;
    cursor: pointer;
    margin-bottom: 0.5em;
    padding: 4%;
    background: @red-dark;
    background: rgba(19, 19, 19, 0.12);
    color: white;
    border-radius: 4px;
    transition: background 0.3s ease-in;
    text-align: left;
    @media @medium {
      padding: 2%;
    }
    &:last-child {
      margin-bottom: 0;
    }
    a {
      font-size: 1.125em;
      @media @small {}
      @media @medium {
        font-size: 2em;
      }
    }
    &:hover {
      background: @red-darker;
      background: rgba(19, 19, 19, 0.22);
    }
    &.active {
      background: @red-darker;
      background: rgba(19, 19, 19, 0.32);
      -moz-border-radius: 4px;
      -webkit-border-radius: 4px;
      a {
        color: #fff;
      }
    }
  }
}

.sc-track-duration {
  float: right;
  margin-top: 0.25em;
  @media @medium {
    margin-top: 0.5em;
  }
}

/* Track info*/

.sc-player .sc-info {
  position: relative;
  margin-bottom: 2em;
  padding: 1% 3%;
  @media @medium {
    margin-top: 1em;
    margin-bottom: 3em;
  }
  h3 {
    font-size: 2em;
    margin-bottom: 0.5em;
  }
  h4 {
    display: none;
  }
  .sc-info a {
    color: #fff;
  }
}

p {
  max-width: 19em;
  max-width: 19rem;
  margin: 0 auto 1em;
  line-height: 1.5;
  text-align: left;
}

.sc-player .sc-info-toggle,
.sc-player .sc-info-close {
  display: none;
}

/* utilities */

.sc-player .hidden {
  //display: none;
}

.sc-player-engine-container {
  width: 1px;
  height: 1px;
  position: fixed;
  top: 2px;
  left: 2px;
}

.sc-player .sc-info-toggle {
  background: #22B573;
  color: #fff;
  border-radius: 1px;
  padding: 4px;
}

.sc-player .sc-info-toggle:hover {
  background: #333;
  color: #fff;
}

.sc-player .sc-info-close {
  background: #22B573;
  border-radius: 4px;
  padding: 2px 4px;
  font-weight: bold;
}

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<body>
  <header class="site-header wrapper">
    <h1>Soundcloud Player</h1>
  </header>
  <section role="main" class="main wrapper">
    <a href="https://soundcloud.com/ritchrd/fly-feat-ritchrd" class="sc-player">Listen</a>

  </section>
</body>


来源: stackexchange

问:
WebDriver Chrome Browser: Avoid 'Do you want chrome to save your password' pop up
Every time my webdriver tests login into the application, 'Do you want chrome to save your password' pop up appears.. Is there a way to avoid this??

Please help.

Thanks,
Mike

答:
Thanks to @karanvir Kang comment above, I added the following to my conf.js which I use when I call protractor.  Example

```<code>protractor tests/conf.js --specs /tests/e2e/myspec.spec.js
</code>```

And in my conf.js

```<code>exports.config = {
    seleniumAddress: 'http://localhost:4444/wd/hub',
    seleniumPort: '4455',
    baseUrl: url,
    directConnect: false,
    //getMultiCapabilities: helper.getFirefoxProfile,
    capabilities: {
        browserName: 'chrome',
        chromeOptions: {
            prefs: {
                'credentials_enable_service': false,
                'profile': {
                    'password_manager_enabled': false
                }
            },
            args: [
                '--disable-cache',
                '--disable-application-cache',
                '--disable-offline-load-stale-cache',
                '--disk-cache-size=0',
                '--v8-cache-options=off'
            ]
        }
    },
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Thanks to @karanvir Kang comment above, I added the following to my conf.js which I use when I call protractor.  Example

protractor tests/conf.js --specs /tests/e2e/myspec.spec.js

And in my conf.js

exports.config = {
    seleniumAddress: 'http://localhost:4444/wd/hub',
    seleniumPort: '4455',
    baseUrl: url,
    directConnect: false,
    //getMultiCapabilities: helper.getFirefoxProfile,
    capabilities: {
        browserName: 'chrome',
        chromeOptions: {
            prefs: {
                'credentials_enable_service': false,
                'profile': {
                    'password_manager_enabled': false
                }
            },
            args: [
                '--disable-cache',
                '--disable-application-cache',
                '--disable-offline-load-stale-cache',
                '--disk-cache-size=0',
                '--v8-cache-options=off'
            ]
        }
    },


问:
Is the Win32_Processor and Win32_NetworkAdapterConfiguration WMI methods available in Windows 8?
I am testing an existing application in the Windows 8 consumer preview and it crashes upon launching.  The log files indicate it is in the method where I do some validation on the CPU ID and Network card details.

To do this, I am calling

```<code>        ManagementClass mc = new ManagementClass("Win32_Processor");
        ManagementObjectCollection moc = mc.GetInstances();
        foreach (ManagementObject mo in moc)
        {
            if (cpuInfo.Length == 0)
            {
                // only return cpuInfo from first CPU
                cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
            }
        }
</code>```

(Note that this application works fine on Windows 7 and earlier).

I then use the same syntax for hooking into Win32_NetworkAdapterConfiguration and getting the IPEnabled, IPAddress[], and MACAddress properties.

But somewhere in here it is crashing.

I have tried to research this already, and found the following Windows 8 server list of WMI classes and methods and the ones I am using are not on it.  However, the same site has a list of Windows 7 WMI classes and methods too, and these aren't in that either! (Even though it works on Windows 7 no problem).

So from the look of that, it is not supported.

The MSDN for the ManagementClass indicates that the method is still present in .NET 4.5.  Additionally, this Microsoft resource does explicitly list Win32_Processor and Win32_NetworkAdapterConfiguration, with the methods I need.

So, from the links, you can see I have tried to research this, so this is my last stop in trying to solve this mystery.

My app is originally a .NET 2.0 solution created in Visual Studio 2005.  I have installed Visual Studio 2011 Beta into my Windows 8 Consumer Preview VM, along with the latest SQL 2012 Express.  I have tried importing my project into this Visual Studio but it doesn't load it, telling me that it only supports Metro development.  Therefore I cannot debug this issue on the machine itself.

So my question is specifically do these classes exist in Windows 8?  If they do, then what am I doing wrong?  If they don't, then I need to find out a way to still get this information - but I guess that's a separate question ;-)

答:
The WMI methods were available in Windows 8, but were removed in Windows 8.1, so alternatively, you could use this code to analyze various network metrics on Windows 8.1 and Windows Phone 8:

https://code.msdn.microsoft.com/windowsapps/network-information-sample-63aaa201

Body:
I am testing an existing application in the Windows 8 consumer preview and it crashes upon launching.  The log files indicate it is in the method where I do some validation on the CPU ID and Network card details.

To do this, I am calling

        ManagementClass mc = new ManagementClass("Win32_Processor");
        ManagementObjectCollection moc = mc.GetInstances();
        foreach (ManagementObject mo in moc)
        {
            if (cpuInfo.Length == 0)
            {
                // only return cpuInfo from first CPU
                cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
            }
        }

(Note that this application works fine on Windows 7 and earlier).

I then use the same syntax for hooking into Win32_NetworkAdapterConfiguration and getting the IPEnabled, IPAddress[], and MACAddress properties.

But somewhere in here it is crashing.

I have tried to research this already, and found the following Windows 8 server list of WMI classes and methods and the ones I am using are not on it.  However, the same site has a list of Windows 7 WMI classes and methods too, and these aren't in that either! (Even though it works on Windows 7 no problem).

So from the look of that, it is not supported.

The MSDN for the ManagementClass indicates that the method is still present in .NET 4.5.  Additionally, this Microsoft resource does explicitly list Win32_Processor and Win32_NetworkAdapterConfiguration, with the methods I need.

So, from the links, you can see I have tried to research this, so this is my last stop in trying to solve this mystery.

My app is originally a .NET 2.0 solution created in Visual Studio 2005.  I have installed Visual Studio 2011 Beta into my Windows 8 Consumer Preview VM, along with the latest SQL 2012 Express.  I have tried importing my project into this Visual Studio but it doesn't load it, telling me that it only supports Metro development.  Therefore I cannot debug this issue on the machine itself.

So my question is specifically do these classes exist in Windows 8?  If they do, then what am I doing wrong?  If they don't, then I need to find out a way to still get this information - but I guess that's a separate question ;-)


问:
Find a table to merge with
In the web application of google fusion tables there is an option "find a table to merge with" which searches for the most similar tables for the specific table.
Is there an option to do it with the api as well?</p>

答: No, unfortunately the service this feature uses is only accessible from the Fusion Tables app.</p>

Title: Find a table to merge with


问:
Ignoring exceptions when using c# selenium webdriverWait wait.untill() function
In order to check if an Element is exists and clickble  i'm trying to write a boolean method which will wait for the element to be enabled and displyed using C# selenium's webDriverWait as follow:

```<code>webDriverWait wait = new webDriverWait(driver, timeSpan.fromSeconds(60));

Wait.untill( d => webElement.enabled() && webElement.displayed());
</code>```

In case the above conditions do not happen, I want the method to return 'false'. The problem is that I get exceptions thrown.
How can I ignore exceptions such as noSuchElementException and timeOutException in case they are thrown?
I have tried to use try catch block but it didn't help and exceptions were thrown.

答:
If you wait for the element to be clickable, it will also be displayed and enabled. You can simply do

```<code>public bool IsElementClickable(By locator, int timeOut)
{
    try
    {
        new WebDriverWait(Driver, TimeSpan.FromSeconds(timeOut)).Until(ExpectedConditions.ElementToBeClickable(locator));

        return true;
    }
    catch (WebDriverTimeoutException)
    {
        return false;
    }
}
</code>```

and it will wait for 60s and click the element once it is found. It still may throw an exception if the element is not found, doesn't become clickable, etc. after the timeout expires.

EDIT:
Wrapped this up in a function based on OPs comment.

ContentLicense: CC BY-SA 4.0

Body:
In order to check if an Element is exists and clickble  i'm trying to write a boolean method which will wait for the element to be enabled and displyed using C# selenium's webDriverWait as follow:

webDriverWait wait = new webDriverWait(driver, timeSpan.fromSeconds(60));

Wait.untill( d => webElement.enabled() && webElement.displayed());

In case the above conditions do not happen, I want the method to return 'false'. The problem is that I get exceptions thrown.
How can I ignore exceptions such as noSuchElementException and timeOutException in case they are thrown?
I have tried to use try catch block but it didn't help and exceptions were thrown.

Body:
If you wait for the element to be clickable, it will also be displayed and enabled. You can simply do

public bool IsElementClickable(By locator, int timeOut)
{
    try
    {
        new WebDriverWait(Driver, TimeSpan.FromSeconds(timeOut)).Until(ExpectedConditions.ElementToBeClickable(locator));

        return true;
    }
    catch (WebDriverTimeoutException)
    {
        return false;
    }
}

and it will wait for 60s and click the element once it is found. It still may throw an exception if the element is not found, doesn't become clickable, etc. after the timeout expires.

EDIT:
Wrapped this up in a function based on OPs comment.


问:
Apache (xamp) and IIS cannot work together
I have XAMP 1.6.8 and IIS 5.0 installed on my PC(Windows XP SP3).

I'm unable to run them simultaneously. If IIS service is running, Apache throws the following error:

(OS 10048)Only one usage of each socket address (protocol/network address/port) is normally permitted. : make_sock: could not bind to address 0.0.0.0:80 no listening sockets available, shutting down Unable to open logs Note the errors or messages above, and press the key to exit. 24...

Windows could not start the Apache2 on Local Computer. For more information, review the System Event Log. If this is a non-Microsoft service, contact the service vendor, and refer to service-specific error code 1.

Edit:

Apache runs on a different port 3128. And IIS (asp.net) usually runs on a different port.

答:
You need to configure either Apache or IIS to listen on a different port.

You can also use tcpview to check which ports are in use by which applications since it sounds like you have a conflict.

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Peter Hilton

OwnerDisplayName: edg

LastEditorDisplayName: edg


问:
Drools - Doing Complex Stuff inside a Rule Condition or Consequence
In my company we are planning to use Drools a BRE for couple of projects. Now we trying to define some best-practices.

My question is what should be and shouldn't be done inside a Rule  Condition/Consequence.
Given that we can write Java directly or call methods (for example From a Global object in the Working Memory).

Example. Given a Rule that evaluates a generic Object (e.g. Person) have property set to true. Now, that specific propertie can only be defined for that Object going to the database and fetching that info.  So we have two ways of implementing that:

Alternative A:

Go to the database and fetch the object property (true/false,  a code)

Insert the Object in the working memory

Evaluate the rule

Alternative B:

Insert a Global Object that has a method that connects to the database and check for the property for the given object.

Insert the Object to eval in Working Memory

In the rule, call the Global Object and perform the access to the database

Which of those is considered better? I really like A, but sometimes B is more straightforward, however what would happen if something like a Exception from the Database is raised?

I have seen the alternative B implemented  in the Drools 5.0 Book from Packt Publishing,however they are doing a mocking and they don't talk about the actual implications of going to the database at all.

Thank you,

答:
One of the things about rules is that they can be executed many, many times.  Particularly if you make an error with your rule conditions.  That obviously has a performance impact.

I'm inclined then to prefer option A, prepare your facts outside, and insert them into working memory for evaluation.

Certainly, there is also the option of partitioning the rules into data loading rules then business rule evaluation (using Rule flow for instance).

That would give you declarative control of populating your data outside of code.


问:
Last entry on join table
I've two table "questionnaires" and "question" link by  the table "question_questionnaire". I want to retrive all questions of the last questionnaire with questionnaire.cible="personnel". I'm using laravel 5.3.

I've tried this but it doesn't work :

```<code>DB::table('questions')
 ->join('question_questionnaire','question_questionnaire.question_id','=','questions.id')
 ->join('questionnaires','questionnaires.id','=','question_questionnaire.questionnaire_id')
 ->orderBy('questionnaires.created_at','desc')
 ->first()->where('questionnaires.cible','=','personnel')->get();
</code>```

Could you help me?

答:
This should do it:     </p>

```<code>DB::table('questions')
        ->join('question_questionnaire','question_questionnaire.question_id','=','questions.id')
        ->join('questionnaires','questionnaires.id','=','question_questionnaire.questionnaire_id')
        ->whereRaw('questionnaires.id = (select max(id) from questionnaires where cible = ?)',['personel'])
        ->get();
</code>```

Title: Last entry on join table

Body:
I've two table "questionnaires" and "question" link by  the table "question_questionnaire". I want to retrive all questions of the last questionnaire with questionnaire.cible="personnel". I'm using laravel 5.3.

I've tried this but it doesn't work :

DB::table('questions')
 ->join('question_questionnaire','question_questionnaire.question_id','=','questions.id')
 ->join('questionnaires','questionnaires.id','=','question_questionnaire.questionnaire_id')
 ->orderBy('questionnaires.created_at','desc')
 ->first()->where('questionnaires.cible','=','personnel')->get();

Could you help me?

Body:
This should do it:

DB::table('questions')
        ->join('question_questionnaire','question_questionnaire.question_id','=','questions.id')
        ->join('questionnaires','questionnaires.id','=','question_questionnaire.questionnaire_id')
        ->whereRaw('questionnaires.id = (select max(id) from questionnaires where cible = ?)',['personel'])
        ->get();


问:
According to what property does collect() sort its output?
Is the collection given by using the aggregation "collect()" on many nodes, sorted after a specific property or id, or is the order random? I've looked at the documentation but didn't find anything helpful.</p>

答:
It depends on how you build up the paths for what you are collecting.

You can use an ORDER BY to ensure the elements are ordered. For example:

```<code>// Don't specify order
MATCH (p:Crew)
RETURN COLLECT(p.name) AS people

> [Neo, Morpheus, Trinity, Cypher]
</code>```

In the case above the ordering ends up being according to the internal node id, which we can confirm by collecting that value along with the name property:

```<code>MATCH (p:Crew)
RETURN COLLECT({name: p.name, id: id(p)}) AS people

> [ {name:"Neo", id:0},  {name:"Morpheus", id:1},  {name:"Trinity", id:2},  {name:"Cypher", id:3}]
</code>```

But we can use an ORDER BY to explicitly specify the order for the elements in our collection:

```<code>// Order by name, ascending
MATCH (p:Crew)
WITH p ORDER BY p.name ASC
RETURN COLLECT(p.name) AS people

> [Cypher, Morpheus, Neo, Trinity]
</code>```

There is a simple example here: http://console.neo4j.org/r/bqxlmx

Body:
It depends on how you build up the paths for what you are collecting.

You can use an ORDER BY to ensure the elements are ordered. For example:

// Don't specify order
MATCH (p:Crew)
RETURN COLLECT(p.name) AS people

> [Neo, Morpheus, Trinity, Cypher]

In the case above the ordering ends up being according to the internal node id, which we can confirm by collecting that value along with the name property:

MATCH (p:Crew)
RETURN COLLECT({name: p.name, id: id(p)}) AS people

> [ {name:"Neo", id:0},  {name:"Morpheus", id:1},  {name:"Trinity", id:2},  {name:"Cypher", id:3}]

But we can use an ORDER BY to explicitly specify the order for the elements in our collection:

// Order by name, ascending
MATCH (p:Crew)
WITH p ORDER BY p.name ASC
RETURN COLLECT(p.name) AS people

> [Cypher, Morpheus, Neo, Trinity]

There is a simple example here: http://console.neo4j.org/r/bqxlmx


问:
Is it possible to retrieve data from a 3rd party App by my own Android app?
I'm too much of an android novice to comprehend the more detailed postings wrt this topic on stackoverflow, so I hope I can ask this simple yes/no question instead.
I have my own flashcard android app and (due to lack of translation APIs, a different story ...) I thought I could utilized a 3rd party dictionary app I have installed on my phone (this is just for me, not for productation, so no concern about how this scales to other phones/envs).
So it sounds like it might be possible to launch the 3rd party app from my app, but it doesn't sound possible to retrieve data from the 3rd party app and consume it in my own i.e. I would have to know the source code of the 3rd party app to understand intent and activity names (and its manifest ?)

So here's the naive/simple question, is it possible to simply launch the app, navigate to the page/activity I'm interested in (since I assume I can't jump directly to it since I don't know the details) and 'swipe/parse' the output of that app and return to my app ?

答: To my knowledge there is no way to do this without the 3rd party having implemented a Content Provider. At least there is no easy way since it would be a huge security issue. Since this is a dictionary app in question, I would suggest using a dictionary API if this is a viable option for you. </p>


问:
What's the best way to load a yaml file to Map(not an environment configuration file) in spring boot web project?
In my data framework layer, I'd like to read an yaml from src/main/resources.
The file name is mapconfigure.yaml. It's associated with the business data, not just environment configuration data.

Its content's like:

```<code>person1:
  name: aaa
  addresses:
    na: jiang
    sb: su
person2:
  name: bbb
  addresses:
    to: jiang
    bit: su
</code>```

I want to store this information into a HashMap.

Does it mean to use some spring annotation like @ConfigurationProperties?
How to achieve this in details?

In addition, I can't change the file name. It means I have to use mapconfigure.yaml as the file name, not application.yml or application.properties.

The structure of my HashMap is as follows:

```<code>HashMap<String, Setting>

@Data
public class Setting{
  private String name;
  private HashMap<String, String> addresses
}
</code>```

My expected HashMap's as follows:

```<code>{person1={name=aaa, addresses={na=jiang, sb=su}}, person2={name=bbb, addresses={to=jiang, bit=su}}}
</code>```

I'm not sure if I can use YamlMapFactoryBean class to do this.

The return type of the getObject method in YamlMapFactoryBean class is Map<String, Object>, not a generic type, like Map<String, T>.

Spring boot doc just said

Spring Framework provides two convenient classes that can be used to load YAML documents. The YamlPropertiesFactoryBean will load YAML as Properties and the YamlMapFactoryBean will load YAML as a Map.

But there isn't a detailed example.

UPDATE:

In github, I created a sample. It's Here.
In this sample, I want to load myconfig.yaml to theMapProperties object in SamplePropertyLoadingTest class. Spring boot version is 1.5.1, so I can't use location attribute of @ConfigurationProperties.
How to do this?

答:
You can indeed achieve this with @ConfigurationProperties.

From Spring Boot 1.5.x onwards (lack of @ConfigurationProperies locations attr.):

```<code>new SpringApplicationBuilder(Application.class)
    .properties("spring.config.name=application,your-filename")
    .run(args);

@Component
@ConfigurationProperties
public class TheProperties {
    private Map<String, Person> people;
    // getters and setters are omitted for brevity
}
</code>```

In Spring Boot 1.3.x:

```<code>@Component
@ConfigurationProperties(locations = "classpath:your-filename.yml")
public class TheProperties {
    private Map<String, Person> people;
    // getters and setters are omitted for brevity
}
</code>```

The Person class for above examples looks like this:

```<code>public class Person {
    private String name;
    private Map<String, String> addresses;
    // getters and setters are omitted for brevity
}
</code>```

I have tested the code with the following file: your-filename.yml
defined in src/main/resources, the contents:

```<code>people:
  person1:
    name: "aaa"
    addresses:
      na: "jiang"
      sb: "su"
  person2:
    name: "bbb"
    addresses:
      to: "jiang"
      bit: "su"
</code>```

Please let me know if you need any further assistance.

Body:
In my data framework layer, I'd like to read an yaml from src/main/resources.
The file name is mapconfigure.yaml. It's associated with the business data, not just environment configuration data.

Its content's like:

person1:
  name: aaa
  addresses:
    na: jiang
    sb: su
person2:
  name: bbb
  addresses:
    to: jiang
    bit: su

I want to store this information into a HashMap.

Does it mean to use some spring annotation like @ConfigurationProperties?
How to achieve this in details?

In addition, I can't change the file name. It means I have to use mapconfigure.yaml as the file name, not application.yml or application.properties.

The structure of my HashMap is as follows:

HashMap<String, Setting>

@Data
public class Setting{
  private String name;
  private HashMap<String, String> addresses
}

My expected HashMap's as follows:

{person1={name=aaa, addresses={na=jiang, sb=su}}, person2={name=bbb, addresses={to=jiang, bit=su}}}

I'm not sure if I can use YamlMapFactoryBean class to do this.

The return type of the getObject method in YamlMapFactoryBean class is Map<String, Object>, not a generic type, like Map<String, T>.

Spring boot doc just said

Spring Framework provides two convenient classes that can be used to load YAML documents. The YamlPropertiesFactoryBean will load YAML as Properties and the YamlMapFactoryBean will load YAML as a Map.

But there isn't a detailed example.

UPDATE:

In github, I created a sample. It's Here.
In this sample, I want to load myconfig.yaml to theMapProperties object in SamplePropertyLoadingTest class. Spring boot version is 1.5.1, so I can't use location attribute of @ConfigurationProperties.
How to do this?

Body:
You can indeed achieve this with @ConfigurationProperties.

From Spring Boot 1.5.x onwards (lack of @ConfigurationProperies locations attr.):

new SpringApplicationBuilder(Application.class)
    .properties("spring.config.name=application,your-filename")
    .run(args);

@Component
@ConfigurationProperties
public class TheProperties {
    private Map<String, Person> people;
    // getters and setters are omitted for brevity
}

In Spring Boot 1.3.x:

@Component
@ConfigurationProperties(locations = "classpath:your-filename.yml")
public class TheProperties {
    private Map<String, Person> people;
    // getters and setters are omitted for brevity
}

The Person class for above examples looks like this:

public class Person {
    private String name;
    private Map<String, String> addresses;
    // getters and setters are omitted for brevity
}

I have tested the code with the following file: your-filename.yml
defined in src/main/resources, the contents:

people:
  person1:
    name: "aaa"
    addresses:
      na: "jiang"
      sb: "su"
  person2:
    name: "bbb"
    addresses:
      to: "jiang"
      bit: "su"

Please let me know if you need any further assistance.


问:
How to convert a public key from a JWK into PEM for OpenSSL?
There is an RSA key from an RFC:

https://www.rfc-editor.org/rfc/rfc7516#appendix-A.1

```<code> {"kty":"RSA",
  "n":"oahUIoWw0K0usKNuOR6H4wkf4oBUXHTxRvgb48E-BVvxkeDNjbC4he8rUW
       cJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3S
       psk_ZkoFnilakGygTwpZ3uesH-PFABNIUYpOiN15dsQRkgr0vEhxN92i2a
       sbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h-QChLOln0_mtUZwfsRaMS
       tPs6mS6XrgxnxbWhojf663tuEQueGC-FCMfra36C9knDFGzKsNa7LZK2dj
       YgyD3JR_MB_4NUJW_TqOQtwHYbxevoJArm-L5StowjzGy-_bq6Gw",
  "e":"AQAB",
  "d":"kLdtIj6GbDks_ApCSTYQtelcNttlKiOyPzMrXHeI-yk1F7-kpDxY4-WY5N
       WV5KntaEeXS1j82E375xxhWMHXyvjYecPT9fpwR_M9gV8n9Hrh2anTpTD9
       3Dt62ypW3yDsJzBnTnrYu1iwWRgBKrEYY46qAZIrA2xAwnm2X7uGR1hghk
       qDp0Vqj3kbSCz1XyfCs6_LehBwtxHIyh8Ripy40p24moOAbgxVw3rxT_vl
       t3UVe4WO3JkJOzlpUf-KTVI2Ptgm-dARxTEtE-id-4OJr0h-K-VFs3VSnd
       VTIznSxfyrj8ILL6MG_Uv8YAu7VILSB3lOW085-4qE3DzgrTjgyQ",
  "p":"1r52Xk46c-LsfB5P442p7atdPUrxQSy4mti_tZI3Mgf2EuFVbUoDBvaRQ-
       SWxkbkmoEzL7JXroSBjSrK3YIQgYdMgyAEPTPjXv_hI2_1eTSPVZfzL0lf
       fNn03IXqWF5MDFuoUYE0hzb2vhrlN_rKrbfDIwUbTrjjgieRbwC6Cl0",
  "q":"wLb35x7hmQWZsWJmB_vle87ihgZ19S8lBEROLIsZG4ayZVe9Hi9gDVCOBm
       UDdaDYVTSNx_8Fyw1YYa9XGrGnDew00J28cRUoeBB_jKI1oma0Orv1T9aX
       IWxKwd4gvxFImOWr3QRL9KEBRzk2RatUBnmDZJTIAfwTs0g68UZHvtc",
  "dp":"ZK-YwE7diUh0qR1tR7w8WHtolDx3MZ_OTowiFvgfeQ3SiresXjm9gZ5KL
       hMXvo-uz-KUJWDxS5pFQ_M0evdo1dKiRTjVw_x4NyqyXPM5nULPkcpU827
       rnpZzAJKpdhWAgqrXGKAECQH0Xt4taznjnd_zVpAmZZq60WPMBMfKcuE",
  "dq":"Dq0gfgJ1DdFGXiLvQEZnuKEN0UUmsJBxkjydc3j4ZYdBiMRAy86x0vHCj
       ywcMlYYg4yoC4YZa9hNVcsjqA3FeiL19rk8g6Qn29Tt0cj8qqyFpz9vNDB
       UfCAiJVeESOjJDZPYHdHY8v1b-o-Z2X5tvLx-TCekf7oxyeKDUqKWjis",
  "qi":"VIMpMYbPf47dT1w_zDUXfPimsSegnMOA1zTaX7aGk_8urY6R8-ZW1FxU7
       AlWAyLWybqq6t16VFd7hQd0y6flUK4SlOydB61gwanOsXGOAOv82cHq0E3
       eL4HrtZkUuKvnPrMnsUUFlfUdybVzxyjz9JF_XyaY14ardLSjf4L_FNY"
 }
</code>```

I've tried jwk-to-pem:

https://stackoverflow.com/a/35995690/4742108

```<code>-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAoahUIoWw0K0usKNuOR6H4wkf4oBUXHTxRvgb48E+BVvxkeDNjbC4
he8rUWcJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3S
psk/ZkoFnilakGygTwpZ3uesH+PFABNIUYpOiN15dsQRkgr0vEhxN92i2asbOenS
ZeyaxziK72UwxrrKoExv6kc5twXTq4h+QChLOln0/mtUZwfsRaMStPs6mS6Xrgxn
xbWhojf663tuEQueGC+FCMfra36C9knDFGzKsNa7LZK2djYgyD3JR/MB/4NUJW/T
qOQtwHYbxevoJArm+L5StowjzGy+/bq6GwIDAQAB
-----END RSA PUBLIC KEY-----
</code>```

Also had to replace "RSA PUBLIC KEY" with "PUBLIC KEY".

The command openssl rsa -inform PEM -pubin gives:

```<code>unable to load Public Key
139911798556312:error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1197:
139911798556312:error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error:tasn_dec.c:374:Type=X509_ALGOR
139911798556312:error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error:tasn_dec.c:697:Field=algor, Type=X509_PUBKEY
139911798556312:error:0906700D:PEM routines:PEM_ASN1_read_bio:ASN1 lib:pem_oth.c:83:
</code>```

How to get a usable key?

答:
I wrote a command line tool called lokey to help with key conversions like this one.

Using curl, grep, and tr to grab the key from question, we can convert the JWK formatted private key into a PEM formatted private key with this command:

```<code>$ curl -s https://tools.ietf.org/rfc/rfc7516.txt | grep '"n":"oahUI' -B1 -A28 | tr -d '[:space:]' | lokey to pem

-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAoahUIoWw0K0usKNuOR6H4wkf4oBUXHTxRvgb48E+BVvxkeDN
jbC4he8rUWcJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2K
rf3Spsk/ZkoFnilakGygTwpZ3uesH+PFABNIUYpOiN15dsQRkgr0vEhxN92i2asb
OenSZeyaxziK72UwxrrKoExv6kc5twXTq4h+QChLOln0/mtUZwfsRaMStPs6mS6X
rgxnxbWhojf663tuEQueGC+FCMfra36C9knDFGzKsNa7LZK2djYgyD3JR/MB/4NU
JW/TqOQtwHYbxevoJArm+L5StowjzGy+/bq6GwIDAQABAoIBAQCQt20iPoZsOSz8
CkJJNhC16Vw222UqI7I/Mytcd4j7KTUXv6SkPFjj5Zjk1ZXkqe1oR5dLWPzYTfvn
HGFYwdfK+Nh5w9P1+nBH8z2BXyf0euHZqdOlMP3cO3rbKlbfIOwnMGdOeti7WLBZ
GAEqsRhjjqoBkisDbEDCebZfu4ZHWGCGSoOnRWqPeRtILPVfJ8Kzr8t6EHC3EcjK
HxGKnLjSnbiag4BuDFXDevFP++W3dRV7hY7cmQk7OWlR/4pNUjY+2Cb50BHFMS0T
6J37g4mvSH4r5UWzdVKd1VMjOdLF/KuPwgsvowb9S/xgC7tUgtIHeU5bTzn7ioTc
POCtOODJAoGBANa+dl5OOnPi7HweT+ONqe2rXT1K8UEsuJrYv7WSNzIH9hLhVW1K
Awb2kUPklsZG5JqBMy+yV66EgY0qyt2CEIGHTIMgBD0z417/4SNv9Xk0j1WX8y9J
X3zZ9NyF6lheTAxbqFGBNIc29r4a5Tf6yq23wyMFG06444InkW8AugpdAoGBAMC2
9+ce4ZkFmbFiZgf75XvO4oYGdfUvJQRETiyLGRuGsmVXvR4vYA1QjgZlA3Wg2FU0
jcf/BcsNWGGvVxqxpw3sNNCdvHEVKHgQf4yiNaJmtDq79U/WlyFsSsHeIL8RSJjl
q90ES/ShAUc5NkWrVAZ5g2SUyAH8E7NIOvFGR77XAoGAZK+YwE7diUh0qR1tR7w8
WHtolDx3MZ/OTowiFvgfeQ3SiresXjm9gZ5KLhMXvo+uz+KUJWDxS5pFQ/M0evdo
1dKiRTjVw/x4NyqyXPM5nULPkcpU827rnpZzAJKpdhWAgqrXGKAECQH0Xt4taznj
nd/zVpAmZZq60WPMBMfKcuECgYAOrSB+AnUN0UZeIu9ARme4oQ3RRSawkHGSPJ1z
ePhlh0GIxEDLzrHS8cKPLBwyVhiDjKgLhhlr2E1VyyOoDcV6IvX2uTyDpCfb1O3R
yPyqrIWnP280MFR8ICIlV4RI6MkNk9gd0djy/Vv6j5nZfm28vH5MJ6R/ujHJ4oNS
opaOKwKBgFSDKTGGz3+O3U9cP8w1F3z4prEnoJzDgNc02l+2hpP/Lq2OkfPmVtRc
VOwJVgMi1sm6qurdelRXe4UHdMun5VCuEpTsnQetYMGpzrFxjgDr/NnB6tBN3i+B
67WZFLir5z6zJ7FFBZX1Hcm1c8co8/SRf18mmNeGq3S0o3+C/xTW
-----END RSA PRIVATE KEY-----
</code>```

lokey also has a fetch command that can be used to fetch JWK keys from OpenID endpoints:

```<code>$ lokey fetch jwk example.okta.com
$ lokey fetch jwk login.salesforce.com
$ lokey fetch jwk accounts.google.com
</code>```

You can then pipe this output into lokey again to get a PEM:

```<code>$ lokey fetch jwk example.okta.com | lokey to pem
</code>```

Body:
There is an RSA key from an RFC:

https://www.rfc-editor.org/rfc/rfc7516#appendix-A.1

 {"kty":"RSA",
  "n":"oahUIoWw0K0usKNuOR6H4wkf4oBUXHTxRvgb48E-BVvxkeDNjbC4he8rUW
       cJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3S
       psk_ZkoFnilakGygTwpZ3uesH-PFABNIUYpOiN15dsQRkgr0vEhxN92i2a
       sbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h-QChLOln0_mtUZwfsRaMS
       tPs6mS6XrgxnxbWhojf663tuEQueGC-FCMfra36C9knDFGzKsNa7LZK2dj
       YgyD3JR_MB_4NUJW_TqOQtwHYbxevoJArm-L5StowjzGy-_bq6Gw",
  "e":"AQAB",
  "d":"kLdtIj6GbDks_ApCSTYQtelcNttlKiOyPzMrXHeI-yk1F7-kpDxY4-WY5N
       WV5KntaEeXS1j82E375xxhWMHXyvjYecPT9fpwR_M9gV8n9Hrh2anTpTD9
       3Dt62ypW3yDsJzBnTnrYu1iwWRgBKrEYY46qAZIrA2xAwnm2X7uGR1hghk
       qDp0Vqj3kbSCz1XyfCs6_LehBwtxHIyh8Ripy40p24moOAbgxVw3rxT_vl
       t3UVe4WO3JkJOzlpUf-KTVI2Ptgm-dARxTEtE-id-4OJr0h-K-VFs3VSnd
       VTIznSxfyrj8ILL6MG_Uv8YAu7VILSB3lOW085-4qE3DzgrTjgyQ",
  "p":"1r52Xk46c-LsfB5P442p7atdPUrxQSy4mti_tZI3Mgf2EuFVbUoDBvaRQ-
       SWxkbkmoEzL7JXroSBjSrK3YIQgYdMgyAEPTPjXv_hI2_1eTSPVZfzL0lf
       fNn03IXqWF5MDFuoUYE0hzb2vhrlN_rKrbfDIwUbTrjjgieRbwC6Cl0",
  "q":"wLb35x7hmQWZsWJmB_vle87ihgZ19S8lBEROLIsZG4ayZVe9Hi9gDVCOBm
       UDdaDYVTSNx_8Fyw1YYa9XGrGnDew00J28cRUoeBB_jKI1oma0Orv1T9aX
       IWxKwd4gvxFImOWr3QRL9KEBRzk2RatUBnmDZJTIAfwTs0g68UZHvtc",
  "dp":"ZK-YwE7diUh0qR1tR7w8WHtolDx3MZ_OTowiFvgfeQ3SiresXjm9gZ5KL
       hMXvo-uz-KUJWDxS5pFQ_M0evdo1dKiRTjVw_x4NyqyXPM5nULPkcpU827
       rnpZzAJKpdhWAgqrXGKAECQH0Xt4taznjnd_zVpAmZZq60WPMBMfKcuE",
  "dq":"Dq0gfgJ1DdFGXiLvQEZnuKEN0UUmsJBxkjydc3j4ZYdBiMRAy86x0vHCj
       ywcMlYYg4yoC4YZa9hNVcsjqA3FeiL19rk8g6Qn29Tt0cj8qqyFpz9vNDB
       UfCAiJVeESOjJDZPYHdHY8v1b-o-Z2X5tvLx-TCekf7oxyeKDUqKWjis",
  "qi":"VIMpMYbPf47dT1w_zDUXfPimsSegnMOA1zTaX7aGk_8urY6R8-ZW1FxU7
       AlWAyLWybqq6t16VFd7hQd0y6flUK4SlOydB61gwanOsXGOAOv82cHq0E3
       eL4HrtZkUuKvnPrMnsUUFlfUdybVzxyjz9JF_XyaY14ardLSjf4L_FNY"
 }

I've tried jwk-to-pem:

https://stackoverflow.com/a/35995690/4742108

-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAoahUIoWw0K0usKNuOR6H4wkf4oBUXHTxRvgb48E+BVvxkeDNjbC4
he8rUWcJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3S
psk/ZkoFnilakGygTwpZ3uesH+PFABNIUYpOiN15dsQRkgr0vEhxN92i2asbOenS
ZeyaxziK72UwxrrKoExv6kc5twXTq4h+QChLOln0/mtUZwfsRaMStPs6mS6Xrgxn
xbWhojf663tuEQueGC+FCMfra36C9knDFGzKsNa7LZK2djYgyD3JR/MB/4NUJW/T
qOQtwHYbxevoJArm+L5StowjzGy+/bq6GwIDAQAB
-----END RSA PUBLIC KEY-----

Also had to replace "RSA PUBLIC KEY" with "PUBLIC KEY".

The command openssl rsa -inform PEM -pubin gives:

unable to load Public Key
139911798556312:error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1197:
139911798556312:error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error:tasn_dec.c:374:Type=X509_ALGOR
139911798556312:error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error:tasn_dec.c:697:Field=algor, Type=X509_PUBKEY
139911798556312:error:0906700D:PEM routines:PEM_ASN1_read_bio:ASN1 lib:pem_oth.c:83:

How to get a usable key?

Body:
I wrote a command line tool called lokey to help with key conversions like this one.

Using curl, grep, and tr to grab the key from question, we can convert the JWK formatted private key into a PEM formatted private key with this command:

$ curl -s https://tools.ietf.org/rfc/rfc7516.txt | grep '"n":"oahUI' -B1 -A28 | tr -d '[:space:]' | lokey to pem

-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAoahUIoWw0K0usKNuOR6H4wkf4oBUXHTxRvgb48E+BVvxkeDN
jbC4he8rUWcJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2K
rf3Spsk/ZkoFnilakGygTwpZ3uesH+PFABNIUYpOiN15dsQRkgr0vEhxN92i2asb
OenSZeyaxziK72UwxrrKoExv6kc5twXTq4h+QChLOln0/mtUZwfsRaMStPs6mS6X
rgxnxbWhojf663tuEQueGC+FCMfra36C9knDFGzKsNa7LZK2djYgyD3JR/MB/4NU
JW/TqOQtwHYbxevoJArm+L5StowjzGy+/bq6GwIDAQABAoIBAQCQt20iPoZsOSz8
CkJJNhC16Vw222UqI7I/Mytcd4j7KTUXv6SkPFjj5Zjk1ZXkqe1oR5dLWPzYTfvn
HGFYwdfK+Nh5w9P1+nBH8z2BXyf0euHZqdOlMP3cO3rbKlbfIOwnMGdOeti7WLBZ
GAEqsRhjjqoBkisDbEDCebZfu4ZHWGCGSoOnRWqPeRtILPVfJ8Kzr8t6EHC3EcjK
HxGKnLjSnbiag4BuDFXDevFP++W3dRV7hY7cmQk7OWlR/4pNUjY+2Cb50BHFMS0T
6J37g4mvSH4r5UWzdVKd1VMjOdLF/KuPwgsvowb9S/xgC7tUgtIHeU5bTzn7ioTc
POCtOODJAoGBANa+dl5OOnPi7HweT+ONqe2rXT1K8UEsuJrYv7WSNzIH9hLhVW1K
Awb2kUPklsZG5JqBMy+yV66EgY0qyt2CEIGHTIMgBD0z417/4SNv9Xk0j1WX8y9J
X3zZ9NyF6lheTAxbqFGBNIc29r4a5Tf6yq23wyMFG06444InkW8AugpdAoGBAMC2
9+ce4ZkFmbFiZgf75XvO4oYGdfUvJQRETiyLGRuGsmVXvR4vYA1QjgZlA3Wg2FU0
jcf/BcsNWGGvVxqxpw3sNNCdvHEVKHgQf4yiNaJmtDq79U/WlyFsSsHeIL8RSJjl
q90ES/ShAUc5NkWrVAZ5g2SUyAH8E7NIOvFGR77XAoGAZK+YwE7diUh0qR1tR7w8
WHtolDx3MZ/OTowiFvgfeQ3SiresXjm9gZ5KLhMXvo+uz+KUJWDxS5pFQ/M0evdo
1dKiRTjVw/x4NyqyXPM5nULPkcpU827rnpZzAJKpdhWAgqrXGKAECQH0Xt4taznj
nd/zVpAmZZq60WPMBMfKcuECgYAOrSB+AnUN0UZeIu9ARme4oQ3RRSawkHGSPJ1z
ePhlh0GIxEDLzrHS8cKPLBwyVhiDjKgLhhlr2E1VyyOoDcV6IvX2uTyDpCfb1O3R
yPyqrIWnP280MFR8ICIlV4RI6MkNk9gd0djy/Vv6j5nZfm28vH5MJ6R/ujHJ4oNS
opaOKwKBgFSDKTGGz3+O3U9cP8w1F3z4prEnoJzDgNc02l+2hpP/Lq2OkfPmVtRc
VOwJVgMi1sm6qurdelRXe4UHdMun5VCuEpTsnQetYMGpzrFxjgDr/NnB6tBN3i+B
67WZFLir5z6zJ7FFBZX1Hcm1c8co8/SRf18mmNeGq3S0o3+C/xTW
-----END RSA PRIVATE KEY-----

lokey also has a fetch command that can be used to fetch JWK keys from OpenID endpoints:

$ lokey fetch jwk example.okta.com
$ lokey fetch jwk login.salesforce.com
$ lokey fetch jwk accounts.google.com

You can then pipe this output into lokey again to get a PEM:

$ lokey fetch jwk example.okta.com | lokey to pem


问:
ReactJS How to toggle elements to hide or show
I am very new to React and the ES6 syntax I have a chat widget that i want to toggle to show and hide as i click the header,and I have already implemented an onClick handler, but in terms of the logic I am having trouble finding a similar implementation online. this is my code:</p>

```<code>import React, {Component} from 'react';
import chat from './styles.css';
import {connect} from 'react-redux';

class ChatWidget extends Component {

  handleClick(event) {
    console.log("Hide or unhide chat body")
  }

  render() {
    return (
      <div className={chat.container}>
        <div onClick={this.handleClick.bind(this)}
             className={chat.header}>
          <span className={chat.name}>Idol</span>
        </div>
        <div className={chat.body}>
          This is the Body of the chat
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    user: state.activeUser
  };
}

export default connect(mapStateToProps)(ChatWidget);
</code>```

答:
Here you have an example, it has comments on the lines so you know what each line is doing.

Consider that adding a hidden class to the component will not unmount it, it will just hide it from the DOM

```<code>import React, {Component} from 'react';
import chat from './styles.css';
import {connect} from 'react-redux';

class ChatWidget extends Component {
  // You need state to update the view
  state = {
    show: false
  }

  toggleBody() {
    // You can pass true or false to this function to show or hide the body
    this.setState({show: !this.state.show})
  }

  render() {
    {/* Take the show property from the state */}
    const {show} = this.state
    return (
      <div className={chat.container}>
        <div onClick={this.toggleBody.bind(this)} className={chat.header}>
          <span className={chat.name}>Idol</span>
        </div>
        {/* Add the class hidden to the body if show is false (you should create the hidden class in CSS) */}
        <div className={`${chat.body} ${show ? '' : 'hidden'}`}>
          This is the Body of the chat
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    user: state.activeUser
  };
}

export default connect(mapStateToProps)(ChatWidget);
</code>```

Body:
I am very new to React and the ES6 syntax I have a chat widget that i want to toggle to show and hide as i click the header,and I have already implemented an onClick handler, but in terms of the logic I am having trouble finding a similar implementation online. this is my code:

import React, {Component} from 'react';
import chat from './styles.css';
import {connect} from 'react-redux';

class ChatWidget extends Component {

  handleClick(event) {
    console.log("Hide or unhide chat body")
  }

  render() {
    return (

          Idol

          This is the Body of the chat

    );
  }
}

function mapStateToProps(state) {
  return {
    user: state.activeUser
  };
}

export default connect(mapStateToProps)(ChatWidget);

Body:
Here you have an example, it has comments on the lines so you know what each line is doing.

Consider that adding a hidden class to the component will not unmount it, it will just hide it from the DOM

import React, {Component} from 'react';
import chat from './styles.css';
import {connect} from 'react-redux';

class ChatWidget extends Component {
  // You need state to update the view
  state = {
    show: false
  }

  toggleBody() {
    // You can pass true or false to this function to show or hide the body
    this.setState({show: !this.state.show})
  }

  render() {
    {/* Take the show property from the state */}
    const {show} = this.state
    return (
      <div className={chat.container}>
        <div onClick={this.toggleBody.bind(this)} className={chat.header}>
          <span className={chat.name}>Idol</span>
        </div>
        {/* Add the class hidden to the body if show is false (you should create the hidden class in CSS) */}
        <div className={`${chat.body} ${show ? '' : 'hidden'}`}>
          This is the Body of the chat
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    user: state.activeUser
  };
}

export default connect(mapStateToProps)(ChatWidget);


问:
Beanstalkd stats show jobs but peek-ready is not found
I've got a Beanstalkd instance running and can put jobs on the queue without problems.

I can see the jobs are there:

```<code>$ echo -e "stats\r\n" | nc localhost 11300 | grep jobs

current-jobs-urgent: 0
current-jobs-ready: 3
current-jobs-reserved: 0
current-jobs-delayed: 0
current-jobs-buried: 0
total-jobs: 3
</code>```

But trying to pull them off with an application fails, as does trying to see one with peek-ready:

```<code>$ echo -e "peek-ready\r\n" | nc localhost 11300

NOT_FOUND
</code>```

What am I doing wrong?

答:
It’s quite possible the jobs are on a different (non-default) tube that you are not USEing.

The peek commands let the client inspect a job in the system. There are four variations. All but the first operate only on the currently used tube.

You can see how many different tubes exist (beyond the tube named default) with the current-tubes that is also returned from the stats command, and the list-tubes command, that will list them.When you know which tube(s) the jobs are on, you can use {tube-name}, and then peek-ready on the  tube.

Body:
I've got a Beanstalkd instance running and can put jobs on the queue without problems.

I can see the jobs are there:

$ echo -e "stats\r\n" | nc localhost 11300 | grep jobs

current-jobs-urgent: 0
current-jobs-ready: 3
current-jobs-reserved: 0
current-jobs-delayed: 0
current-jobs-buried: 0
total-jobs: 3

But trying to pull them off with an application fails, as does trying to see one with peek-ready:

$ echo -e "peek-ready\r\n" | nc localhost 11300

NOT_FOUND

What am I doing wrong?


问:
eclipse loads web.xml incorrectly to tomcat
And I'm having issue in running spring project on tomcat in eclipse(mars).

My project is built with maven and basing on profiles, the web.xml file is built. So here is how dev profile is defined as following:

```<code><profile>
  <id>dev</id>
  ...
  <properties>
    ...
    <welcomePage>devIndexPage.xhtml</welcomePage>
</properties>
</code>```

Then in the web.xml I have following definition with a placeholder:

```<code><welcome-file-list>
   <welcome-file>${welcomePage}</welcome-file>
</welcome-file-list>
</code>```

After building a project, I'm opening WAR file and can see that web.xml has welcome file config like (placeholder replaced with value of dev profile):

```<code><welcome-file-list>
     <welcome-file>devIndexPage.xhtml</welcome-file>
</welcome-file-list>
</code>```

So until now everything is OK, but when I run project on tomcat7 in eclipse, looks like welcome file value is ${welcomePage}. In other words, looks like eclipse+tomcat load web.xml without replacing placeholder.

I'm sure that my configuration should work, because I successfully run it manually on tomcat without using eclipse. So I guess that eclipse copies project wrongly to wtpwebapps folder.

Could you please give me suggestions what should I configure on eclipse in order to load web.xml correctly?

In addition I'm providing tomcat overview:

Edit
So I already figured out that web.xml, which is copied to workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\myapp has as following <welcome-file>${welcomePage}</welcome-file>. So any idea why placeholder wasn't replaced wen web app was deployed in this folder?

答: The replace of expressions is a maven feature Independent of the ide used. Try mvn tomcat:run instead of eclipse.</p>

Body:
And I'm having issue in running spring project on tomcat in eclipse(mars).

My project is built with maven and basing on profiles, the web.xml file is built. So here is how dev profile is defined as following:

<profile>
  <id>dev</id>
  ...
  <properties>
    ...
    <welcomePage>devIndexPage.xhtml</welcomePage>
</properties>

Then in the web.xml I have following definition with a placeholder:

<welcome-file-list>
   <welcome-file>${welcomePage}</welcome-file>
</welcome-file-list>

After building a project, I'm opening WAR file and can see that web.xml has welcome file config like (placeholder replaced with value of dev profile):

<welcome-file-list>
     <welcome-file>devIndexPage.xhtml</welcome-file>
</welcome-file-list>

So until now everything is OK, but when I run project on tomcat7 in eclipse, looks like welcome file value is ${welcomePage}. In other words, looks like eclipse+tomcat load web.xml without replacing placeholder.

I'm sure that my configuration should work, because I successfully run it manually on tomcat without using eclipse. So I guess that eclipse copies project wrongly to wtpwebapps folder.

Could you please give me suggestions what should I configure on eclipse in order to load web.xml correctly?

In addition I'm providing tomcat overview:

Edit
So I already figured out that web.xml, which is copied to workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\myapp has as following <welcome-file>${welcomePage}</welcome-file>. So any idea why placeholder wasn't replaced wen web app was deployed in this folder?


问:
How to pass multiple values to a stored procedure
I have an Excel worksheet with a dropdown data validation box where the user can select from a list of integer values to determine a department or the word "ALL" to get all departments.  I'm passing that cell's value to a stored procedure using SQL. In the SQL, I have WHERE Department=@Dept.

If I'm only going to allow one department choice, this works fine, but I want to also allow for all departments.

Are there any ideas on how to make that work?  Does it take some sort of trick with the IN operator or something else?

答:
Two solutions here in the stored script:

put an if statement then you'll have to sets of queries.

put an iif/case statement within the criteria.


问:
Cannot publish a MongoDB collection from the server to client Meteor
I want to publish a sever side collection to the client side.

In Server Side

```<code>MedicalCenters = new Mongo.Collection('medicalCenters');

Meteor.publish('medicalCenters',function () {
    return MedicalCenters.find({});
});
</code>```

I want this collection only to be accessed by a particular template. Thefore,

In Client Side

```<code>Template.doctor.onCreated(function () {
    Meteor.subscribe('medicalCenters');
});
</code>```

Now I can pass the data from client side template and even write to the serve side collection. But it seems to be subscription did not work and therefore, I cannot display collection data in the template.
(The collection is not displayed in the meteortoys Mongol)

How do I fix this?

答:
It sounds like you have not placed your collection definition code in a common location that is executed by both the client and server.  I'm making this assumption because you said that the collection itself was not visible in mongol.

Remember that in order for publish/subscribe to work, collections must exist on both the client side (using minimongo) and the server side (using mongodb).

Refer to the Meteor Application Structure guide for the details, but essentially you should put your collection definition code in a file that is not within a special directory (e.g. the server/ or client/ folder).  Doing so ensures that the code is executed by both the client and server (per the meteor api docs).

All JavaScript files outside special directories are loaded on both the client and the server.

In the older meteor days (before we had the imports/ folder) people often placed their collection definition code inside a lib/ folder within the meteor project root.  Now it's common for it to be within the import/api/ directory as described here.

Body:
I want to publish a sever side collection to the client side.

In Server Side

MedicalCenters = new Mongo.Collection('medicalCenters');

Meteor.publish('medicalCenters',function () {
    return MedicalCenters.find({});
});

I want this collection only to be accessed by a particular template. Thefore,

In Client Side

Template.doctor.onCreated(function () {
    Meteor.subscribe('medicalCenters');
});

Now I can pass the data from client side template and even write to the serve side collection. But it seems to be subscription did not work and therefore, I cannot display collection data in the template.
(The collection is not displayed in the meteortoys Mongol)

How do I fix this?


问:
Cache locality with unique_ptr
I have a vector of custom classes (std::string just for example).

The vector is large and I iterate through often, so I rely on cache locality.

I also have one raw pointer which points at one of the vector elements.

Now is the trick:

The vector is sorted from time to time, so the raw pointer loose the actual pointed element value, and will point to some random element value.

Here is an example to illustrate the same:

```<code>#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <memory>

using namespace std;

int main()
{

    vector<string> v = {"9","3", "8", "7", "6", "5", "1", "4", "2"};

    string* rs = &v[7]; //point to the 7th element

    for (size_t i = 0; i < v.size(); ++i)
        cerr << v[i];
    cerr << endl;
    cerr << "Referenced string: " << rs->c_str() << endl;

    cerr << "Sort ..." << endl;
    sort(v.begin(), v.end(), [](const string& a, const string& b)
    {
        if (a < b)
            return true;
        else
            return false;
    }
    );

    for (size_t i = 0; i < v.size(); ++i)
        cerr << v[i];
    cerr << endl;
    cerr << "Referenced string: " << rs->c_str() << endl;

    cin.get();
    return 0;

}
</code>```

Output:

```<code>938765142
Referenced string before sort : 4
Sort ...
123456789
Referenced string after sort : 8
</code>```

Since I wish the rs pointer to keep pointing to the 7th element value (which is 4) even after the sort, I came up with the following solution (vector of pointers):

```<code>#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <memory>

using namespace std;

int main()
{

    vector<unique_ptr<string>> v;
    v.resize(9);
    v[0] = make_unique<string>("9");
    v[1] = make_unique<string>("3");
    v[2] = make_unique<string>("8");
    v[3] = make_unique<string>("7");
    v[4] = make_unique<string>("6");
    v[5] = make_unique<string>("5");
    v[6] = make_unique<string>("1");
    v[7] = make_unique<string>("4");
    v[8] = make_unique<string>("2");

    string* rs = v[7].get();

    for (size_t i = 0; i < v.size(); ++i)
    cerr << v[i]->c_str();
    cerr << endl;
    cerr << "Referenced string before sort: " << rs->c_str() << endl;

    cerr << "Sort ..." << endl;
    sort(v.begin(), v.end(), [](const unique_ptr<string>& a, const unique_ptr<string>& b)
    {
    if (*a < *b)
    return true;
    else
    return false;
    }
    );

    for (size_t i = 0; i < v.size(); ++i)
    cerr << v[i]->c_str();
    cerr << endl;
    cerr << "Referenced string after sort: " << rs->c_str() << endl;

    cin.get();
    return 0;

}
</code>```

Output:

```<code>938765142
Referenced string before sort: 4
Sort ...
123456789
Referenced string after sort: 4
</code>```

While this latter solution works, there is a price: I have lost the cache locality of my vector, since I store pointers in it, rather than the actual objects.

Is there a way to maintain cache locality (e.g.: store my actual objects in the vector), and somehow manage to rs pointer to keep track where its pointed value wander around due to the sorts?
Or from the other perspective, is there a way to achieve cache locality with the vector of pointers?

Solution from Pubby, thanks!:

```<code>#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <memory>

using namespace std;

int main()
{

    vector<string> data = { "d","e", "f", "g", "i", "b", "c", "a", "h" };
    vector<int> indexes = {0,1,2,3,4,5,6,7,8};

    int si = 6;

    for (size_t i = 0; i < indexes.size(); ++i)
        cerr << indexes[i];
    cerr << endl;
    for (size_t i = 0; i < indexes.size(); ++i)
        cerr << data[indexes[i]];
    cerr << endl;
    cerr << "Referenced string before sort: " << data[si] << endl;

    cerr << "Sort ..." << endl;
    sort(indexes.begin(), indexes.end(), [&](const int a, const int b)
    {
        return data[a] < data[b];
    }
    );

    for (size_t i = 0; i < indexes.size(); ++i)
        cerr << indexes[i];
    cerr << endl;
    for (size_t i = 0; i < indexes.size(); ++i)
        cerr << data[indexes[i]];
    cerr << endl;
    cerr << "Referenced string after sort: " << data[si] << endl;

    cin.get();
    return 0;

}
</code>```

答:
Just an idea: Instead of storing std::string in the vector, just append the character arrays of each string to a std::vector<char>.

This packs the strings closely together in memory, improving locality even better than std::string with small string optimization. It will also give better results if the strings exceed the max. size for small string optimization.

For sorting, store index and size of each string in a 2nd vector similar to Pubbys suggestion.

Of course this only works if the string length doesn't need to change dynamically. Otherwise you would have to rebuild the vector<char>.

```<code>#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
#include <string_view>

using namespace std;

using IndexAndSize = pair<size_t,size_t>;

void push_and_index( vector<char>& v, vector<IndexAndSize>& vi, string_view s )
{
    vi.emplace_back( v.size(), s.size() );
    v.insert( end(v), begin(s), end(s) );
}

string_view make_string_view( vector<char> const& v, IndexAndSize is )
{
    return { v.data() + is.first, is.second };
}

int main()
{
    vector<char> v;
    vector<IndexAndSize> vi;

    push_and_index( v, vi, "foo" );
    push_and_index( v, vi, "bar" );
    push_and_index( v, vi, "foobar" );
    push_and_index( v, vi, "barfoo" );

    sort( begin(vi), end(vi), [&]( IndexAndSize a, IndexAndSize b )
    {
        return make_string_view( v, a ) < make_string_view( v, b );
    });

    for( IndexAndSize is : vi )
    {
        cout << make_string_view( v, is ) << endl;
    }
}
</code>```

Live demo on Coliru.

Note: C++17's string_view is used only to help with the sorting and output, it's not crucial for this idea.

Title: Cache locality with unique_ptr

Body:
I have a vector of custom classes (std::string just for example).

The vector is large and I iterate through often, so I rely on cache locality.

I also have one raw pointer which points at one of the vector elements.

Now is the trick:

The vector is sorted from time to time, so the raw pointer loose the actual pointed element value, and will point to some random element value.

Here is an example to illustrate the same:

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <memory>

using namespace std;

int main()
{

    vector<string> v = {"9","3", "8", "7", "6", "5", "1", "4", "2"};

    string* rs = &v[7]; //point to the 7th element

    for (size_t i = 0; i < v.size(); ++i)
        cerr << v[i];
    cerr << endl;
    cerr << "Referenced string: " << rs->c_str() << endl;

    cerr << "Sort ..." << endl;
    sort(v.begin(), v.end(), [](const string& a, const string& b)
    {
        if (a < b)
            return true;
        else
            return false;
    }
    );

    for (size_t i = 0; i < v.size(); ++i)
        cerr << v[i];
    cerr << endl;
    cerr << "Referenced string: " << rs->c_str() << endl;

    cin.get();
    return 0;

}

Output:

938765142
Referenced string before sort : 4
Sort ...
123456789
Referenced string after sort : 8

Since I wish the rs pointer to keep pointing to the 7th element value (which is 4) even after the sort, I came up with the following solution (vector of pointers):

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <memory>

using namespace std;

int main()
{

    vector<unique_ptr<string>> v;
    v.resize(9);
    v[0] = make_unique<string>("9");
    v[1] = make_unique<string>("3");
    v[2] = make_unique<string>("8");
    v[3] = make_unique<string>("7");
    v[4] = make_unique<string>("6");
    v[5] = make_unique<string>("5");
    v[6] = make_unique<string>("1");
    v[7] = make_unique<string>("4");
    v[8] = make_unique<string>("2");

    string* rs = v[7].get();

    for (size_t i = 0; i < v.size(); ++i)
    cerr << v[i]->c_str();
    cerr << endl;
    cerr << "Referenced string before sort: " << rs->c_str() << endl;

    cerr << "Sort ..." << endl;
    sort(v.begin(), v.end(), [](const unique_ptr<string>& a, const unique_ptr<string>& b)
    {
    if (*a < *b)
    return true;
    else
    return false;
    }
    );

    for (size_t i = 0; i < v.size(); ++i)
    cerr << v[i]->c_str();
    cerr << endl;
    cerr << "Referenced string after sort: " << rs->c_str() << endl;

    cin.get();
    return 0;

}

Output:

938765142
Referenced string before sort: 4
Sort ...
123456789
Referenced string after sort: 4

While this latter solution works, there is a price: I have lost the cache locality of my vector, since I store pointers in it, rather than the actual objects.

Is there a way to maintain cache locality (e.g.: store my actual objects in the vector), and somehow manage to rs pointer to keep track where its pointed value wander around due to the sorts?
Or from the other perspective, is there a way to achieve cache locality with the vector of pointers?

Solution from Pubby, thanks!:

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <memory>

using namespace std;

int main()
{

    vector<string> data = { "d","e", "f", "g", "i", "b", "c", "a", "h" };
    vector<int> indexes = {0,1,2,3,4,5,6,7,8};

    int si = 6;

    for (size_t i = 0; i < indexes.size(); ++i)
        cerr << indexes[i];
    cerr << endl;
    for (size_t i = 0; i < indexes.size(); ++i)
        cerr << data[indexes[i]];
    cerr << endl;
    cerr << "Referenced string before sort: " << data[si] << endl;

    cerr << "Sort ..." << endl;
    sort(indexes.begin(), indexes.end(), [&](const int a, const int b)
    {
        return data[a] < data[b];
    }
    );

    for (size_t i = 0; i < indexes.size(); ++i)
        cerr << indexes[i];
    cerr << endl;
    for (size_t i = 0; i < indexes.size(); ++i)
        cerr << data[indexes[i]];
    cerr << endl;
    cerr << "Referenced string after sort: " << data[si] << endl;

    cin.get();
    return 0;

}

Body:
Just an idea: Instead of storing std::string in the vector, just append the character arrays of each string to a std::vector<char>.

This packs the strings closely together in memory, improving locality even better than std::string with small string optimization. It will also give better results if the strings exceed the max. size for small string optimization.

For sorting, store index and size of each string in a 2nd vector similar to Pubbys suggestion.

Of course this only works if the string length doesn't need to change dynamically. Otherwise you would have to rebuild the vector<char>.

#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
#include <string_view>

using namespace std;

using IndexAndSize = pair<size_t,size_t>;

void push_and_index( vector<char>& v, vector<IndexAndSize>& vi, string_view s )
{
    vi.emplace_back( v.size(), s.size() );
    v.insert( end(v), begin(s), end(s) );
}

string_view make_string_view( vector<char> const& v, IndexAndSize is )
{
    return { v.data() + is.first, is.second };
}

int main()
{
    vector<char> v;
    vector<IndexAndSize> vi;

    push_and_index( v, vi, "foo" );
    push_and_index( v, vi, "bar" );
    push_and_index( v, vi, "foobar" );
    push_and_index( v, vi, "barfoo" );

    sort( begin(vi), end(vi), [&]( IndexAndSize a, IndexAndSize b )
    {
        return make_string_view( v, a ) < make_string_view( v, b );
    });

    for( IndexAndSize is : vi )
    {
        cout << make_string_view( v, is ) << endl;
    }
}

Live demo on Coliru.

Note: C++17's string_view is used only to help with the sorting and output, it's not crucial for this idea.


答:
If your user selects "ALL", you can set the paramter to NULL:

```<code>select * from table1 WHERE Department=isnull(@Dept,Department)
</code>```

When the value of @Dept is NULL the query will be:

```<code>select * from table1 WHERE Department=Department
</code>```

just like 1=1.

Title: How to pass multiple values to a stored procedure

Body:
I have an Excel worksheet with a dropdown data validation box where the user can select from a list of integer values to determine a department or the word "ALL" to get all departments.  I'm passing that cell's value to a stored procedure using SQL. In the SQL, I have WHERE Department=@Dept.

If I'm only going to allow one department choice, this works fine, but I want to also allow for all departments.

Are there any ideas on how to make that work?  Does it take some sort of trick with the IN operator or something else?

Body:
If your user selects "ALL", you can set the paramter to NULL:

select * from table1 WHERE Department=isnull(@Dept,Department)

When the value of @Dept is NULL the query will be:

select * from table1 WHERE Department=Department

just like 1=1.


问:
Hosting an asp website on EasyCgi
I have developed a website using ASP.NET/VB + SqlServer 2008 and Dotnetnuke CMS.
Now I have to host it on easycgi.com

I have some questions:

How should I restore my db (unfortunately easycgi supports just sqlserver 2005) so what should I do to convert my db to 2005?

and what should I do to host my website (step-by-step "please").

Any help appreciated.

Sorry for my english.

答:
Not familiar with easycgi but often times getting SQL Server can be a lot of work. If you can create a database at easycgi the best thing to do is script out your database in SQL server 2008 using this process SQL Server 2008 script data

You'll then have everything for your database in a file.  It's scripted and then run that at easy cgi if they have a way to run scripts. Otherwise sometimes you can connect your SQL SErver management studio directly to your database there.

You'll get a temp URL probably at easycgi, make sure that is in PortalAlias table in your SQL Server database.

Update your web.config in two spots to connect to your new database, upload your files to the web server.

Again, never used easycgi, but hope this helps.

Title: Hosting an asp website on EasyCgi


问:
ClassNotFoundException & app crashing
I'm working with Android Studio on a learning app, but when i run it, it crashes and give me this error code:

```<code>03-29 22:36:03.546 13455-13455/com.training.criminalintent E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.training.criminalintent, PID: 13455
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.training.criminalintent/com.training.criminalintent.CrimeListActivity}: java.lang.ClassNotFoundException: Didn't find class "com.training.criminalintent.CrimeListActivity" on path: DexPathList[[zip file "/data/app/com.training.criminalintent-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2290)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
    at android.app.ActivityThread.access$800(ActivityThread.java:156)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:211)
    at android.app.ActivityThread.main(ActivityThread.java:5371)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:945)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:740)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.training.criminalintent.CrimeListActivity" on path: DexPathList[[zip file "/data/app/com.training.criminalintent-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2280)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
    at android.app.ActivityThread.access$800(ActivityThread.java:156)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:211)
    at android.app.ActivityThread.main(ActivityThread.java:5371)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:945)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:740)
Suppressed: java.lang.ClassNotFoundException: com.training.criminalintent.CrimeListActivity
    at java.lang.Class.classForName(Native Method)
    at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
    at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
        ... 13 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
</code>```

I looked for a solution but didn't find something adequate for android studio, but most importantly i didn't find the source of the problem, why android studio is behaving like that.

EDIT: The activity exists in the manifest File :

```<code><application
>     android:allowBackup="true"
>     android:icon="@mipmap/ic_launcher"
>     android:label="@string/app_name"
>     android:supportsRtl="true"
>     android:theme="@style/AppTheme">
>     <activity android:name=".CrimeListActivity">
>         <intent-filter>
>             <action android:name="android.intent.action.MAIN" />
>             <category android:name="android.intent.category.LAUNCHER" />
>         </intent-filter>
>     </activity>
>     <activity android:name=".CrimePagerActivity">
>     </activity> </application>
</code>```

I must also precise that before i downgraded the tools folder in the sdk (compatibility problem with another software)[I named the folder tools ==> toolsXXXX and download the version 24.2 and put the tools folder in the sdk folder], it was working..

答:
Make sure com.training.criminalintent.CrimeListActivity exists in your AndroidManifest.xml.

```<code><activity android:name="com.training.criminalintent.CrimeListActivity" />
</code>```

Title: ClassNotFoundException & app crashing

Body:
I'm working with Android Studio on a learning app, but when i run it, it crashes and give me this error code:

03-29 22:36:03.546 13455-13455/com.training.criminalintent E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.training.criminalintent, PID: 13455
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.training.criminalintent/com.training.criminalintent.CrimeListActivity}: java.lang.ClassNotFoundException: Didn't find class "com.training.criminalintent.CrimeListActivity" on path: DexPathList[[zip file "/data/app/com.training.criminalintent-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2290)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
    at android.app.ActivityThread.access$800(ActivityThread.java:156)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:211)
    at android.app.ActivityThread.main(ActivityThread.java:5371)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:945)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:740)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.training.criminalintent.CrimeListActivity" on path: DexPathList[[zip file "/data/app/com.training.criminalintent-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2280)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
    at android.app.ActivityThread.access$800(ActivityThread.java:156)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:211)
    at android.app.ActivityThread.main(ActivityThread.java:5371)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:945)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:740)
Suppressed: java.lang.ClassNotFoundException: com.training.criminalintent.CrimeListActivity
    at java.lang.Class.classForName(Native Method)
    at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
    at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
        ... 13 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

I looked for a solution but didn't find something adequate for android studio, but most importantly i didn't find the source of the problem, why android studio is behaving like that.

EDIT: The activity exists in the manifest File :

<application
>     android:allowBackup="true"
>     android:icon="@mipmap/ic_launcher"
>     android:label="@string/app_name"
>     android:supportsRtl="true"
>     android:theme="@style/AppTheme">
>     <activity android:name=".CrimeListActivity">
>         <intent-filter>
>             <action android:name="android.intent.action.MAIN" />
>             <category android:name="android.intent.category.LAUNCHER" />
>         </intent-filter>
>     </activity>
>     <activity android:name=".CrimePagerActivity">
>     </activity> </application>

I must also precise that before i downgraded the tools folder in the sdk (compatibility problem with another software)[I named the folder tools ==> toolsXXXX and download the version 24.2 and put the tools folder in the sdk folder], it was working..

Body:
Make sure com.training.criminalintent.CrimeListActivity exists in your AndroidManifest.xml.

<activity android:name="com.training.criminalintent.CrimeListActivity" />


问:
How to check an email address for existence programmatically on Gmail?
If you google "How to check an email address for existence" question, you will find, basically, only solutions using SMTP protocol what is not reliable. I tried this approach and found that Gmail SMTP server says "Yes, this email is registered here" on each and every email address I ask about. I suspect such strategy is used on the majority of popular email servers.</p>

答:
The method I would like to share is used in Gmail registration form to ensure you are going to register a brand new email. It uses AJAX request to ask Gmail server if given email exists or not

```<code>Request URL:https://accounts.google.com/InputValidator?resource=SignUp
Request Method:POST
Status Code:200
Remote Address:173.194.222.84:443
</code>```

Response Headers

```<code>alt-svc:quic=":443"; ma=2592000; v="37,36,35"
cache-control:private, max-age=0
content-encoding:gzip
content-type:application/json; charset=utf-8
date:Wed, 29 Mar 2017 21:06:06 GMT
expires:Wed, 29 Mar 2017 21:06:06 GMT
server:GSE
set-cookie:GAPS=1:<redacted>;Path=/;Expires=Fri, 29-Mar-2019 21:06:06 GMT;Secure;HttpOnly;Priority=HIGH
status:200
strict-transport-security:max-age=10893354; includeSubDomains
x-content-type-options:nosniff
x-frame-options:DENY
x-xss-protection:1; mode=block
</code>```

Request Headers

```<code>Provisional headers are shown
Content-type:application/json
Origin:https://accounts.google.com
Referer:https://accounts.google.com/SignUp?hl=en-GB
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
</code>```

Query String Parameters

```<code>resource=SignUp
</code>```

Request Payload

```<code>{"input01":{"Input":"GmailAddress","GmailAddress":"andy.v.che","FirstName":"","LastName":""},"Locale":"en-GB"}
</code>```

Response

```<code>{"input01":{"Valid":"false","ErrorMessage":"Someone already has that username. Note that we ignore full stops and capitalisation in usernames. Try another?","Errors":{"GmailAddress":"Someone already has that username. Note that we ignore full stops and capitalisation in usernames. Try another?"},"ErrorData":["andyvche959"]},"Locale":"en_GB"}
</code>```

As you can see, there is "Valid":"false" in the response if such an email does exist, and (spoilers) "Valid":"true" if it doesn't.

Throttling queries down

Guys from Gmail do understand this method could be used by spammers to look for existing emails. That's why they don't allow massive scans using it. I was doing such a scan for some time and could scan only 200 emails a day approximately.

More details

I was scanning 1 email a minute, and if I was getting response "No, this email doesn't exist", I also asked if my own email exists. If I got "No, your email doesn't exist as well" answer, I could clearly understand that I got ban from Gmail server by my IP address. Then, I took a break for 45 minutes to get unbanned, then continued the loop. The number af emails scanned a day was fluctuating around 200.

You may ask: you did a scan like a spammer would perform, for what purpose did you do that scan then?

My answer is: I was trying to find a guy who wrote his email unclearly (bad cursive). There was no other option to find him.

There were 3 unclear letters in his written email but it was clear the domain of it is gmail.com, so I came up with an idea to find a way to check an email address for existence on Gmail, generate a list of all possible emails (trying to substitute unknown symbols with all possible English letters) and check them all for existence. Then, send a letter to all existing ones.

The right of this information to be published is discussed in this question. I understand this article will be very useful for spammers so I'm open to deleting it partially or even completely for the sake of security.

Body:
The method I would like to share is used in Gmail registration form to ensure you are going to register a brand new email. It uses AJAX request to ask Gmail server if given email exists or not

Request URL:https://accounts.google.com/InputValidator?resource=SignUp
Request Method:POST
Status Code:200
Remote Address:173.194.222.84:443

Response Headers

alt-svc:quic=":443"; ma=2592000; v="37,36,35"
cache-control:private, max-age=0
content-encoding:gzip
content-type:application/json; charset=utf-8
date:Wed, 29 Mar 2017 21:06:06 GMT
expires:Wed, 29 Mar 2017 21:06:06 GMT
server:GSE
set-cookie:GAPS=1:<redacted>;Path=/;Expires=Fri, 29-Mar-2019 21:06:06 GMT;Secure;HttpOnly;Priority=HIGH
status:200
strict-transport-security:max-age=10893354; includeSubDomains
x-content-type-options:nosniff
x-frame-options:DENY
x-xss-protection:1; mode=block

Request Headers

Provisional headers are shown
Content-type:application/json
Origin:https://accounts.google.com
Referer:https://accounts.google.com/SignUp?hl=en-GB
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36

Query String Parameters

resource=SignUp

Request Payload

{"input01":{"Input":"GmailAddress","GmailAddress":"andy.v.che","FirstName":"","LastName":""},"Locale":"en-GB"}

Response

{"input01":{"Valid":"false","ErrorMessage":"Someone already has that username. Note that we ignore full stops and capitalisation in usernames. Try another?","Errors":{"GmailAddress":"Someone already has that username. Note that we ignore full stops and capitalisation in usernames. Try another?"},"ErrorData":["andyvche959"]},"Locale":"en_GB"}

As you can see, there is "Valid":"false" in the response if such an email does exist, and (spoilers) "Valid":"true" if it doesn't.

Throttling queries down

Guys from Gmail do understand this method could be used by spammers to look for existing emails. That's why they don't allow massive scans using it. I was doing such a scan for some time and could scan only 200 emails a day approximately.

More details

I was scanning 1 email a minute, and if I was getting response "No, this email doesn't exist", I also asked if my own email exists. If I got "No, your email doesn't exist as well" answer, I could clearly understand that I got ban from Gmail server by my IP address. Then, I took a break for 45 minutes to get unbanned, then continued the loop. The number af emails scanned a day was fluctuating around 200.

You may ask: you did a scan like a spammer would perform, for what purpose did you do that scan then?

My answer is: I was trying to find a guy who wrote his email unclearly (bad cursive). There was no other option to find him.

There were 3 unclear letters in his written email but it was clear the domain of it is gmail.com, so I came up with an idea to find a way to check an email address for existence on Gmail, generate a list of all possible emails (trying to substitute unknown symbols with all possible English letters) and check them all for existence. Then, send a letter to all existing ones.

The right of this information to be published is discussed in this question. I understand this article will be very useful for spammers so I'm open to deleting it partially or even completely for the sake of security.