问:
Can't get radio button styling to work in plunker
I'm trying to get the skewed radio button style found here (https://codepen.io/anon/pen/yXNopJ) to work in my project. Visually it looks right but doesn't do anything on click. So to debug I thought I'd place this in plunker and play around with it in an isolated area. However when I copy and paste the html and css into Plunker the visuals don't work. Can anyone see why the visuals don't work in plunker but do in codepen?

http://plnkr.co/edit/IPiDZdLS51UzAwUcQZHp?p=preview

HTML

```<code><h2>Toggle 'em</h2>
<ul class="tg-list">
  <li class="tg-list-item">
    <h4>Light</h4>
    <input class="tgl tgl-light" id="cb1" type="checkbox"/>
    <label class="tgl-btn" for="cb1"></label>
  </li>
  <li class="tg-list-item">
    <h4>iOS</h4>
    <input class="tgl tgl-ios" id="cb2" type="checkbox"/>
    <label class="tgl-btn" for="cb2"></label>
  </li>
  <li class="tg-list-item">
    <h4>Skewed</h4>
    <input class="tgl tgl-skewed" id="cb3" type="checkbox"/>
    <label class="tgl-btn" data-tg-off="OFF" data-tg-on="ON" for="cb3"></label>
  </li>
  <li class="tg-list-item">
    <h4>Flat</h4>
    <input class="tgl tgl-flat" id="cb4" type="checkbox"/>
    <label class="tgl-btn" for="cb4"></label>
  </li>
  <li class="tg-list-item">
    <h4>Flip</h4>
    <input class="tgl tgl-flip" id="cb5" type="checkbox"/>
    <label class="tgl-btn" data-tg-off="Nope" data-tg-on="Yeah!" for="cb5"></label>
  </li>
</ul>
</code>```

CSS

```<code>html, body {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  min-height: 100%;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
      -ms-flex-direction: column;
          flex-direction: column;
  font-family: sans-serif;
}

ul, li {
  list-style: none;
  margin: 0;
  padding: 0;
}

.tg-list {
  text-align: center;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
}

.tg-list-item {
  margin: 0 2em;
}

h2 {
  color: #777;
}

h4 {
  color: #999;
}

.tgl {
  display: none;
}
.tgl, .tgl:after, .tgl:before, .tgl *, .tgl *:after, .tgl *:before, .tgl + .tgl-btn {
  box-sizing: border-box;
}
.tgl::-moz-selection, .tgl:after::-moz-selection, .tgl:before::-moz-selection, .tgl *::-moz-selection, .tgl *:after::-moz-selection, .tgl *:before::-moz-selection, .tgl + .tgl-btn::-moz-selection {
  background: none;
}
.tgl::selection, .tgl:after::selection, .tgl:before::selection, .tgl *::selection, .tgl *:after::selection, .tgl *:before::selection, .tgl + .tgl-btn::selection {
  background: none;
}
.tgl + .tgl-btn {
  outline: 0;
  display: block;
  width: 4em;
  height: 2em;
  position: relative;
  cursor: pointer;
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
}
.tgl + .tgl-btn:after, .tgl + .tgl-btn:before {
  position: relative;
  display: block;
  content: "";
  width: 50%;
  height: 100%;
}
.tgl + .tgl-btn:after {
  left: 0;
}
.tgl + .tgl-btn:before {
  display: none;
}
.tgl:checked + .tgl-btn:after {
  left: 50%;
}

.tgl-light + .tgl-btn {
  background: #f0f0f0;
  border-radius: 2em;
  padding: 2px;
  -webkit-transition: all .4s ease;
  transition: all .4s ease;
}
.tgl-light + .tgl-btn:after {
  border-radius: 50%;
  background: #fff;
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
}
.tgl-light:checked + .tgl-btn {
  background: #9FD6AE;
}

.tgl-ios + .tgl-btn {
  background: #fbfbfb;
  border-radius: 2em;
  padding: 2px;
  -webkit-transition: all .4s ease;
  transition: all .4s ease;
  border: 1px solid #e8eae9;
}
.tgl-ios + .tgl-btn:after {
  border-radius: 2em;
  background: #fbfbfb;
  -webkit-transition: left 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), padding 0.3s ease, margin 0.3s ease;
  transition: left 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), padding 0.3s ease, margin 0.3s ease;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1), 0 4px 0 rgba(0, 0, 0, 0.08);
}
.tgl-ios + .tgl-btn:hover:after {
  will-change: padding;
}
.tgl-ios + .tgl-btn:active {
  box-shadow: inset 0 0 0 2em #e8eae9;
}
.tgl-ios + .tgl-btn:active:after {
  padding-right: .8em;
}
.tgl-ios:checked + .tgl-btn {
  background: #86d993;
}
.tgl-ios:checked + .tgl-btn:active {
  box-shadow: none;
}
.tgl-ios:checked + .tgl-btn:active:after {
  margin-left: -.8em;
}

.tgl-skewed + .tgl-btn {
  overflow: hidden;
  -webkit-transform: skew(-10deg);
          transform: skew(-10deg);
  -webkit-backface-visibility: hidden;
          backface-visibility: hidden;
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
  font-family: sans-serif;
  background: #888;
}
.tgl-skewed + .tgl-btn:after, .tgl-skewed + .tgl-btn:before {
  -webkit-transform: skew(10deg);
          transform: skew(10deg);
  display: inline-block;
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
  width: 100%;
  text-align: center;
  position: absolute;
  line-height: 2em;
  font-weight: bold;
  color: #fff;
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4);
}
.tgl-skewed + .tgl-btn:after {
  left: 100%;
  content: attr(data-tg-on);
}
.tgl-skewed + .tgl-btn:before {
  left: 0;
  content: attr(data-tg-off);
}
.tgl-skewed + .tgl-btn:active {
  background: #888;
}
.tgl-skewed + .tgl-btn:active:before {
  left: -10%;
}
.tgl-skewed:checked + .tgl-btn {
  background: #86d993;
}
.tgl-skewed:checked + .tgl-btn:before {
  left: -100%;
}
.tgl-skewed:checked + .tgl-btn:after {
  left: 0;
}
.tgl-skewed:checked + .tgl-btn:active:after {
  left: 10%;
}

.tgl-flat + .tgl-btn {
  padding: 2px;
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
  background: #fff;
  border: 4px solid #f2f2f2;
  border-radius: 2em;
}
.tgl-flat + .tgl-btn:after {
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
  background: #f2f2f2;
  content: "";
  border-radius: 1em;
}
.tgl-flat:checked + .tgl-btn {
  border: 4px solid #7FC6A6;
}
.tgl-flat:checked + .tgl-btn:after {
  left: 50%;
  background: #7FC6A6;
}

.tgl-flip + .tgl-btn {
  padding: 2px;
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
  font-family: sans-serif;
  -webkit-perspective: 100px;
          perspective: 100px;
}
.tgl-flip + .tgl-btn:after, .tgl-flip + .tgl-btn:before {
  display: inline-block;
  -webkit-transition: all .4s ease;
  transition: all .4s ease;
  width: 100%;
  text-align: center;
  position: absolute;
  line-height: 2em;
  font-weight: bold;
  color: #fff;
  position: absolute;
  top: 0;
  left: 0;
  -webkit-backface-visibility: hidden;
          backface-visibility: hidden;
  border-radius: 4px;
}
.tgl-flip + .tgl-btn:after {
  content: attr(data-tg-on);
  background: #02C66F;
  -webkit-transform: rotateY(-180deg);
          transform: rotateY(-180deg);
}
.tgl-flip + .tgl-btn:before {
  background: #FF3A19;
  content: attr(data-tg-off);
}
.tgl-flip + .tgl-btn:active:before {
  -webkit-transform: rotateY(-20deg);
          transform: rotateY(-20deg);
}
.tgl-flip:checked + .tgl-btn:before {
  -webkit-transform: rotateY(180deg);
          transform: rotateY(180deg);
}
.tgl-flip:checked + .tgl-btn:after {
  -webkit-transform: rotateY(0);
          transform: rotateY(0);
  left: 0;
  background: #7FC6A6;
}
.tgl-flip:checked + .tgl-btn:active:after {
  -webkit-transform: rotateY(20deg);
          transform: rotateY(20deg);
}
</code>```

答:
You need to define the css sheet:

```<code>  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>
</code>```

Working example: https://plnkr.co/edit/F8BN6S0YHG1s6M5tq6zD?p=preview

```<code><!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <h2>Toggle 'em</h2>
<ul class="tg-list">
  <li class="tg-list-item">
    <h4>Light</h4>
    <input class="tgl tgl-light" id="cb1" type="checkbox" />
    <label class="tgl-btn" for="cb1"></label>
  </li>
  <li class="tg-list-item">
    <h4>iOS</h4>
    <input class="tgl tgl-ios" id="cb2" type="checkbox" />
    <label class="tgl-btn" for="cb2"></label>
  </li>
  <li class="tg-list-item">
    <h4>Skewed</h4>
    <input class="tgl tgl-skewed" id="cb3" type="checkbox" />
    <label class="tgl-btn" data-tg-off="OFF" data-tg-on="ON" for="cb3"></label>
  </li>
  <li class="tg-list-item">
    <h4>Flat</h4>
    <input class="tgl tgl-flat" id="cb4" type="checkbox" />
    <label class="tgl-btn" for="cb4"></label>
  </li>
  <li class="tg-list-item">
    <h4>Flip</h4>
    <input class="tgl tgl-flip" id="cb5" type="checkbox" />
    <label class="tgl-btn" data-tg-off="Nope" data-tg-on="Yeah!" for="cb5"></label>
  </li>
</ul>

  </body>

</html>
</code>```

Body:
I'm trying to get the skewed radio button style found here (https://codepen.io/anon/pen/yXNopJ) to work in my project. Visually it looks right but doesn't do anything on click. So to debug I thought I'd place this in plunker and play around with it in an isolated area. However when I copy and paste the html and css into Plunker the visuals don't work. Can anyone see why the visuals don't work in plunker but do in codepen?

http://plnkr.co/edit/IPiDZdLS51UzAwUcQZHp?p=preview

HTML

Toggle 'em

Light

    <input class="tgl tgl-light" id="cb1" type="checkbox"/>

iOS

    <input class="tgl tgl-ios" id="cb2" type="checkbox"/>

Skewed

    <input class="tgl tgl-skewed" id="cb3" type="checkbox"/>

Flat

    <input class="tgl tgl-flat" id="cb4" type="checkbox"/>

Flip

    <input class="tgl tgl-flip" id="cb5" type="checkbox"/>

CSS

html, body {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  min-height: 100%;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
      -ms-flex-direction: column;
          flex-direction: column;
  font-family: sans-serif;
}

ul, li {
  list-style: none;
  margin: 0;
  padding: 0;
}

.tg-list {
  text-align: center;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
}

.tg-list-item {
  margin: 0 2em;
}

h2 {
  color: #777;
}

h4 {
  color: #999;
}

.tgl {
  display: none;
}
.tgl, .tgl:after, .tgl:before, .tgl *, .tgl *:after, .tgl *:before, .tgl + .tgl-btn {
  box-sizing: border-box;
}
.tgl::-moz-selection, .tgl:after::-moz-selection, .tgl:before::-moz-selection, .tgl *::-moz-selection, .tgl *:after::-moz-selection, .tgl *:before::-moz-selection, .tgl + .tgl-btn::-moz-selection {
  background: none;
}
.tgl::selection, .tgl:after::selection, .tgl:before::selection, .tgl *::selection, .tgl *:after::selection, .tgl *:before::selection, .tgl + .tgl-btn::selection {
  background: none;
}
.tgl + .tgl-btn {
  outline: 0;
  display: block;
  width: 4em;
  height: 2em;
  position: relative;
  cursor: pointer;
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
}
.tgl + .tgl-btn:after, .tgl + .tgl-btn:before {
  position: relative;
  display: block;
  content: "";
  width: 50%;
  height: 100%;
}
.tgl + .tgl-btn:after {
  left: 0;
}
.tgl + .tgl-btn:before {
  display: none;
}
.tgl:checked + .tgl-btn:after {
  left: 50%;
}

.tgl-light + .tgl-btn {
  background: #f0f0f0;
  border-radius: 2em;
  padding: 2px;
  -webkit-transition: all .4s ease;
  transition: all .4s ease;
}
.tgl-light + .tgl-btn:after {
  border-radius: 50%;
  background: #fff;
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
}
.tgl-light:checked + .tgl-btn {
  background: #9FD6AE;
}

.tgl-ios + .tgl-btn {
  background: #fbfbfb;
  border-radius: 2em;
  padding: 2px;
  -webkit-transition: all .4s ease;
  transition: all .4s ease;
  border: 1px solid #e8eae9;
}
.tgl-ios + .tgl-btn:after {
  border-radius: 2em;
  background: #fbfbfb;
  -webkit-transition: left 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), padding 0.3s ease, margin 0.3s ease;
  transition: left 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), padding 0.3s ease, margin 0.3s ease;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1), 0 4px 0 rgba(0, 0, 0, 0.08);
}
.tgl-ios + .tgl-btn:hover:after {
  will-change: padding;
}
.tgl-ios + .tgl-btn:active {
  box-shadow: inset 0 0 0 2em #e8eae9;
}
.tgl-ios + .tgl-btn:active:after {
  padding-right: .8em;
}
.tgl-ios:checked + .tgl-btn {
  background: #86d993;
}
.tgl-ios:checked + .tgl-btn:active {
  box-shadow: none;
}
.tgl-ios:checked + .tgl-btn:active:after {
  margin-left: -.8em;
}

.tgl-skewed + .tgl-btn {
  overflow: hidden;
  -webkit-transform: skew(-10deg);
          transform: skew(-10deg);
  -webkit-backface-visibility: hidden;
          backface-visibility: hidden;
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
  font-family: sans-serif;
  background: #888;
}
.tgl-skewed + .tgl-btn:after, .tgl-skewed + .tgl-btn:before {
  -webkit-transform: skew(10deg);
          transform: skew(10deg);
  display: inline-block;
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
  width: 100%;
  text-align: center;
  position: absolute;
  line-height: 2em;
  font-weight: bold;
  color: #fff;
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4);
}
.tgl-skewed + .tgl-btn:after {
  left: 100%;
  content: attr(data-tg-on);
}
.tgl-skewed + .tgl-btn:before {
  left: 0;
  content: attr(data-tg-off);
}
.tgl-skewed + .tgl-btn:active {
  background: #888;
}
.tgl-skewed + .tgl-btn:active:before {
  left: -10%;
}
.tgl-skewed:checked + .tgl-btn {
  background: #86d993;
}
.tgl-skewed:checked + .tgl-btn:before {
  left: -100%;
}
.tgl-skewed:checked + .tgl-btn:after {
  left: 0;
}
.tgl-skewed:checked + .tgl-btn:active:after {
  left: 10%;
}

.tgl-flat + .tgl-btn {
  padding: 2px;
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
  background: #fff;
  border: 4px solid #f2f2f2;
  border-radius: 2em;
}
.tgl-flat + .tgl-btn:after {
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
  background: #f2f2f2;
  content: "";
  border-radius: 1em;
}
.tgl-flat:checked + .tgl-btn {
  border: 4px solid #7FC6A6;
}
.tgl-flat:checked + .tgl-btn:after {
  left: 50%;
  background: #7FC6A6;
}

.tgl-flip + .tgl-btn {
  padding: 2px;
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
  font-family: sans-serif;
  -webkit-perspective: 100px;
          perspective: 100px;
}
.tgl-flip + .tgl-btn:after, .tgl-flip + .tgl-btn:before {
  display: inline-block;
  -webkit-transition: all .4s ease;
  transition: all .4s ease;
  width: 100%;
  text-align: center;
  position: absolute;
  line-height: 2em;
  font-weight: bold;
  color: #fff;
  position: absolute;
  top: 0;
  left: 0;
  -webkit-backface-visibility: hidden;
          backface-visibility: hidden;
  border-radius: 4px;
}
.tgl-flip + .tgl-btn:after {
  content: attr(data-tg-on);
  background: #02C66F;
  -webkit-transform: rotateY(-180deg);
          transform: rotateY(-180deg);
}
.tgl-flip + .tgl-btn:before {
  background: #FF3A19;
  content: attr(data-tg-off);
}
.tgl-flip + .tgl-btn:active:before {
  -webkit-transform: rotateY(-20deg);
          transform: rotateY(-20deg);
}
.tgl-flip:checked + .tgl-btn:before {
  -webkit-transform: rotateY(180deg);
          transform: rotateY(180deg);
}
.tgl-flip:checked + .tgl-btn:after {
  -webkit-transform: rotateY(0);
          transform: rotateY(0);
  left: 0;
  background: #7FC6A6;
}
.tgl-flip:checked + .tgl-btn:active:after {
  -webkit-transform: rotateY(20deg);
          transform: rotateY(20deg);
}

Body:
You need to define the css sheet:

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

Working example: https://plnkr.co/edit/F8BN6S0YHG1s6M5tq6zD?p=preview

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <h2>Toggle 'em</h2>
<ul class="tg-list">
  <li class="tg-list-item">
    <h4>Light</h4>
    <input class="tgl tgl-light" id="cb1" type="checkbox" />
    <label class="tgl-btn" for="cb1"></label>
  </li>
  <li class="tg-list-item">
    <h4>iOS</h4>
    <input class="tgl tgl-ios" id="cb2" type="checkbox" />
    <label class="tgl-btn" for="cb2"></label>
  </li>
  <li class="tg-list-item">
    <h4>Skewed</h4>
    <input class="tgl tgl-skewed" id="cb3" type="checkbox" />
    <label class="tgl-btn" data-tg-off="OFF" data-tg-on="ON" for="cb3"></label>
  </li>
  <li class="tg-list-item">
    <h4>Flat</h4>
    <input class="tgl tgl-flat" id="cb4" type="checkbox" />
    <label class="tgl-btn" for="cb4"></label>
  </li>
  <li class="tg-list-item">
    <h4>Flip</h4>
    <input class="tgl tgl-flip" id="cb5" type="checkbox" />
    <label class="tgl-btn" data-tg-off="Nope" data-tg-on="Yeah!" for="cb5"></label>
  </li>
</ul>

  </body>

</html>


来源: stackexchange

问:
Simple Javascript Regex Question
Google is failing me because ?= is not searchable.  What does

```<code>(?=[aeiouy])
</code>```

match -- specifically ?=, I know that [aeiouy] is any of aeiouy.

答:
From MDC:

x(?=y)

Matches x only if x is followed by y.

For example, /Jack(?=Sprat)/ matches 'Jack' only if it is followed by 'Sprat'. /Jack(?=Sprat|Frost)/ matches 'Jack' only if it is followed by 'Sprat' or 'Frost'. However, neither 'Sprat' nor 'Frost' is part of the match results.

So:

```<code>foo(?=[aeiouy])
</code>```

Would match fooe, fooi etc. but not foo alone, but as already stated in the quote, the vowel in this case will not be included in the match itself.

ContentLicense: CC BY-SA 2.5

Title: Simple Javascript Regex Question

Body:
Google is failing me because ?= is not searchable.  What does

(?=[aeiouy])

match -- specifically ?=, I know that [aeiouy] is any of aeiouy.

Body:
From MDC:

x(?=y)

Matches x only if x is followed by y.

For example, /Jack(?=Sprat)/ matches 'Jack' only if it is followed by 'Sprat'. /Jack(?=Sprat|Frost)/ matches 'Jack' only if it is followed by 'Sprat' or 'Frost'. However, neither 'Sprat' nor 'Frost' is part of the match results.

So:

foo(?=[aeiouy])

Would match fooe, fooi etc. but not foo alone, but as already stated in the quote, the vowel in this case will not be included in the match itself.


问:
mysql select only groups having certain length
Lets say, i have a table like this:

table1

```<code>  id | val
_____________
   1 | a
   2 | b
   3 | b
   4 | a
   5 | b
   6 | a
   7 | c
</code>```

and i want to have all rows grouped by val but only if the size of the group is 3. So intended result is:

```<code>[1, a], [4, a], [6, a]
[2, b], [3, b], [5, b]
</code>```

[7, c] should be ignored cause the size of it's group is less than 3.

Note, the solution with having will return one row for each group and i want to see them all.

答:
You can use the following query:</p>

```<code>SELECT
    id,
    val as letter,
    (select count(*) FROM things WHERE val=letter) as number
  FROM things
HAVING number >= 3;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Lets say, i have a table like this:

table1

  id | val
_____________
   1 | a
   2 | b
   3 | b
   4 | a
   5 | b
   6 | a
   7 | c

and i want to have all rows grouped by val but only if the size of the group is 3. So intended result is:

[1, a], [4, a], [6, a]
[2, b], [3, b], [5, b]

[7, c] should be ignored cause the size of it's group is less than 3.

Note, the solution with having will return one row for each group and i want to see them all.

Body:
You can use the following query:

SELECT
    id,
    val as letter,
    (select count(*) FROM things WHERE val=letter) as number
  FROM things
HAVING number >= 3;


问:
Increment page value when passing through URL
I need to pass the value of page by increasing one. This is my pure code

```<code><?php echo "<li><a href='pro.php?page=$page'><span class='ico-next'></span></a></li>" ?>
</code>```

this is I tried one

```<code><?php echo "<li><a href='pro.php?page=.$page++.'><span class='ico-next'></span></a></li>" ?>
</code>```

But its not working,how can I pass the value by increasing it by one

答:
This is not possible due to limitations of the php parser. You have to use concatenation instead:

```<code><?php echo "<li><a href='pro.php?page=" . ++$page . "'>";
</code>```

Some find it easier to read such style, it separates formatting and computation:

```<code><?php echo sprintf("<li><a href='pro.php?page=%s'>", ++$page);
</code>```

Note that you probably also need to use ++$page instead of $page++, though that depends on your actual situation.

Body:
I need to pass the value of page by increasing one. This is my pure code

<?php echo "

" ?>

this is I tried one

<?php echo "

" ?>

But its not working,how can I pass the value by increasing it by one

Body:
This is not possible due to limitations of the php parser. You have to use concatenation instead:

<?php echo "<li><a href='pro.php?page=" . ++$page . "'>";

Some find it easier to read such style, it separates formatting and computation:

<?php echo sprintf("<li><a href='pro.php?page=%s'>", ++$page);

Note that you probably also need to use ++$page instead of $page++, though that depends on your actual situation.


问:
Tic Tac Toe how to tell user there is no winner?
I'm working in this project for 3 days and i can not figure out where I'm doing wrong if you can help me with i really appreciate your help.I'm trying to create a tic tac toe game .When I'm running the game if the player X or O  wins a message will pop up saying that X or O win .But if the a non of users win a message should pop up and saying there is no winner . the pop up for the winner is working perfectly but the pop up for no one win does not work.if you can help me to fix it you are really making my day.</p>

```<code>public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;

int activePlayer = 0; // for x player

int[] gameState ={2,2,2,2,2,2,2,2,2}; // 2 means unplayed.

int[][] winningLocation ={{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
boolean gameover =false;

public void gameLogic(View view){

    ImageView tappedView =(ImageView) view;

    int tappedLocation = Integer.parseInt(view.getTag().toString());

    if(gameState[tappedLocation]==2 && !gameover) {
        gameState[tappedLocation]=activePlayer;

        tappedView.setTranslationY(-3000f);

        if (activePlayer == 0) {

            tappedView.setImageResource(R.drawable.x);

            activePlayer = 1;

        } else if (activePlayer == 1) {
            tappedView.setImageResource(R.drawable.o);
            activePlayer = 0;
        }
        tappedView.animate().translationYBy(3000f).setDuration(500);
    }
  String mesg ="";

    for(int[]winningPostion :winningLocation){

        if(gameState[winningPostion[0]] == gameState [winningPostion[1]]
                && gameState[winningPostion[1]]== gameState [winningPostion[2]]
                && gameState[winningPostion[0]]!=2){

            if (activePlayer ==0)

                mesg = "O is the winner!";

            if(activePlayer==1)

                mesg = "X is the winner!";

            else
                gameover=true;
            mesg="there is no winner ";

            LinearLayout winnerLayout =(LinearLayout)findViewById (R.id.winnerLayout);
            winnerLayout.setVisibility(View .VISIBLE);

            TextView winnermesg = (TextView) findViewById(R.id.editText);
            winnermesg.setText(mesg);

            gameover=true;
        }
    }

}

// a method that let the players play again

public void playagain(View view){
    LinearLayout winnerLayout = (LinearLayout) findViewById(R.id.winnerLayout);
    winnerLayout.setVisibility(View.INVISIBLE);
    gameover=false;
    activePlayer=0;

    for (int i =0; i < gameState.length;i++)
        gameState[i]=2;

    GridLayout gridlayout = (GridLayout) findViewById(R.id.gridlayout);
    for(int i =0 ; i < gridlayout.getChildCount(); i++)
        ((ImageView)gridlayout.getChildAt(i)).setImageResource(0);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

 // to play the song
      mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.song);
      mediaPlayer.start();

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // to show and hide the playing again button

   LinearLayout winnerLayout = ( LinearLayout) findViewById(R.id.winnerLayout);
    winnerLayout.setVisibility(View.INVISIBLE);

   FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

// pause and play the song when the user leaving annd returning the game
@Override
protected void onPause(){
    super.onPause();
    mediaPlayer.stop();
    mediaPlayer.release();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}
</code>```

答:
```<code>change the forloop with below one....

for(int i=0;i<winningLocation.length;i++){
        Boolean istie = true;
        int []winningPostion = winningLocation[i];
        mesg="there is no winner ";

        if(gameState[winningPostion[0]] == gameState [winningPostion[1]]
                && gameState[winningPostion[1]]== gameState [winningPostion[2]]
                && gameState[winningPostion[0]]!=2){
            mesg="there is no winner ";
            if (activePlayer ==0)
                mesg = "O is the winner!";

            if(activePlayer==1)
                mesg = "X is the winner!";

            LinearLayout winnerLayout =(LinearLayout)findViewById (R.id.winnerLayout);
            winnerLayout.setVisibility(View .VISIBLE);

            TextView winnermesg = (TextView) findViewById(R.id.editText);
            winnermesg.setText(mesg);
            istie = false;
            gameover=true;
             return;
        }
        if(i==winningLocation.length-1){
            if(istie){
                LinearLayout winnerLayout =(LinearLayout)findViewById (R.id.winnerLayout);
                winnerLayout.setVisibility(View .VISIBLE);

                TextView winnermesg = (TextView) findViewById(R.id.editText);
                winnermesg.setText(mesg);
            }

        }
    }
</code>```

Body:
I'm working in this project for 3 days and i can not figure out where I'm doing wrong if you can help me with i really appreciate your help.I'm trying to create a tic tac toe game .When I'm running the game if the player X or O  wins a message will pop up saying that X or O win .But if the a non of users win a message should pop up and saying there is no winner . the pop up for the winner is working perfectly but the pop up for no one win does not work.if you can help me to fix it you are really making my day.

public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;

int activePlayer = 0; // for x player

int[] gameState ={2,2,2,2,2,2,2,2,2}; // 2 means unplayed.

int[][] winningLocation ={{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
boolean gameover =false;

public void gameLogic(View view){

    ImageView tappedView =(ImageView) view;

    int tappedLocation = Integer.parseInt(view.getTag().toString());

    if(gameState[tappedLocation]==2 && !gameover) {
        gameState[tappedLocation]=activePlayer;

        tappedView.setTranslationY(-3000f);

        if (activePlayer == 0) {

            tappedView.setImageResource(R.drawable.x);

            activePlayer = 1;

        } else if (activePlayer == 1) {
            tappedView.setImageResource(R.drawable.o);
            activePlayer = 0;
        }
        tappedView.animate().translationYBy(3000f).setDuration(500);
    }
  String mesg ="";

    for(int[]winningPostion :winningLocation){

        if(gameState[winningPostion[0]] == gameState [winningPostion[1]]
                && gameState[winningPostion[1]]== gameState [winningPostion[2]]
                && gameState[winningPostion[0]]!=2){

            if (activePlayer ==0)

                mesg = "O is the winner!";

            if(activePlayer==1)

                mesg = "X is the winner!";

            else
                gameover=true;
            mesg="there is no winner ";

            LinearLayout winnerLayout =(LinearLayout)findViewById (R.id.winnerLayout);
            winnerLayout.setVisibility(View .VISIBLE);

            TextView winnermesg = (TextView) findViewById(R.id.editText);
            winnermesg.setText(mesg);

            gameover=true;
        }
    }

}

// a method that let the players play again

public void playagain(View view){
    LinearLayout winnerLayout = (LinearLayout) findViewById(R.id.winnerLayout);
    winnerLayout.setVisibility(View.INVISIBLE);
    gameover=false;
    activePlayer=0;

    for (int i =0; i < gameState.length;i++)
        gameState[i]=2;

    GridLayout gridlayout = (GridLayout) findViewById(R.id.gridlayout);
    for(int i =0 ; i < gridlayout.getChildCount(); i++)
        ((ImageView)gridlayout.getChildAt(i)).setImageResource(0);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

 // to play the song
      mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.song);
      mediaPlayer.start();

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // to show and hide the playing again button

   LinearLayout winnerLayout = ( LinearLayout) findViewById(R.id.winnerLayout);
    winnerLayout.setVisibility(View.INVISIBLE);

   FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

// pause and play the song when the user leaving annd returning the game
@Override
protected void onPause(){
    super.onPause();
    mediaPlayer.stop();
    mediaPlayer.release();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}


问:
Buildroot + QT5 + VC4 opengl - not all examples run ok
While learning buildroot i write this document
https://github.com/EliArad/MyDocuments/blob/master/Linux/Buildroot/Buildroot_image_with_Qt5_OPEGN_GLS_2.0_mesa_VC4_driver_in_32_bit.odt

That list the steps i make to get QT5 run with the VC4 driver.

The status for now is that i managed to get the device loaded.
I built image with buildroot with examples for qt5.

But not all the examples are working fine.
some works and the majority not.
for example, the marron game
and animation are not showing ( just gray screen)

many of the help out there are referring to vc4 + raspbian jessie
but i want to make it work using build root.

Can you please tell me what should be done to make it work perfectly
using buildroot?

答:
*This is not final answer but some issue solved.

I found several things , not yet complete my mission here but                           1. I need the x.org  fbdev , because QT uses this plugin to determine the screen size.                                                                                2. Need to install libxkbcommon  for the keyboard                                          3. Need to add  export QT_QPA_EGLFS_NO_LIBINPUT=1     found it here:

4. Need to link between  /usr/share/fonts to /usr/lib/fonts
  because buildroot install it in usr/share/fonts
and qt wants it in usr/lib/fonts ( howto use fontconfig?)
https://github.com/carlonluca/pot/issues/54

5. QT complains that it cannot decode png files.  there is also some issue with fake kms or kms.  I checked raspbian and there only fake kms works but without mouse left click. if some one use buildroot with QT and can share with us it will be great.


问:
Getting timezone not found error while performing group by month in Laravel Carbon
I'm trying to run the following SQL query in Laravel Eloquent syntax (not correct yet so not shown here) to select the number of occurrences of startdate in a given range of dates:

```<code>SELECT  COUNT(startdate) as TotalCount
FROM    Users
WHERE   startdate >= '2017-01-01'
AND     startdate <= '2017-12-31'
AND     startdate IS NOT NULL
GROUP BY Month(startdate)
</code>```

Now, I am aware that this might not be right. The GroupBy in particular is not correct. I also keep getting a "Timezone not found in Database" error. How do I correct the error and perform a correct query, so that the results are somewhat like the following:

```<code>January: 1
February: 3
March: 0
April: 9
....
</code>```

EDIT: The erroneous PHP Code:

```<code> $starters = User::select(DB::raw('Count(*), startdate'))
        ->groupBy(Carbon::parse('startdate')->format('m'))
        ->get();
</code>```

答:
You are probably looking for the MONTHNAME function as documented here... https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_monthname

For your query, it would be pretty simple to use.

```<code>SELECT  MONTHNAME(startdate) AS `month`, COUNT(*) AS `TotalCount`
FROM    Users
WHERE   startdate >= '2017-01-01'
AND     startdate <= '2017-12-31'
AND     startdate IS NOT NULL
GROUP BY MONTHNAME(startdate)
</code>```

You almost always want to select whatever you are grouping by and the rest of the items you are selecting should be aggregates (things like count, sum, avg, etc...)

You just need to be careful here though because if you go back more than one year, it will start including results for the same month in both years because you are only grouping by the month.  If that's what you want, then obviously that's okay but it might be necessary to also add YEAR(startdate) in the select and group by of your query as well.

Body:
I'm trying to run the following SQL query in Laravel Eloquent syntax (not correct yet so not shown here) to select the number of occurrences of startdate in a given range of dates:

SELECT  COUNT(startdate) as TotalCount
FROM    Users
WHERE   startdate >= '2017-01-01'
AND     startdate <= '2017-12-31'
AND     startdate IS NOT NULL
GROUP BY Month(startdate)

Now, I am aware that this might not be right. The GroupBy in particular is not correct. I also keep getting a "Timezone not found in Database" error. How do I correct the error and perform a correct query, so that the results are somewhat like the following:

January: 1
February: 3
March: 0
April: 9
....

EDIT: The erroneous PHP Code:

 $starters = User::select(DB::raw('Count(*), startdate'))
        ->groupBy(Carbon::parse('startdate')->format('m'))
        ->get();

Body:
You are probably looking for the MONTHNAME function as documented here... https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_monthname

For your query, it would be pretty simple to use.

SELECT  MONTHNAME(startdate) AS `month`, COUNT(*) AS `TotalCount`
FROM    Users
WHERE   startdate >= '2017-01-01'
AND     startdate <= '2017-12-31'
AND     startdate IS NOT NULL
GROUP BY MONTHNAME(startdate)

You almost always want to select whatever you are grouping by and the rest of the items you are selecting should be aggregates (things like count, sum, avg, etc...)

You just need to be careful here though because if you go back more than one year, it will start including results for the same month in both years because you are only grouping by the month.  If that's what you want, then obviously that's okay but it might be necessary to also add YEAR(startdate) in the select and group by of your query as well.


问:
Saving Password with Md5
I am using Postgresql,hibernate and Java and I need to store a password. Can someone suggest me how to encrypt the password with md5. Else is there a better way to store secure password in the database

Thanks

答:
You shouldn't use md5 for password hashing. It's built for speed which makes it easier to attack. Use bcrypt instead. Also, you're not supposed to try to decrypt the password after it has been stored. See the examples on the bcrypt page for how to verify a password from user input. More information on how to store passwords safely.

jBcrypt is real simple to use too. Here's how you hash a password:

```<code>BCrypt.hashpw(password_from_user, BCrypt.gensalt());
</code>```

And to verify it:

```<code>BCrypt.checkpw(password_from_user, hashed_password_from_database)
</code>```

Title: Saving Password with Md5

Body:
You shouldn't use md5 for password hashing. It's built for speed which makes it easier to attack. Use bcrypt instead. Also, you're not supposed to try to decrypt the password after it has been stored. See the examples on the bcrypt page for how to verify a password from user input. More information on how to store passwords safely.

jBcrypt is real simple to use too. Here's how you hash a password:

BCrypt.hashpw(password_from_user, BCrypt.gensalt());

And to verify it:

BCrypt.checkpw(password_from_user, hashed_password_from_database)


问:
Handle the Incoming Content from share button not working android 6.0 and higher
I have an app that receives data from the share option and until Android 6.0 it has been working fine. When the app is not running - and I use the share functionality (i.e. via an image). Pick my app. OnNewIntent get called and the intent cantains action.SEND and extras that is ok.
But, when the app is running in the background and I use the share option, then the onNewIntent get called and intent contains action.MAIN and no extras.

here is manifest:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

```<code><intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter >
    <action android:name="android.intent.action.SEND"/>
    <category android:name="android.intent.category.DEFAULT"/>
    <data android:mimeType="text/*" />
</intent-filter>
<intent-filter >
    <action android:name="android.intent.action.SEND"/>
    <category android:name="android.intent.category.DEFAULT"/>
    <data android:mimeType="image/*" />
</intent-filter>
</code>```

java code:

```<code>@Override
 protected void onNewIntent(Intent intent) {
  String action = intent.getAction();
 if(Intent.ACTION_SEND.equals(action)&&intent.hasExtra(Intent.EXTRA_STREAM))
 {
     Uri uri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
        if ("text/".equals(type)) {
            String shareText = intent.getDataString();
           //handleSendText(intent); // Handle text being sent
        } else if (type.startsWith("image/")) {
            getDataFromUri(intent,activity);
        }
}
</code>```

How do I fix this? Is there anything wrong with my code?
Thanks for your help

答:
Is there any special reason why you use onNewIntent ? This function exists only for afew rare edge cases (launchMode to "singleTop").

You should put your Intent-handling into Activity-onCreate and call getIntent() to process send text/image service requests.

Body:
I have an app that receives data from the share option and until Android 6.0 it has been working fine. When the app is not running - and I use the share functionality (i.e. via an image). Pick my app. OnNewIntent get called and the intent cantains action.SEND and extras that is ok.
But, when the app is running in the background and I use the share option, then the onNewIntent get called and intent contains action.MAIN and no extras.

here is manifest:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter >
    <action android:name="android.intent.action.SEND"/>
    <category android:name="android.intent.category.DEFAULT"/>
    <data android:mimeType="text/*" />
</intent-filter>
<intent-filter >
    <action android:name="android.intent.action.SEND"/>
    <category android:name="android.intent.category.DEFAULT"/>
    <data android:mimeType="image/*" />
</intent-filter>

java code:

@Override
 protected void onNewIntent(Intent intent) {
  String action = intent.getAction();
 if(Intent.ACTION_SEND.equals(action)&&intent.hasExtra(Intent.EXTRA_STREAM))
 {
     Uri uri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
        if ("text/".equals(type)) {
            String shareText = intent.getDataString();
           //handleSendText(intent); // Handle text being sent
        } else if (type.startsWith("image/")) {
            getDataFromUri(intent,activity);
        }
}

How do I fix this? Is there anything wrong with my code?
Thanks for your help


问:
Joomla, is this a bad thing, injecting view, model and controller to container?
As the title says, I just want to ask if this is a bad thing or not if I inject all views, models, controllers and other classes like helpers into the container (IoC) for example like the following image.

Sample:

Note: In this case, I make my own base view, model and controller for my component so I don't use default Joomla instance like JModelLegacy::getInstance(); or JControllerLegacy::getInstance();.

Thanks.

答:
This is what I did. I've tired of constant changes that breaks extensions and force to rewrite them without any actual benefit.

I have forced all MVC classes of Joomla and added my prefix to them. Everything works just fine.

I do not think you will have a problem to load everything at once. At least with the list you've shown. If you would have extension with hundreds of views and models, may be you could be hurt.

On the other hand why would you do that? Decouple your library off Joomla's and it will load everything automatically.


问:
Watch website and wait for events
I want to analyze a website that is not mine.
So, I want to use Javascript to do it at my end in the browser.
After I click a button on the website I want to trigger a timer and as soon as a notification from the website comes back, the timer should stop and save the notification that came back.
How can I do this the easiest way?

I cannot give you the link to the website, because it's hosted in a private network.

My first question would be, how I can log all events that are triggered on a website to the console, so I know the name of the button I want to wait for.

Thanks!
dave

答:
If I understand you, the easiest option I see is to open your browser developer tools and using the console get the button (document.getElementById, i.e.) and change its onclick callback, including a call to the old callback in your new callback, and trigger your timer.

To intercept the response to this button (I assume that it triggers a network request), you'll have to analyze a bit the code of the web to see how you can detect it.

You could also edit the website javascript throught "Sources" tab of your browser's dev tools.

It's an idea. I have never done something like that. I have to admit that it sounds a little weird to me.

Title: Watch website and wait for events


问:
Is there a Unity Unet Spawn CallBack function?
On the server，I create an obj, and spawn it. But on the client how do I know when the object is spawned? I want to know whether there is a spawn callback function.</p>

答:
i don't know if you can directly get a callback to the spawn function client side, but you could just attach a script inheriting NetworkBehaviour to the spawned object, and add this in the script :

```<code>public class MySpawnedObject : NetworkBehaviour
{
     void Awake()
     {
          if (!isServer)
             //do what you want with your client
     }
}
</code>```

But do not forget that isServer return true if the current executable is a host, while UNET consider a host to be server AND client, you can also use isClient that will trigger for both hosts and clients.

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

ContentLicense: CC BY-SA 4.0

Body:
i don't know if you can directly get a callback to the spawn function client side, but you could just attach a script inheriting NetworkBehaviour to the spawned object, and add this in the script :

public class MySpawnedObject : NetworkBehaviour
{
     void Awake()
     {
          if (!isServer)
             //do what you want with your client
     }
}

But do not forget that isServer return true if the current executable is a host, while UNET consider a host to be server AND client, you can also use isClient that will trigger for both hosts and clients.

if (isClient)


问:
Formatting URLs in list to all have a trailing slash in python
There's some similar questions to this on stackoverflow but none do exactly what I want and my various attempts seem to fail.

I have a list of urls, some have trailing slash, others not... I want to check them and add a slash to those that don't.

```<code>url_list = ['http://google.com/somedirectory/', 'http://google.com/someotherdirectory/', 'http://google.com/anotherdirectory', 'http://google.com/yetanotherdirectory']

for url in url_list:
    if url[len(url)-1] != "/":
        url = url + "/"
    else:
        url = url

print url_list
</code>```

returns the same list (last two urls still don't have a trailing slash)

```<code>['http://google.com/somedirectory/', 'http://google.com/someotherdirectory/', 'http://google.com/anotherdirectory', 'http://google.com/yetanotherdirectory']
</code>```

why isn't it working? any ideas?

thanks :)

答:
Your url variable is isolated from url_list. You can try this:

```<code>for i, url in enumerate(url_list):
    if url.endswith("/"):
        url_list[i] = url + "/"
print(url_list)
</code>```

Body:
There's some similar questions to this on stackoverflow but none do exactly what I want and my various attempts seem to fail.

I have a list of urls, some have trailing slash, others not... I want to check them and add a slash to those that don't.

url_list = ['http://google.com/somedirectory/', 'http://google.com/someotherdirectory/', 'http://google.com/anotherdirectory', 'http://google.com/yetanotherdirectory']

for url in url_list:
    if url[len(url)-1] != "/":
        url = url + "/"
    else:
        url = url

print url_list

returns the same list (last two urls still don't have a trailing slash)

['http://google.com/somedirectory/', 'http://google.com/someotherdirectory/', 'http://google.com/anotherdirectory', 'http://google.com/yetanotherdirectory']

why isn't it working? any ideas?

thanks :)

Body:
Your url variable is isolated from url_list. You can try this:

for i, url in enumerate(url_list):
    if url.endswith("/"):
        url_list[i] = url + "/"
print(url_list)


问:
Spyder does not show lists and arrays in variable explorer
i don't really know why, but Spyder is not able to show lists or arrays in the variable explorer anymore. Do you have the same problem, any fixes? I have that problem on two computers.

Example:

```<code>CSV = []
for x in os.listdir(location):
    if x.split(".")[-1] =="CSV":
        CSV.append(location+x)
CSV = np.array(CSV)
</code>```

Thank you very much!

答: Just make sure "Exclude capitalized references" in "Tools->Preferences->Variable Explorer" is not marked. The reason you don't see your list in variable explorer is that your list name starts with capital letters and Spyder considers it a capitalized reference. If you define it as for example 'my_csv' or 'aCSV' instead of 'CSV', you don't need to change the setting and it will be fine. </p>

Body:
i don't really know why, but Spyder is not able to show lists or arrays in the variable explorer anymore. Do you have the same problem, any fixes? I have that problem on two computers.

Example:

CSV = []
for x in os.listdir(location):
    if x.split(".")[-1] =="CSV":
        CSV.append(location+x)
CSV = np.array(CSV)

Thank you very much!


问:
dynamically adjust height and/or width of shiny-plotly output based on window size
I would like to have the shiny-plotly output height and width adjusted to the current window size. I have tried to use the below but of no use.

```<code>ShinyUi <- fluidPage(

  # Application title
  titlePanel("title"),

  sidebarLayout(
    sidebarPanel(
      ... inputs ...
    ),

    mainPanel(
          plotlyOutput("distPlot", height = 'auto', width = 'auto')
      )
  ))

ShinyServer <- function(input, output, session) {

   output$distPlot <- renderPlotly({

    p <- ggplot(dataShow, aes(x=dataShow$X, y=dataShow$Y))  +
geom_point(shape=1, alpha = 0.5, color = "grey50")

    ggplotly(p)

  })

}

# Run the application
shinyApp(ui = ShinyUi, server = ShinyServer)
</code>```

Would you know of any other options to use maybe in server function instead of the above UI function usage?

Smaller Window:

Expanded Window:

答:
It does not answer your question but in line to my comments you can add the plot height and width to the ggplotly function using the js from this link.

I have prepared a minimal example of what you are want.

```<code>library(shiny)
library(plotly)

ShinyUi <- fluidPage(
  tags$head(tags$script('
                        var dimension = [0, 0];
                        $(document).on("shiny:connected", function(e) {
                        dimension[0] = window.innerWidth;
                        dimension[1] = window.innerHeight;
                        Shiny.onInputChange("dimension", dimension);
                        });
                        $(window).resize(function(e) {
                        dimension[0] = window.innerWidth;
                        dimension[1] = window.innerHeight;
                        Shiny.onInputChange("dimension", dimension);
                        });
                        ')),

      plotlyOutput("distPlot", width = "auto")

  )

ShinyServer <- function(input, output, session) {

  #To make the responsive to the change in UI size
  observeEvent(input$dimension,{

    output$distPlot <- renderPlotly({

      p <- ggplot(iris, aes(x = Sepal.Length, y=Sepal.Width))  +
        geom_point(shape=1, alpha = 0.5, color = "grey50")
      ggplotly(p, width = (0.95*as.numeric(input$dimension[1])), height = as.numeric(input$dimension[2]))

    })

  })

}

# Run the application
shinyApp(ui = ShinyUi, server = ShinyServer)
</code>```

The output you get is as follows:

Now when you make the window even smaller you still get a plot which occupies the whole screen (no scrollbars!) as follows:

Body:
I would like to have the shiny-plotly output height and width adjusted to the current window size. I have tried to use the below but of no use.

ShinyUi <- fluidPage(

  # Application title
  titlePanel("title"),

  sidebarLayout(
    sidebarPanel(
      ... inputs ...
    ),

    mainPanel(
          plotlyOutput("distPlot", height = 'auto', width = 'auto')
      )
  ))

ShinyServer <- function(input, output, session) {

   output$distPlot <- renderPlotly({

    p <- ggplot(dataShow, aes(x=dataShow$X, y=dataShow$Y))  +
geom_point(shape=1, alpha = 0.5, color = "grey50")

    ggplotly(p)

  })

}

# Run the application
shinyApp(ui = ShinyUi, server = ShinyServer)

Would you know of any other options to use maybe in server function instead of the above UI function usage?

Smaller Window:

Expanded Window:

Body:
It does not answer your question but in line to my comments you can add the plot height and width to the ggplotly function using the js from this link.

I have prepared a minimal example of what you are want.

library(shiny)
library(plotly)

ShinyUi <- fluidPage(
  tags$head(tags$script('
                        var dimension = [0, 0];
                        $(document).on("shiny:connected", function(e) {
                        dimension[0] = window.innerWidth;
                        dimension[1] = window.innerHeight;
                        Shiny.onInputChange("dimension", dimension);
                        });
                        $(window).resize(function(e) {
                        dimension[0] = window.innerWidth;
                        dimension[1] = window.innerHeight;
                        Shiny.onInputChange("dimension", dimension);
                        });
                        ')),

      plotlyOutput("distPlot", width = "auto")

  )

ShinyServer <- function(input, output, session) {

  #To make the responsive to the change in UI size
  observeEvent(input$dimension,{

    output$distPlot <- renderPlotly({

      p <- ggplot(iris, aes(x = Sepal.Length, y=Sepal.Width))  +
        geom_point(shape=1, alpha = 0.5, color = "grey50")
      ggplotly(p, width = (0.95*as.numeric(input$dimension[1])), height = as.numeric(input$dimension[2]))

    })

  })

}

# Run the application
shinyApp(ui = ShinyUi, server = ShinyServer)

The output you get is as follows:

Now when you make the window even smaller you still get a plot which occupies the whole screen (no scrollbars!) as follows:


问:
How to scrape AJAX based websites by using Scrapy and Splash?
I want to make a general scraper which can crawl and scrape all data from any type of website including AJAX websites. I have extensively searched the internet but could not find any proper link which can explain me how Scrapy and Splash together can scrape AJAX websites(which includes pagination,form data and clicking on button before page is displayed). Every link I have referred tells me that Javascript websites can be rendered using Splash but there's no good tutorial/explanation about using Splash to render JS websites. Please don't give me solutions related to using browsers(I want to do everything programmatically,headless browser suggestions are welcome..but I want to use Splash).

class FlipSpider(CrawlSpider):
    name = "flip"
    allowed_domains = ["www.amazon.com"]

    start_urls = ['https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=mobile']

    rules = (Rule(LinkExtractor(), callback='lol', follow=True),

    def parse_start_url(self,response):
       yield scrapy.Request(response.url,
                            self.lol,
                            meta={'splash':{'endpoint':'render.html','args':{'wait': 5,'iframes':1,}}})

    def lol(self, response):
       """
       Some code
       """
```

答:
You can emulate behaviors, like a ckick, or scroll, by writting a JavaScript function and by telling Splash to execute that script when it renders your page.

A little exemple:

You define a JavaScript function that selects an element in the page and then clicks on it:

(source: splash doc)

# Get button element dimensions with javascript and perform mouse click.
_script = """
function main(splash)
    assert(splash:go(splash.args.url))
    local get_dimensions = splash:jsfunc([[
        function () {
            var rect = document.getElementById('button').getClientRects()[0];
            return {"x": rect.left, "y": rect.top}
        }
    ]])
    splash:set_viewport_full()
    splash:wait(0.1)
    local dimensions = get_dimensions()
    splash:mouse_click(dimensions.x, dimensions.y)

    -- Wait split second to allow event to propagate.
    splash:wait(0.1)
    return splash:html()
end
"""
```

<p>Then, when you <code>request</code>, you modify the <code>endpoint</code> and set it to <code>"execute"</code>, and you add <code>"lua_script": _script</code> to the <strong>args</strong>.</p>

<p><strong>Exemple :</strong></p>

<pre class="lang-python prettyprint-override"><code>def parse(self, response):
    yield SplashRequest(response.url, self.parse_elem,
                        endpoint="execute",
                        args={"lua_source": _script})
</code>```

You will find all the informations about splash scripting here

Body:
You can emulate behaviors, like a ckick, or scroll, by writting a JavaScript function and by telling Splash to execute that script when it renders your page.

A little exemple:

You define a JavaScript function that selects an element in the page and then clicks on it:

(source: splash doc)

# Get button element dimensions with javascript and perform mouse click.
_script = """
function main(splash)
    assert(splash:go(splash.args.url))
    local get_dimensions = splash:jsfunc([[
        function () {
            var rect = document.getElementById('button').getClientRects()[0];
            return {"x": rect.left, "y": rect.top}
        }
    ]])
    splash:set_viewport_full()
    splash:wait(0.1)
    local dimensions = get_dimensions()
    splash:mouse_click(dimensions.x, dimensions.y)

    -- Wait split second to allow event to propagate.
    splash:wait(0.1)
    return splash:html()
end
"""

Then, when you request, you modify the endpoint and set it to "execute", and you add "lua_script": _script to the args.

Exemple :

def parse(self, response):
    yield SplashRequest(response.url, self.parse_elem,
                        endpoint="execute",
                        args={"lua_source": _script})

You will find all the informations about splash scripting here


问:
Python 3 dictionary update sequence element error
I'm trying to make a simple Def so I can append my json file easily. I cant get the value(s) to work no matter how I try.

At the top I'm using

```<code>def AppendPersonal_data(X,Y):
    with open( username +'.json') as f:
        keymaster= X,Y
        Personal_data = json.load(f)
        Personal_data.update(keymaster)
        with open(username + '.json', 'w') as f:
            json.dump(Personal_data, f)
</code>```

Then on my button press in my menu I have

```<code>choice = input()
random_number = "1"
if choice == "1":
    if random_number == choice:
        now = str(datetime.now())
        print("YOU PICKED CORRECT!! ")
    else:
        print("YOU PICKED WRONG!! ")
    AppendPersonal_data(random_number,now)
</code>```

No matter what I try I always end up with a :

ValueError: dictionary update sequence element #0 has length 1; 2 is required

答:
There are multiple problems with your code - one being what throws your error - you're trying to update a dictionary (Personal_data) with a tuple (keymaster). You should be updating your dictionary as: Personal_data[X] = Y

But more importantly, you should not open two file handles to the same file at the same time - instead update the already opened file:

```<code>import json

def append_personal_data(username, x, y):
    with open(username + ".json", "r+") as f:
        personal_data = json.load(f)
        personal_data[x] = y
        f.seek(0)  # rewind
        f.truncate()  # clear the file content
        json.dump(personal_data, f)
</code>```

Body:
I'm trying to make a simple Def so I can append my json file easily. I cant get the value(s) to work no matter how I try.

At the top I'm using

def AppendPersonal_data(X,Y):
    with open( username +'.json') as f:
        keymaster= X,Y
        Personal_data = json.load(f)
        Personal_data.update(keymaster)
        with open(username + '.json', 'w') as f:
            json.dump(Personal_data, f)

Then on my button press in my menu I have

choice = input()
random_number = "1"
if choice == "1":
    if random_number == choice:
        now = str(datetime.now())
        print("YOU PICKED CORRECT!! ")
    else:
        print("YOU PICKED WRONG!! ")
    AppendPersonal_data(random_number,now)

No matter what I try I always end up with a :

ValueError: dictionary update sequence element #0 has length 1; 2 is required

Body:
There are multiple problems with your code - one being what throws your error - you're trying to update a dictionary (Personal_data) with a tuple (keymaster). You should be updating your dictionary as: Personal_data[X] = Y

But more importantly, you should not open two file handles to the same file at the same time - instead update the already opened file:

import json

def append_personal_data(username, x, y):
    with open(username + ".json", "r+") as f:
        personal_data = json.load(f)
        personal_data[x] = y
        f.seek(0)  # rewind
        f.truncate()  # clear the file content
        json.dump(personal_data, f)


问:
How can I limit fling in Android gallery to just one item per fling?
I have a gallery with several full screen images. I want to limit the fling gesture to only advance one image at a time (like the HTC Gallery app). What's the right/easiest way to achieve this?</p>

答:
Simply override the Gallery Widget's onFling() method and don't call the superclass onFling() method.

This will make the gallery advance one item per swipe.


答:
Make sure you set your user privileges right
Like -host localhost -user root and -pass {your pass word}

GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY PASSWORD;. Set a user privilege to a particular user like people and then follow the example grant all on people.*to 'root'@'localhost' identified by 'PASSWORD';

Title: mysql acces denied for creating database

Body:
I want to create new DB in mysql.

I am logged in as root. I have set password for root user.

mysql> SHOW GRANTS FOR root;

+---------------------------------------------------------------------------------------------+

| Grants for root@%                                                                           |

+---------------------------------------------------------------------------------------------+

| GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY PASSWORD <secret> WITH GRANT OPTION |

| GRANT PROXY ON ''@'' TO 'root'@'%' WITH GRANT OPTION
|

+---------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

mysql> create database xxx;

ERROR 1044 (42000): Access denied for user 'root'@'localhost' to database 'xxx'

One thing I notice that i do not have mysql db

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| info_schema        |
| sms_auto           |
| smstest            |
+--------------------+

Please can you help me


问:
AJAX does not send FormData Correctly?
I'm working on something to send one image file and few data to PHP file. So I'm using a Form to do that. This is my JS code;

```<code>var pictureForm = new FormData();
var imgFile = $('#avatarSelect')[0];
pictureForm.append('email', email);
pictureForm.append('firName',editfirName);
pictureForm.append('lstName',editlstName);
pictureForm.append('newPass',editpass);
pictureForm.append('newPhn', editphnNum);
pictureForm.append('pictureFile', imgFile.files[0]);

$.ajax({
        type: "POST",
        url: "php/accountUpdate.php",
        dataType:'json',
        data:{pictureForm},
        processData: false,
        contentType: false,
        success : function(response)
        {
            if(response==1)
            {
                alert("Success");

            }
            else
            {
                alert(response);

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

And accountUpdate.php;

```<code><?php
if($_POST)
{
$userEmail= $_POST['email'];
$userPass= $_POST['newPass'];
$userPhone = $_POST['newPhn'];
$userFName= $_POST['firName'];
$userLName = $_POST['lstName'];
$servername ="localhost";
$username="root";
$password="";
$dbname="AS2014459";

// Some code
}
else
 echo json_encode("Error");
?>
</code>```

My Problem

However this always alert me "Error". Means $_POST isn't set properly. I couldn't find the reason. But all the variables such as email,editfirname...etc are properly set and have values.

Also when I run that on my local server (removing PHP if($_POST) condition ) console log says undefined index : email.  Any guesses?

答: You haven't closed off the if/else statement therefore it echos out the error everytime and also use isset($_POST)</p>

Title: AJAX does not send FormData Correctly?

Body:
I'm working on something to send one image file and few data to PHP file. So I'm using a Form to do that. This is my JS code;

var pictureForm = new FormData();
var imgFile = $('#avatarSelect')[0];
pictureForm.append('email', email);
pictureForm.append('firName',editfirName);
pictureForm.append('lstName',editlstName);
pictureForm.append('newPass',editpass);
pictureForm.append('newPhn', editphnNum);
pictureForm.append('pictureFile', imgFile.files[0]);

$.ajax({
        type: "POST",
        url: "php/accountUpdate.php",
        dataType:'json',
        data:{pictureForm},
        processData: false,
        contentType: false,
        success : function(response)
        {
            if(response==1)
            {
                alert("Success");

            }
            else
            {
                alert(response);

            }
        }
    });

And accountUpdate.php;

<?php
if($_POST)
{
$userEmail= $_POST['email'];
$userPass= $_POST['newPass'];
$userPhone = $_POST['newPhn'];
$userFName= $_POST['firName'];
$userLName = $_POST['lstName'];
$servername ="localhost";
$username="root";
$password="";
$dbname="AS2014459";

// Some code
}
else
 echo json_encode("Error");
?>

My Problem

However this always alert me "Error". Means $_POST isn't set properly. I couldn't find the reason. But all the variables such as email,editfirname...etc are properly set and have values.

Also when I run that on my local server (removing PHP if($_POST) condition ) console log says undefined index : email.  Any guesses?


问:
How do I install pip on Windows?
pip is a replacement for easy_install. But should I install pip using easy_install on Windows? Is there a better way?

答:
For the latest Python download - I have Python 3.6 on Windows. You don't have to wonder. Everything you need is there. Take a breath, and I will show you how to do it.

Make sure where you install Python. For me, it was in the following directory

Now, let’s add the Python and pip into environment variable path settings
if you are on Windows, so that typing pip or python anywhere call
python or pip from where they are installed.

So, PIP is found under the folder in the above screen "SCRIPTS"
Let's add Python and PIP in the environment variable path.

Almost done. Let's test with CMD to install the google package using pip.

```<code> pip install google
</code>```

Title: How do I install pip on Windows?

Body:
For the latest Python download - I have Python 3.6 on Windows. You don't have to wonder. Everything you need is there. Take a breath, and I will show you how to do it.

Make sure where you install Python. For me, it was in the following directory

Now, let’s add the Python and pip into environment variable path settings
if you are on Windows, so that typing pip or python anywhere call
python or pip from where they are installed.

So, PIP is found under the folder in the above screen "SCRIPTS"
Let's add Python and PIP in the environment variable path.

Almost done. Let's test with CMD to install the google package using pip.

 pip install google


问:
How to change button color when radio input is selected, but input is wrapped in div before label?
I am trying to make our dinky radio buttons into lovely toggle buttons on our donation page. The HTML cannot be modified, and as it stands the inputs are wrapped in divs, then followed by the labels. I have zero knowledge of JS/jQuery and I imagine this task requires some.

Here is my fiddle: https://jsfiddle.net/cgz63qhd/

body {
  padding: 10px;
  font-family: sans-serif;
}

div.donation-levels {
  margin: 3px 0;
}

.donation-level-container {
  display: inline-block;
}

.donation-level-container input {
  visibility: hidden;
}

.donation-level-amount-container {
  text-align: center;
  margin: 5px 2px;
  padding: 0.7em 2em;
  color: #ffffff;
  background-color: #1a92b4;
  border-radius: 5px;
  display: inline-block;
  cursor: pointer;
  font-size: 22px;
}

.donation-level-amount-container:hover {
  background: #e8525f;
  color: #ffffff;
}

.donation-level-label-input-container input:checked~label {
  background: #e8525f;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="donation-level-container">
  <div class="form-content">

    <div class="donation-level-input-container form-input">

      <div class="donation-level-label-input-container">
        <input name="level_flexibleexpanded" id="level_flexibleexpanded5942" value="5942" onclick="evalMatchingGift('$35.00');" type="radio">
      </div>

      <label for="level_flexibleexpanded5942" onclick="">

    <div class="donation-level-amount-container">
    $35.00
    </div>

    </label>

    </div>

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5942expandedsubmit" value="true" type="hidden">
  </div>
</div>
<div class="donation-level-container">
  <div class="form-content">

    <div class="donation-level-input-container form-input">

      <div class="donation-level-label-input-container">
        <input name="level_flexibleexpanded" id="level_flexibleexpanded5943" value="5943" onclick="evalMatchingGift('$60.00');" type="radio">
      </div>

      <label for="level_flexibleexpanded5943" onclick="">

    <div class="donation-level-amount-container">
    $60.00
    </div>

    </label>

    </div>

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5943expandedsubmit" value="true" type="hidden">
  </div>
</div>
<div class="donation-level-container">
  <div class="form-content">

    <div class="donation-level-input-container form-input">

      <div class="donation-level-label-input-container">
        <input name="level_flexibleexpanded" id="level_flexibleexpanded5944" value="5944" onclick="evalMatchingGift('$120.00');" type="radio">
      </div>

      <label for="level_flexibleexpanded5944" onclick="">

    <div class="donation-level-amount-container">
    $120.00
    </div>

    </label>

    </div>

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5944expandedsubmit" value="true" type="hidden">
  </div>
</div></code>```

Here is my inspiration donate page: https://action.audubon.org/donate/now

Alas, their labels are set up better so I think they were able to make the buttons with pure CSS (?).

My buttons currently are looking decent, are sized fine and colored nicely, but they just won't stay that coral color when clicked! Can someone help me out?

I've seen a lot of questions here on this topic but I can't seem to get anything to work.

I'm sure there are other issues in the code, please point them out if you see them!

答:
You need this

```<code>$(".donation-level-amount-container").on("click", function() {
    $(".donation-level-amount-container").css("background", "#1a92b4");
    $(this).css("background", "#e8525f");
})
</code>```

and css !important for background property

```<code>.donation-level-amount-container:hover {
    background:#e8525f!important;
    color:#ffffff;
}
</code>```

here's your updated fiddle https://jsfiddle.net/cgz63qhd/3/

Body:
I am trying to make our dinky radio buttons into lovely toggle buttons on our donation page. The HTML cannot be modified, and as it stands the inputs are wrapped in divs, then followed by the labels. I have zero knowledge of JS/jQuery and I imagine this task requires some.

Here is my fiddle: https://jsfiddle.net/cgz63qhd/

body {
  padding: 10px;
  font-family: sans-serif;
}

div.donation-levels {
  margin: 3px 0;
}

.donation-level-container {
  display: inline-block;
}

.donation-level-container input {
  visibility: hidden;
}

.donation-level-amount-container {
  text-align: center;
  margin: 5px 2px;
  padding: 0.7em 2em;
  color: #ffffff;
  background-color: #1a92b4;
  border-radius: 5px;
  display: inline-block;
  cursor: pointer;
  font-size: 22px;
}

.donation-level-amount-container:hover {
  background: #e8525f;
  color: #ffffff;
}

.donation-level-label-input-container input:checked~label {
  background: #e8525f;
}

        <input name="level_flexibleexpanded" id="level_flexibleexpanded5942" value="5942" onclick="evalMatchingGift('$35.00');" type="radio">

    $35.00

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5942expandedsubmit" value="true" type="hidden">

        <input name="level_flexibleexpanded" id="level_flexibleexpanded5943" value="5943" onclick="evalMatchingGift('$60.00');" type="radio">

    $60.00

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5943expandedsubmit" value="true" type="hidden">

        <input name="level_flexibleexpanded" id="level_flexibleexpanded5944" value="5944" onclick="evalMatchingGift('$120.00');" type="radio">

    $120.00

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5944expandedsubmit" value="true" type="hidden">

Here is my inspiration donate page: https://action.audubon.org/donate/now

Alas, their labels are set up better so I think they were able to make the buttons with pure CSS (?).

My buttons currently are looking decent, are sized fine and colored nicely, but they just won't stay that coral color when clicked! Can someone help me out?

I've seen a lot of questions here on this topic but I can't seem to get anything to work.

I'm sure there are other issues in the code, please point them out if you see them!

Body:
You need this

$(".donation-level-amount-container").on("click", function() {
    $(".donation-level-amount-container").css("background", "#1a92b4");
    $(this).css("background", "#e8525f");
})

and css !important for background property

.donation-level-amount-container:hover {
    background:#e8525f!important;
    color:#ffffff;
}

here's your updated fiddle https://jsfiddle.net/cgz63qhd/3/


问:
Hide component when certain component shown (with react router)
I have render function below.

```<code>class App extends Component {
    render() {
        return (
            <Router>
                <div>
                    <Header/>
                    <Switch>
                        <Route exact path="/" component={TestApp}/>
                        <Route exact path="/chat" component={ChahtView1}/>
                        <Route exact path="/chat/invite" component={ChatView2}/>
                        <Route exact path="/chat/chatting" component={ChatView3}/>
                        <Route component={NotFound}/>
                    </Switch>
                </div>
            </Router>
        );
    }
 }
</code>```

In this condition, every page shows Header component. What I want to do is to hide Header when NotFound component appears.

How can I do this? Help me please!

Thanks.

答:
I have the same issue.
The only way I found is changing component's state from child component and displaying  upon its state.

So, first I've added showHeader state and function which will false this state, pass this func to <NotFound />:

```<code>class App extends Component {

  constructor (props) {
    super(props)
    this.state = {
      showHeader: true
    }
  }

  hideNavigation = () => {
    this.setState({
      showHeader: false
    })
  }

  render() {
    return (
      <Router>
        <div>
          {this.state.showHeader && <Header/>}

          <Switch>
            <Route exact path="/" component={TestApp}/>

            <Route render={ (props) => (
                <NotFound
                    hideNavigation={this.hideNavigation}
                    {...props}
                />
              )}
            />
          </Switch>
        </div>
      </Router>
    );
  }
}
</code>```

And then calling hideNavigation() from <NotFound /> component:

```<code>class NotFound extends Component {

  componentWillMount () {
    this.props.hideNavigation()
  }

  render() {
    return (
      <div>
          <h1>Ooops!</h1>
      </div>
    );
  }
}
</code>```

Body:
I have render function below.

class App extends Component {
    render() {
        return (
            <Router>

                    <Switch>
                        <Route exact path="/" component={TestApp}/>
                        <Route exact path="/chat" component={ChahtView1}/>
                        <Route exact path="/chat/invite" component={ChatView2}/>
                        <Route exact path="/chat/chatting" component={ChatView3}/>
                        <Route component={NotFound}/>
                    </Switch>

            </Router>
        );
    }
 }

In this condition, every page shows Header component. What I want to do is to hide Header when NotFound component appears.

How can I do this? Help me please!

Thanks.

Body:
I have the same issue.
The only way I found is changing component's state from child component and displaying <Header /> upon its state.

So, first I've added showHeader state and function which will false this state, pass this func to <NotFound />:

class App extends Component {

  constructor (props) {
    super(props)
    this.state = {
      showHeader: true
    }
  }

  hideNavigation = () => {
    this.setState({
      showHeader: false
    })
  }

  render() {
    return (
      <Router>
        <div>
          {this.state.showHeader && <Header/>}

          <Switch>
            <Route exact path="/" component={TestApp}/>

            <Route render={ (props) => (
                <NotFound
                    hideNavigation={this.hideNavigation}
                    {...props}
                />
              )}
            />
          </Switch>
        </div>
      </Router>
    );
  }
}

And then calling hideNavigation() from <NotFound /> component:

class NotFound extends Component {

  componentWillMount () {
    this.props.hideNavigation()
  }

  render() {
    return (
      <div>
          <h1>Ooops!</h1>
      </div>
    );
  }
}


问:
How can I see a unified log of changes to a set of files in perforce?
I'm new to perforce, coming from a history of cvs->svn->git.  I'm having a difficult time seeing a compact representation of the most recent changes impacting a set of file.  For instance, if I go to a directory and type:

```<code>% p4 filelog .
</code>```

It doesn't do anything useful.  More interesting is

```<code>% p4 filelog *
</code>```

However this shows me the change history of every file individually.  I'd rather see a unified view of changes in a format showing: change number, submit message, changed files for the most recent N submits.

答:
You can almost get this with:

```<code>p4 changes -lt [file[RevRange]...]
</code>```

This will show you the changelists that affected the files in question. It doesn't show which files were affected by each change, however. You could write a script that took the output of p4 changes and used p4 describe -s to get the file listing for each changelist.

Note that p4 changes includes pending changes by default. Add -s submitted for only submitted changelists. There are other flags to narrow it down further, like -u username and -m max (to limit the number of changelists returned -- it returns newest first).

Body:
I'm new to perforce, coming from a history of cvs->svn->git.  I'm having a difficult time seeing a compact representation of the most recent changes impacting a set of file.  For instance, if I go to a directory and type:

% p4 filelog .

It doesn't do anything useful.  More interesting is

% p4 filelog *

However this shows me the change history of every file individually.  I'd rather see a unified view of changes in a format showing: change number, submit message, changed files for the most recent N submits.

Body:
You can almost get this with:

p4 changes -lt [file[RevRange]...]

This will show you the changelists that affected the files in question. It doesn't show which files were affected by each change, however. You could write a script that took the output of p4 changes and used p4 describe -s to get the file listing for each changelist.

Note that p4 changes includes pending changes by default. Add -s submitted for only submitted changelists. There are other flags to narrow it down further, like -u username and -m max (to limit the number of changelists returned -- it returns newest first).


问:
Some puzzles for the operator Parallelism in Flink
I just got the example below for the parallelism and have some related questions:

The setParallelism(5) is setting the Parallelism 5 just to sum or both flatMap and sum?

Is it possible that we can set the different Parallelism to different operators such as flatMap and sum respectively ?such as set Parallelism 5 to sum and 10 to flatMap .

Based on my understanding ,keyBy is partitioning the DataStream to logical Stream\partitions based on the different keys, and suppose there are 10,000 different key values, so there are 10,000 different partitions , then how many threads would deal with the 10,000 partitions? Just 5 threads? How about if we didn't set the  setParallelism(5) ?

https://ci.apache.org/projects/flink/flink-docs-release-1.3/dev/parallel.html

final StreamExecutionEnvironment env =
  StreamExecutionEnvironment.getExecutionEnvironment();

DataStream<String> text = [...]
DataStream<Tuple2<String, Integer>> wordCounts = text
  .flatMap(new LineSplitter())
  .keyBy(0)
  .timeWindow(Time.seconds(5))
  .sum(1).setParallelism(5);

wordCounts.print();

env.execute("Word Count Example");
```

答:
When calling setParallelism on an operator, then it changes the parallelism of this specific operator. Consequently, in your example, only the window operator will be executed with a parallelism of 5 and the preceding flatMap operator with the default parallelism.

Consequently, you can set for each operator a different parallelism. However, be aware that operators with different parallelism cannot be chained and entail a rebalance (similar to a shuffle) operation.

If you want to set the parallelism for all operators, then you have to do it via the ExecutionEnvironment#setParallelism API call.

The keyBy operation partitions in the input stream into as many partitions as you have parallel operator instances. This makes sure that all elements with the same key end up in the same partition. So in your example where you set the parallelism to 5, you would end up with 5 partitions. Each partition can harbour elements with different keys.


问:
DatePicker in xaml.vb
I am completely new to XAML.vb. when I want to calculate the age in .cs, I used to enter the following code:

```<code>private void dateTimePicker1_valueChanged (object sender, EventArgs e)
{
DateTime from = dateTimePicker1.Value;
DateTime  to = dateTimePicker1.Now;
TimeSpan Tspan = to-from;
double days = Tspan.TotalDays;
textbox1.Text = (days/365)ToString("0");
}
</code>```

The following code is from XAML.VB. All the functions that I used in cs before are not present.

```<code>Private Sub dob_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

{

DateTime from = dob.Value;  // it doesn't exist. I found dob.GetValue but its not helping.

}
</code>```

Same was with "TimeSpan" and all the other built-in functions from Microsoft they have changed it so much and much is not available on the internet. It would be great if someone has any idea about it.
Thanks

答:
DateTimePicker is a WindowsForms control. In WPF the control is called DatePicker and it has a SelectedDate property that returns a Nullable(Of DateTime).

Try this.

XAML:

```<code><DatePicker x:Name="dob" SelectedDateChanged="dob_SelectedDateChanged" />
<TextBox x:Name="textBox1" />
</code>```

VB.NET:

```<code>Private Sub dob_SelectedDateChanged(sender As Object, e As SelectionChangedEventArgs)
    Dim fromDate = dob.SelectedDate.Value
    Dim toDate = DateTime.Now
    Dim tspan = toDate - fromDate
    Dim days = tspan.TotalDays
    textBox1.Text = days.ToString
End Sub
</code>```

Title: DatePicker in xaml.vb

Body:
I am completely new to XAML.vb. when I want to calculate the age in .cs, I used to enter the following code:

private void dateTimePicker1_valueChanged (object sender, EventArgs e)
{
DateTime from = dateTimePicker1.Value;
DateTime  to = dateTimePicker1.Now;
TimeSpan Tspan = to-from;
double days = Tspan.TotalDays;
textbox1.Text = (days/365)ToString("0");
}

The following code is from XAML.VB. All the functions that I used in cs before are not present.

Private Sub dob_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

{

DateTime from = dob.Value;  // it doesn't exist. I found dob.GetValue but its not helping.

}

Same was with "TimeSpan" and all the other built-in functions from Microsoft they have changed it so much and much is not available on the internet. It would be great if someone has any idea about it.
Thanks

Body:
DateTimePicker is a WindowsForms control. In WPF the control is called DatePicker and it has a SelectedDate property that returns a Nullable(Of DateTime).

Try this.

XAML:

<DatePicker x:Name="dob" SelectedDateChanged="dob_SelectedDateChanged" />
<TextBox x:Name="textBox1" />

VB.NET:

Private Sub dob_SelectedDateChanged(sender As Object, e As SelectionChangedEventArgs)
    Dim fromDate = dob.SelectedDate.Value
    Dim toDate = DateTime.Now
    Dim tspan = toDate - fromDate
    Dim days = tspan.TotalDays
    textBox1.Text = days.ToString
End Sub


问:
Python Opencv imshow error
my code:

```<code>import cv2
img = cv2.imread("dU4fHDw-Ho.jpg", cv2.IMREAD_GRAYSCALE)

cv2.imshow('image', img)
k = cv2.waitKey(0)
if k == 27:
    cv2.destroyWindow()
</code>```

And i get this error:

```<code>OpenCV Error: Unspecified error (The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Carbon support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script) in cvShowImage, file /io/opencv/modules/highgui/src/window.cpp, line 583
Traceback (most recent call last):
  File "simpleopencv.py", line 4, in <module>
    cv2.imshow('image', img)
cv2.error: /io/opencv/modules/highgui/src/window.cpp:583: error: (-2) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Carbon support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function cvShowImage
</code>```

I'm using linux mint KDE
What might be the problem?

Update1: Opencv works fine with python2.7 but not working for python3.5

Update2: As it turns out running the script as Jack Gold suggested actually worked but since i already had cv2 folder in my /usr/local/lib/python3.5/dist-packages/ (which was installed using PIP i think) conflicted with the one install using the script and python3 kept using the PIP version so, I deleted that cv2 folder and restarted and everything worked fine.

答: Not sure about the problem since it works fine for me. But just as an alternative, use plt.imshow() from Matplotlib, it also works fine.</p>

Title: Python Opencv imshow error

Body:
my code:

import cv2
img = cv2.imread("dU4fHDw-Ho.jpg", cv2.IMREAD_GRAYSCALE)

cv2.imshow('image', img)
k = cv2.waitKey(0)
if k == 27:
    cv2.destroyWindow()

And i get this error:

OpenCV Error: Unspecified error (The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Carbon support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script) in cvShowImage, file /io/opencv/modules/highgui/src/window.cpp, line 583
Traceback (most recent call last):
  File "simpleopencv.py", line 4, in <module>
    cv2.imshow('image', img)
cv2.error: /io/opencv/modules/highgui/src/window.cpp:583: error: (-2) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Carbon support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function cvShowImage

I'm using linux mint KDE
What might be the problem?

Update1: Opencv works fine with python2.7 but not working for python3.5

Update2: As it turns out running the script as Jack Gold suggested actually worked but since i already had cv2 folder in my /usr/local/lib/python3.5/dist-packages/ (which was installed using PIP i think) conflicted with the one install using the script and python3 kept using the PIP version so, I deleted that cv2 folder and restarted and everything worked fine.


问:
How do I check if a string contains any characters from a given set of characters represented in another string?
How do I check if a list of characters are in a String, for example "ABCDEFGH" how do I check if any one of those is in a string.</p>

答:
From Guava: CharMatcher.matchesAnyOf</p>

```<code>private static final CharMatcher CHARACTERS = CharMatcher.anyOf("ABCDEFGH");
assertTrue(CHARACTERS.matchesAnyOf("39823839A983923"));
</code>```

Body:
From Guava: CharMatcher.matchesAnyOf

private static final CharMatcher CHARACTERS = CharMatcher.anyOf("ABCDEFGH");
assertTrue(CHARACTERS.matchesAnyOf("39823839A983923"));


问:
Join row with specified field value and highest value in other field
I have 2 tables:

Articles:

ID INTEGER

...

Article_versions:

article INTEGER

lang ENUM

time TIMESTAMP

PRIMARY KEY( article,lang,time )

...

I want to select fields from Articles and fields from related latest row Article_versions.
Should i use join or 2 select statements?

And how can i do this?

答:
It is confusing exactly what information you are trying to retrieve but if you know a particular ID then you can use:

```<code>SELECT ID,lang,time
FROM articles,article_versions
WHERE articles.ID=<article_id_you_provide> AND
      articles.ID=article_versions.article AND
      article_versions.time = (SELECT max(time)
                               FROM article_versions
                               WHERE article=<article_id_you_provide>);
</code>```

Let me know if this isn't what you are looking for and I can revise my answer further.

Body:
It is confusing exactly what information you are trying to retrieve but if you know a particular ID then you can use:

SELECT ID,lang,time
FROM articles,article_versions
WHERE articles.ID=<article_id_you_provide> AND
      articles.ID=article_versions.article AND
      article_versions.time = (SELECT max(time)
                               FROM article_versions
                               WHERE article=<article_id_you_provide>);

Let me know if this isn't what you are looking for and I can revise my answer further.


问:
no libopencv_core.so in java.library.path hadoop
I was working in hadoop and suddenly once i created runnable jar for my image processing program this error occured it has relation with opencv native library path

while using eclipse the path i can set using :

// System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

But while executing runnable jar using hadoop it gives error.
Anyone who can rectify ?

```<code>    hduser@master:/home/mnh/Desktop$ hadoop jar  opencv19.jar /usr/local/hadoop/input/cars.mp4 /usr/local/hadoop/cars89
17/06/07 16:15:37 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/06/07 16:15:39 INFO client.RMProxy: Connecting to ResourceManager at master/192.168.137.52:8050
17/06/07 16:15:40 WARN mapreduce.JobSubmitter: Hadoop command-line option parsing not performed. Implement the Tool interface and execute your application with ToolRunner to remedy this.
17/06/07 16:16:08 INFO input.FileInputFormat: Total input paths to process : 1
17/06/07 16:16:08 INFO mapreduce.JobSubmitter: number of splits:1
17/06/07 16:16:09 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1496831815466_0009
17/06/07 16:16:09 INFO impl.YarnClientImpl: Submitted application application_1496831815466_0009
17/06/07 16:16:09 INFO mapreduce.Job: The url to track the job: http://master:8088/proxy/application_1496831815466_0009/
17/06/07 16:16:09 INFO mapreduce.Job: Running job: job_1496831815466_0009
17/06/07 16:16:20 INFO mapreduce.Job: Job job_1496831815466_0009 running in uber mode : false
17/06/07 16:16:20 INFO mapreduce.Job:  map 0% reduce 0%
17/06/07 16:16:29 INFO mapreduce.Job: Task Id : attempt_1496831815466_0009_m_000000_0, Status : FAILED
Error: no libopencv_core.so in java.library.path
17/06/07 16:16:37 INFO mapreduce.Job: Task Id : attempt_1496831815466_0009_m_000000_1, Status : FAILED
Error: no libopencv_core.so in java.library.path
17/06/07 16:16:45 INFO mapreduce.Job: Task Id : attempt_1496831815466_0009_m_000000_2, Status : FAILED
Error: no libopencv_core.so in java.library.path
17/06/07 16:16:54 INFO mapreduce.Job:  map 100% reduce 100%
17/06/07 16:16:55 INFO mapreduce.Job: Job job_1496831815466_0009 failed with state FAILED due to: Task failed task_1496831815466_0009_m_000000
Job failed as tasks failed. failedMaps:1 failedReduces:0

17/06/07 16:16:56 INFO mapreduce.Job: Counters: 12
    Job Counters
        Failed map tasks=4
        Launched map tasks=4
        Other local map tasks=3
        Data-local map tasks=1
        Total time spent by all maps in occupied slots (ms)=26582
        Total time spent by all reduces in occupied slots (ms)=0
        Total time spent by all map tasks (ms)=26582
        Total vcore-seconds taken by all map tasks=26582
        Total megabyte-seconds taken by all map tasks=27219968
    Map-Reduce Framework
        CPU time spent (ms)=0
        Physical memory (bytes) snapshot=0
        Virtual memory (bytes) snapshot=0
</code>```

答: The error message you are getting is related with the workers not being able to use OpenCV, because it is not installed on the respective machines. So the solution would be installing OpenCV on the cluster machines which have the Nodemanager component installed (those which will be executing the tasks). To be able to load the library using System.loadLibrary() method, you would need to add the location of the so file to the PATH system variable.

Body:
I was working in hadoop and suddenly once i created runnable jar for my image processing program this error occured it has relation with opencv native library path

while using eclipse the path i can set using :

// System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

But while executing runnable jar using hadoop it gives error.
Anyone who can rectify ?

    hduser@master:/home/mnh/Desktop$ hadoop jar  opencv19.jar /usr/local/hadoop/input/cars.mp4 /usr/local/hadoop/cars89
17/06/07 16:15:37 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/06/07 16:15:39 INFO client.RMProxy: Connecting to ResourceManager at master/192.168.137.52:8050
17/06/07 16:15:40 WARN mapreduce.JobSubmitter: Hadoop command-line option parsing not performed. Implement the Tool interface and execute your application with ToolRunner to remedy this.
17/06/07 16:16:08 INFO input.FileInputFormat: Total input paths to process : 1
17/06/07 16:16:08 INFO mapreduce.JobSubmitter: number of splits:1
17/06/07 16:16:09 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1496831815466_0009
17/06/07 16:16:09 INFO impl.YarnClientImpl: Submitted application application_1496831815466_0009
17/06/07 16:16:09 INFO mapreduce.Job: The url to track the job: http://master:8088/proxy/application_1496831815466_0009/
17/06/07 16:16:09 INFO mapreduce.Job: Running job: job_1496831815466_0009
17/06/07 16:16:20 INFO mapreduce.Job: Job job_1496831815466_0009 running in uber mode : false
17/06/07 16:16:20 INFO mapreduce.Job:  map 0% reduce 0%
17/06/07 16:16:29 INFO mapreduce.Job: Task Id : attempt_1496831815466_0009_m_000000_0, Status : FAILED
Error: no libopencv_core.so in java.library.path
17/06/07 16:16:37 INFO mapreduce.Job: Task Id : attempt_1496831815466_0009_m_000000_1, Status : FAILED
Error: no libopencv_core.so in java.library.path
17/06/07 16:16:45 INFO mapreduce.Job: Task Id : attempt_1496831815466_0009_m_000000_2, Status : FAILED
Error: no libopencv_core.so in java.library.path
17/06/07 16:16:54 INFO mapreduce.Job:  map 100% reduce 100%
17/06/07 16:16:55 INFO mapreduce.Job: Job job_1496831815466_0009 failed with state FAILED due to: Task failed task_1496831815466_0009_m_000000
Job failed as tasks failed. failedMaps:1 failedReduces:0

17/06/07 16:16:56 INFO mapreduce.Job: Counters: 12
    Job Counters
        Failed map tasks=4
        Launched map tasks=4
        Other local map tasks=3
        Data-local map tasks=1
        Total time spent by all maps in occupied slots (ms)=26582
        Total time spent by all reduces in occupied slots (ms)=0
        Total time spent by all map tasks (ms)=26582
        Total vcore-seconds taken by all map tasks=26582
        Total megabyte-seconds taken by all map tasks=27219968
    Map-Reduce Framework
        CPU time spent (ms)=0
        Physical memory (bytes) snapshot=0
        Virtual memory (bytes) snapshot=0


问:
Writing to output window of Visual Studio
I am trying to write a message to the output window for debugging purposes. I searched for a function like Java's system.out.println(""). I tried Debug.Write, Console.Write, and Trace.Write. It does not give an error, but it does not print anything either.

"Define DEBUG constant" and "Define TRACE constant" options are checked.

Menu Tools → Options → Debugging → "Redirect all Output Window text to the Immediate Window" option is not checked.

Configuration: Active (Debug)

Note: I created a project with the wizard as "Windows Forms Application" if relevant. I have no idea where to look.

答:
This is not an answer to the original question. But since I found this question when searching for a means of interactively dumping object data, I figured others may benefit from mentioning this very useful alternative.

I ultimately used the Command Window and entered the Debug.Print command, as shown below. This printed a memory object in a format that can be copied as text, which is all I really needed.

```<code>> Debug.Print <item>

  id: 1
  idt: null
  igad: 99
  igbd: 99
  gl_desc: "New #20"
  te_num: "1-001-001-020"
</code>```

Body:
This is not an answer to the original question. But since I found this question when searching for a means of interactively dumping object data, I figured others may benefit from mentioning this very useful alternative.

I ultimately used the Command Window and entered the Debug.Print command, as shown below. This printed a memory object in a format that can be copied as text, which is all I really needed.

> Debug.Print <item>

  id: 1
  idt: null
  igad: 99
  igbd: 99
  gl_desc: "New #20"
  te_num: "1-001-001-020"