问:
Native promises vs. Bluebird promises
Is there a way in Node.js to check to determine if global.Promise is the native promise implementation? As opposed to Bluebird promises, etc?

答:
You could do a feature test and test to see if any of the Bluebird extended features are present:

```<code>function testBluebird() {
   // test to see if a representative sample of Bluebird-specific features are present
   return Promise && Promise.join && Promise.try && Promise.method && Promise.map;
}
</code>```

Like with many things in Javascript, you should probably just test to see if the features you want to use are present rather than trying to determine if a specific library is loaded.

Title: Native promises vs. Bluebird promises

Body:
You could do a feature test and test to see if any of the Bluebird extended features are present:

function testBluebird() {
   // test to see if a representative sample of Bluebird-specific features are present
   return Promise && Promise.join && Promise.try && Promise.method && Promise.map;
}

Like with many things in Javascript, you should probably just test to see if the features you want to use are present rather than trying to determine if a specific library is loaded.


来源: stackexchange

问:
replace sed command text inline
I have this file

file.txt

```<code>unknown@mail.com||unknown@mail.com||
unknown@mail2.com||unknown@mail2.com||
unknown@mail3.com||unknown@mail3.com||
unknown@mail4.com||unknown@mail4.com||
unknownpass
unknownpass2
unknownpass3
unknownpass4
</code>```

How can I use the sed command to obtain this:

```<code>unknown@mail.com|unknownpass|unknown@mail.com|unknownpass|
unknown@mail2.com|unknownpass2|unknown@mail2.com|unknownpass2|
unknown@mail3.com|unknownpass3|unknown@mail3.com|unknownpass3|
unknown@mail4.com|unknownpass4|unknown@mail4.com|unknownpass4|
</code>```

答:
Well, this does use sed anyway:

```<code>{ sed -n 5,\$p file.txt; sed 4q file.txt; }  | awk 'NR<5{a[NR]=$0; next}
        {$2=a[NR-4]; $4=a[NR-4]} 1' FS=\| OFS=\|
</code>```

ContentLicense: CC BY-SA 3.0

Title: replace sed command text inline

Body:
I have this file

file.txt

unknown@mail.com||unknown@mail.com||
unknown@mail2.com||unknown@mail2.com||
unknown@mail3.com||unknown@mail3.com||
unknown@mail4.com||unknown@mail4.com||
unknownpass
unknownpass2
unknownpass3
unknownpass4

How can I use the sed command to obtain this:

unknown@mail.com|unknownpass|unknown@mail.com|unknownpass|
unknown@mail2.com|unknownpass2|unknown@mail2.com|unknownpass2|
unknown@mail3.com|unknownpass3|unknown@mail3.com|unknownpass3|
unknown@mail4.com|unknownpass4|unknown@mail4.com|unknownpass4|

Body:
Well, this does use sed anyway:

{ sed -n 5,\$p file.txt; sed 4q file.txt; }  | awk 'NR<5{a[NR]=$0; next}
        {$2=a[NR-4]; $4=a[NR-4]} 1' FS=\| OFS=\|


问:
How to put HashMap into different elements with same key
This is my output which contains three HashMap.

```<code>{2017-03-11=1, 2017-03-05=6}
{2017-03-11=1, 2017-03-05=5}
{2017-03-05=1}
</code>```

i want them to look like this

```<code>date:2017-03-11
c=1, d=1, e=0

date:2017-03-05
c=6, d=5, e=1
</code>```

答:
I believe you may be looking for the MultiHashMap from the Apache Commons Collections

Here's the example from the documentation:

```<code>MultiMap mhm = new MultiHashMap();
mhm.put(key, "A");
mhm.put(key, "B");
mhm.put(key, "C");
List list = (List) mhm.get(key);
</code>```

Body:
This is my output which contains three HashMap.

{2017-03-11=1, 2017-03-05=6}
{2017-03-11=1, 2017-03-05=5}
{2017-03-05=1}

i want them to look like this

date:2017-03-11
c=1, d=1, e=0

date:2017-03-05
c=6, d=5, e=1

Body:
I believe you may be looking for the MultiHashMap from the Apache Commons Collections

Here's the example from the documentation:

MultiMap mhm = new MultiHashMap();
mhm.put(key, "A");
mhm.put(key, "B");
mhm.put(key, "C");
List list = (List) mhm.get(key);


问:
Where is Smalltalk-80 best used?
I want to know in which applications/programming domain are most suitable for Smalltalk. Could anyone please provide me some useful links that could answer my query?

Through googling I learned that some companies use it for:

logistics and foreign trade application

desktop, server and script development

data processing and logistics, scripts and presentations

but I cant find documents/research papers that can tell me which programming domain Smalltalk-80 (or Smalltalk) is best suited.

Some of the programming domains are:
 - Artificial intelligence reasoning
 - General purpose applications
 - Financial time series analysis
 - Natural language processing
 - Relational database querying
 - Application scripting
 - Internet
 - Symbolic mathematics
 - Numerical mathematics
 - Statistical applications
 - Text processing
 - Matrix algorithms

I hope you guys can help me. I am doing this for my case study. Thanks in advance.

答:
My goal has been to do a brain dump into software. And I have found Smalltalk to be very well suited for that. Smalltalk makes it easy to put my ideas down in code. And it provides feedback to my thinking. The ability to debug infinitely deep at any point in the execution just enhances my understand of the problem to be solved. Then it allows me to carry out my solution most naturally.

Aik-Siong Koh

ContentLicense: CC BY-SA 2.5

Title: Where is Smalltalk-80 best used?


问:
Gap above ContentView / not the same height as UIScrollview - xib
Issue: gap above where contentView starts.  Should be 0.

Despite setting the content view top bottom leading and trailing to 0, the content view has a gap at the top.  I am using auto layout only.

Scrollview background is blue &

Content view is grey for easy viewing.

If I set the content view to equal heights as the scroll view, I get an error.  And this doesn't seem like the right approach away.  According to this setting equal height is optional:

Apple auto layout scrollview page

I do set equal widths.

Entire Screen:

Top of Scroll view:

Bottom of scroll view -> this is right - flush with bottom of scroll view (not sure if that matters)

Constraints:

Subview constraints:

Please help!!  Also I am using xib files - not sure if that matters.

Thank you!

答:
You'll notice that the gap is equal in height to the navigation bar.

The gap is there because by default iOS assumes that when using a translucent navigation bar, scroll views (and their subclasses like table views) begin at the top of the screen, behind the translucent navigation bar.

iOS then assumes you do not want your content hidden behind the translucent navigation bar, so it applies a top content inset to any scroll view, of height equal to the navigation bar height.

This behavior can be overridden in two ways:

Unmark Adjust Scroll View Insets on the view controller (see image below)

Make your navigation bar not translucent. If you're using a Storyboard, select the navigation controller that contains the affected view controller, and unmark the Translucent checkbox.


问:
Chrome mousedown and mouseup events no longer working, other browsers are fine
As of today (or yesterday, didn't notice it then), mousedown and mouseup events are no longer working. I am on Chrome Version 55.0.2883.95 (64-bit). Safari and FireFox are working fine (I am on a mac computer).

Here is the code:

```<code>document.getElementById("floorplan-backdrop-rect").addEventListener('mousedown', function(ev) {
    o.clickDown(ev);
}, false);

document.getElementById("floorplan-backdrop-rect").addEventListener('mouseup', function(ev) {
    o.clickUp(ev);
}, false);
</code>```

Were there any API changes regarding mouse-events that we missed? Chrome does not throw any warning when registering the events either. Touchdown and touch up event seem to fail too (in emulated iPad mode in developer tools)

EDIT: Right after changing tab, or when resizing the window, the events seem to come through for a short while. Then they stop again..

Regards

答:
To add to @WouterCoebergh solution. You must remember to add a fallback for the old event. This can be done by the following, taken from the same[1] source.

```<code>var mousedownEvent = function(ev) {
  o.clickDown(ev);
}

var elm = document.getElementById("floorplan-backdrop-rect");

if (window.PointerEvent) {
  elm.addEventListener('pointerdown', mousedownEvent);
} else {
  elm.addEventListener('mousedown', mousedownEvent);
}
</code>```

[1]: Google Developers Blog

Body:
As of today (or yesterday, didn't notice it then), mousedown and mouseup events are no longer working. I am on Chrome Version 55.0.2883.95 (64-bit). Safari and FireFox are working fine (I am on a mac computer).

Here is the code:

document.getElementById("floorplan-backdrop-rect").addEventListener('mousedown', function(ev) {
    o.clickDown(ev);
}, false);

document.getElementById("floorplan-backdrop-rect").addEventListener('mouseup', function(ev) {
    o.clickUp(ev);
}, false);

Were there any API changes regarding mouse-events that we missed? Chrome does not throw any warning when registering the events either. Touchdown and touch up event seem to fail too (in emulated iPad mode in developer tools)

EDIT: Right after changing tab, or when resizing the window, the events seem to come through for a short while. Then they stop again..

Regards

Body:
To add to @WouterCoebergh solution. You must remember to add a fallback for the old event. This can be done by the following, taken from the same[1] source.

var mousedownEvent = function(ev) {
  o.clickDown(ev);
}

var elm = document.getElementById("floorplan-backdrop-rect");

if (window.PointerEvent) {
  elm.addEventListener('pointerdown', mousedownEvent);
} else {
  elm.addEventListener('mousedown', mousedownEvent);
}

[1]: Google Developers Blog


问:
Use <canvas> as a CSS background
Can I use the canvas element as a css background?</p>

答:
You can emulate this behavior quickly without the performance drop of toDataURL() using z-index (granted, it's a workaround, since CSS images 4 / CSS Houdini hasn't implemented "background: element(#mycanvas)" as of 2017))

Working JSFiddle here. I didn't write this, all credit goes to Derek Leung:

http://jsfiddle.net/DerekL/uw5XU/

Title: Use <canvas> as a CSS background


问:
CSS/HTML fit any resolution
I am relatively new to the css/html world. I am trying to create a website. I noticed though that even though everything looks great on my screen when i try to view it on lower resolution screens everything is messed up. Is there a way to make it display correctly through css?

Here is an image of what i'm trying to achieve and make it possible for lower resolutions as well: image
here is my css so far (the first part is a reseter. i got it as it is from watching a youtube tutorial) :

html,body, div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp, small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, figcaption, figure, footer, header, hgroup, menu, nav, section, summary, time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  outline: 0;
  font-size: 100%;
  vertical-align: baseline;
  background: transparent;
}

body {
  line-height: 1;
}

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}

nav ul {
  list-style: none;
}

blockquote,
q {
  quotes: none;
}

blockquote:before,
blockquote:after,
q:before,
q:after {
  content: '';
  content: none;
}

a {
  margin: 0;
  padding: 0;
  font-size: 100%;
  vertical-align: baseline;
  background: transparent;
}

/* change colours to suit your needs */

ins {
  background-color: #ff9;
  color: #000;
  text-decoration: none;
}

/* change colours to suit your needs */

mark {
  background-color: #ff9;
  color: #000;
  font-style: italic;
  font-weight: bold;
}

del {
  text-decoration: line-through;
}

abbr[title],
dfn[title] {
  border-bottom: 1px dotted;
  cursor: help;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

/* change border colour to suit your needs */

hr {
  display: block;
  height: 1px;
  border: 0;
  border-top: 1px solid #cccccc;
  margin: 1em 0;
  padding: 0;
}

input,
select {
  vertical-align: middle;
}

/*!!!!!END OF RESET!!!!!*/

/*MY CSS*/

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

#logo1 {
  padding-left: 25px;
}

#logo2 {
  padding-left: 260px;
}

#eternal {
  padding-top: 15px;
  display: block;
  position: absolute;
  left: 0;
}

#prwtoetis {
  padding-top: 20px;
  float: right;
  position: absolute;
  bottom: 0%;
  left: 0;
}

#akyri {
  padding-top: 5px;
  display: block;
  position: absolute;
  right: 0%;
}

#akyri2 {
  padding-top: 5px;
  display: block;
  bottom: 0%;
  right: 0%;
  position: absolute;
}

#quote {
  text-align: center;
  padding: 13%;
  font-family: Calibri;
  font-size: 35px;
}

a {
  color: #000;
  text-decoration: none;
}

body {
  background-color: #e1e8ea;
  width: 100%;
  min-width: 600px;
  max-width: 2000px
}

header {
  background-color: #b5c4c9;
  padding-top: 8px;
  padding-bottom: 10px;
  width: 100%;
  height: 159px;
}

header img {
  float: left;
}

nav {
  float: left;
}

nav ul {
  margin-top: 86px;
  margin-left: 200px;
}

nav ul li {
  display: inline-block;
  margin-left: 20px;
}

nav ul li a {
  font-family: Calibri;
  font-size: 22px;
}

a.ex5:hover,
a.ex5:active {
  text-decoration: underline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>RateYourProfessor</title>
  <link rel="stylesheet" type="text/css" href="css/style.css">
</head>

<body>
  <div id="site-wrapper">

    <header>
      <div>
        <img id="logo1" src="images/logo.png">
        <nav>
          <ul>
            <li>HOME</li>
            <li>CREATE PROFESSOR</li>
            <li>RATE PROFESSOR</li>
            <li>SCOREBOARD</li>
            <li>TOP 5</li>
          </ul>
        </nav>
        <img id="logo2" src="images/logo.png">
      </div>
    </header>

    <section>
      <div>
        <img id="eternal" src="images/eternal.png">
        <img id="prwtoetis" src="images/prwtoetis.png">
        <img id="akyri" src="images/akyri.png">
        <img id="akyri2" src="images/akyri2.png">
      </div>
      <div id="quote"><br> There is no end to education. <br>It is not that you read a book, pass an examination, and finish with education. <br>The whole of life, from the moment you are born to the moment you die, is a process of learning.
        <br>- <i>Jiddu Krishnamurti</i>
      </div>
    </section>
  </div>

</body>

</html></code>```

答:
If what you are referring to as "lower resolutions" meaning different screen sizes i.e. mobile, tablet, desktop, or even a smaller window size on the same desktop, then your solution lies with CSS media queries. You appear to have got to grips with the basics of HTML and CSS.

Your next step with CSS should be learning about media queries to shuffle/move content of the page depending on the screen size/resolution.

Bootstrap is great for handling this for you, but if you're new to HTML/CSS you should learn about the code that Bootstrap is built on before using it. Depending on the skill level you want to achieve of course.

W3Schools is excellent for beginners getting to grips with key concepts. Check out their section on media queries:

https://www.w3schools.com/cssref/css3_pr_mediaquery.asp

OR

another great resource is CSS-Tricks. Check out their article:

https://css-tricks.com/css-media-queries/

Last but not least, make sure to include the meta tag:

```<code><meta name="viewport" content="width=device-width, initial-scale=1">
</code>```

This will render the content of the screen at the device screen width and sets the zoom level of the content of the page upon loading. Your won't notice too much different by just throwing in the meta tag above. You need to create some CSS Media Queries first to see the full advantage of this meta tag.

Good luck and have fun!

Title: CSS/HTML fit any resolution

Body:
I am relatively new to the css/html world. I am trying to create a website. I noticed though that even though everything looks great on my screen when i try to view it on lower resolution screens everything is messed up. Is there a way to make it display correctly through css?

Here is an image of what i'm trying to achieve and make it possible for lower resolutions as well: image
here is my css so far (the first part is a reseter. i got it as it is from watching a youtube tutorial) :

html,body, div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp, small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, figcaption, figure, footer, header, hgroup, menu, nav, section, summary, time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  outline: 0;
  font-size: 100%;
  vertical-align: baseline;
  background: transparent;
}

body {
  line-height: 1;
}

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}

nav ul {
  list-style: none;
}

blockquote,
q {
  quotes: none;
}

blockquote:before,
blockquote:after,
q:before,
q:after {
  content: '';
  content: none;
}

a {
  margin: 0;
  padding: 0;
  font-size: 100%;
  vertical-align: baseline;
  background: transparent;
}

/* change colours to suit your needs */

ins {
  background-color: #ff9;
  color: #000;
  text-decoration: none;
}

/* change colours to suit your needs */

mark {
  background-color: #ff9;
  color: #000;
  font-style: italic;
  font-weight: bold;
}

del {
  text-decoration: line-through;
}

abbr[title],
dfn[title] {
  border-bottom: 1px dotted;
  cursor: help;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

/* change border colour to suit your needs */

hr {
  display: block;
  height: 1px;
  border: 0;
  border-top: 1px solid #cccccc;
  margin: 1em 0;
  padding: 0;
}

input,
select {
  vertical-align: middle;
}

/*!!!!!END OF RESET!!!!!*/

/*MY CSS*/

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

#logo1 {
  padding-left: 25px;
}

#logo2 {
  padding-left: 260px;
}

#eternal {
  padding-top: 15px;
  display: block;
  position: absolute;
  left: 0;
}

#prwtoetis {
  padding-top: 20px;
  float: right;
  position: absolute;
  bottom: 0%;
  left: 0;
}

#akyri {
  padding-top: 5px;
  display: block;
  position: absolute;
  right: 0%;
}

#akyri2 {
  padding-top: 5px;
  display: block;
  bottom: 0%;
  right: 0%;
  position: absolute;
}

#quote {
  text-align: center;
  padding: 13%;
  font-family: Calibri;
  font-size: 35px;
}

a {
  color: #000;
  text-decoration: none;
}

body {
  background-color: #e1e8ea;
  width: 100%;
  min-width: 600px;
  max-width: 2000px
}

header {
  background-color: #b5c4c9;
  padding-top: 8px;
  padding-bottom: 10px;
  width: 100%;
  height: 159px;
}

header img {
  float: left;
}

nav {
  float: left;
}

nav ul {
  margin-top: 86px;
  margin-left: 200px;
}

nav ul li {
  display: inline-block;
  margin-left: 20px;
}

nav ul li a {
  font-family: Calibri;
  font-size: 22px;
}

a.ex5:hover,
a.ex5:active {
  text-decoration: underline;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>RateYourProfessor</title>
  <link rel="stylesheet" type="text/css" href="css/style.css">

HOME

CREATE PROFESSOR

RATE PROFESSOR

SCOREBOARD

TOP 5

 There is no end to education.
It is not that you read a book, pass an examination, and finish with education.
The whole of life, from the moment you are born to the moment you die, is a process of learning.

- Jiddu Krishnamurti

Body:
If what you are referring to as "lower resolutions" meaning different screen sizes i.e. mobile, tablet, desktop, or even a smaller window size on the same desktop, then your solution lies with CSS media queries. You appear to have got to grips with the basics of HTML and CSS.

Your next step with CSS should be learning about media queries to shuffle/move content of the page depending on the screen size/resolution.

Bootstrap is great for handling this for you, but if you're new to HTML/CSS you should learn about the code that Bootstrap is built on before using it. Depending on the skill level you want to achieve of course.

W3Schools is excellent for beginners getting to grips with key concepts. Check out their section on media queries:

https://www.w3schools.com/cssref/css3_pr_mediaquery.asp

OR

another great resource is CSS-Tricks. Check out their article:

https://css-tricks.com/css-media-queries/

Last but not least, make sure to include the meta tag:

<meta name="viewport" content="width=device-width, initial-scale=1">

This will render the content of the screen at the device screen width and sets the zoom level of the content of the page upon loading. Your won't notice too much different by just throwing in the meta tag above. You need to create some CSS Media Queries first to see the full advantage of this meta tag.

Good luck and have fun!


答:
You can use split():

```<code>split(test, treatments)
</code>```

res <- split(x, f) divides the data into the groups defined by f into a list.

unsplit(res, f) does the opposite.

Title: subset a data frame by group

Body:
I have a dataframe:

dput(test)
test <- structure(list(Blocking = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 5L,
5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L), Treatment = structure(c(1L,
2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L,
2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L,
2L, 3L, 4L), .Label = c("A", "B", "C", "D"), class = "factor"),
ID69 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), ID70 = c(1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L), ID71 = c(0L, 0L, 1L, 1L, 1L, 0L, 0L, 0L, 0L,
1L, 1L, 0L, 0L, 1L, 1L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L), ID72 = c(0L,
0L, 1L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 1L, 0L), ID73 = c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L),
ID74 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), ID75 = c(0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L), ID77 = c(0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L,
1L, 1L, 1L, 1L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 0L)), .Names = c("Blocking",
"Treatment", "ID69", "ID70", "ID71", "ID72", "ID73", "ID74",
"ID75", "ID77"), class = "data.frame", row.names = c(NA, -36L
))

I would like to split it based on treatment into four data frames. I tried the following code:

 treatments <- c("A", "B", "C", "D")
 subset_list <- lapply(treatments, function(x, input_df = test){
 subset(input_dt, treatment=treatments)
 })

 names(subset_list) <- treatments

I get a list but individual data frames are the full test df's and do not contain rows only corresponding to the treatment. This seems like a really easy question, but I am missing a crucial detail here and I am new to the apply family. Please let me know, thanks!

Body:
You can use split():

split(test, treatments)

res <- split(x, f) divides the data into the groups defined by f into a list.

unsplit(res, f) does the opposite.


问:
How can I automate the process of deploying an InfoPath Form to SharePoint Server 2007?
It is a real pain to deploy my InfoPath 2007 Forms from the designer into our development environment's SharePoint server.  All of our forms require "full trust" since they include business logic written in C#.  Here are the manual steps:

1) Run the "Publish Form" wizard in InfoPath, specifying the target site to publish to and location to save the xsn file.

2) De-activate the existing version of the form from the site collection features (if an older version exists).

3) Log into Central Admin on the development server.  Navigate to Application Management -> Manage Form Templates and upload the xsn file.

4) Activate the form as a site collection feature.

Does anyone have an idea how this can be automated?  Maybe via stsadm?

答:
We can build our own service to deploy the InfoPath form in Share point Server. I have developed the service to solve my problem.
 I have used “STSADM” command to deploy the InfoPath form. You have to understand the STSADM syntax so that you can build the script to deploy the InfoPath form.

Here I have summarized what I did. It may useful for you to start.
 I developed the web service that will construct the script using STSADM and save it as bat file and run the batch file using Process command available in C#.

OwnerDisplayName: Saul

OwnerDisplayName: guna Samba


问:
Javascript - React - Arrow Function Usage Understanding
I'm trying to wrap my head around how this is coded

https://github.com/ReactTraining/react-router/blob/dc2149ec0c63bfc95b71e40c81431e34cfbfeda9/packages/react-router-dom/modules/NavLink.js#L8

```<code>const NavLink = ({
  to,
  exact,
  strict,
  activeClassName,
  className,
  activeStyle,
  style,
  isActive: getIsActive,
  ...rest
}) => (
  <Route
    path={typeof to === 'object' ? to.pathname : to}
    exact={exact}
    strict={strict}
    children={({ location, match }) => {
      const isActive = !!(getIsActive ? getIsActive(match, location) : match)

      return (
        <Link
          to={to}
          className={isActive ? [ activeClassName, className ].join(' ') : className}
          style={isActive ? { ...style, ...activeStyle } : style}
          {...rest}
        />
      )
    }}
  />
)
</code>```

What's going on here? Is this defining a function that returned a JSX element? The only thing that is throwing me is the JSX element being wrapped in parentheses ()

What is going on in the first part where there is isActive: getIsActive?

I was looking at http://es6-features.org/#ExpressionBodies and couldn't find a direct example.

I was trying to figure out how to use the isActive method of router and couldn't parse this code.

答:
isActive: getIsActive - this is aliasing of isActive as getIsActive. In the props of the component there's one called isActive, it's extracted by using object destructuring AND renamed locally as getIsActive.

Parenthesis are required here as the jsx markup spans multiple lines. Had it been a single line jsx, no parenthesis would've been needed.

And yes, this is a function (component) that returns jsx markup. This is known as stateless component as it's just a simple function. The opposite would be a full-blown React component that extends React.Component.

Body:
I'm trying to wrap my head around how this is coded

https://github.com/ReactTraining/react-router/blob/dc2149ec0c63bfc95b71e40c81431e34cfbfeda9/packages/react-router-dom/modules/NavLink.js#L8

const NavLink = ({
  to,
  exact,
  strict,
  activeClassName,
  className,
  activeStyle,
  style,
  isActive: getIsActive,
  ...rest
}) => (
  <Route
    path={typeof to === 'object' ? to.pathname : to}
    exact={exact}
    strict={strict}
    children={({ location, match }) => {
      const isActive = !!(getIsActive ? getIsActive(match, location) : match)

      return (
        <Link
          to={to}
          className={isActive ? [ activeClassName, className ].join(' ') : className}
          style={isActive ? { ...style, ...activeStyle } : style}
          {...rest}
        />
      )
    }}
  />
)

What's going on here? Is this defining a function that returned a JSX element? The only thing that is throwing me is the JSX element being wrapped in parentheses ()

What is going on in the first part where there is isActive: getIsActive?

I was looking at http://es6-features.org/#ExpressionBodies and couldn't find a direct example.

I was trying to figure out how to use the isActive method of router and couldn't parse this code.


问:
How to get rid of empty strings from csv file's row using Python
I am writing code which takes rows from a CSV file and transfers them into a lists of integers. However, if I leave some blank entries in the row, I get a "list index out of range" error. Here is the code:

```<code>import csv

with open('Test.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')
    rows = [[int(row[0]), int(row[1]),int(row[2]),int(row[3])] for row in reader]

for row in rows:
   print(row)
</code>```

I looked up some similar questions on this website and the best idea for the solution I got was:

```<code>rows = [[int(row[0]), int(row[1]),int(row[2]),int(row[3])] for row in reader if len(row)>1]
</code>```

However, it resulted with the same error.

Thanks in advance!

答:
The problem is that if you don't have an int or it is empty the cast will fail.

The below example inserts a zero '0' in case the value is not an int or is empty. Replace it by what you want.

You can optimize the code but this should work:

Edit: Shorter version

```<code>import csv

def RepresentsInt(s):
    try:
        int(s)
        return True
    except ValueError:
        return False
l = []
with open('test.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')

    for row in reader:
        l.append([int(r) if RepresentsInt(r) else 0 for r in row])

for row in l:
   print(row)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am writing code which takes rows from a CSV file and transfers them into a lists of integers. However, if I leave some blank entries in the row, I get a "list index out of range" error. Here is the code:

import csv

with open('Test.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')
    rows = [[int(row[0]), int(row[1]),int(row[2]),int(row[3])] for row in reader]

for row in rows:
   print(row)

I looked up some similar questions on this website and the best idea for the solution I got was:

rows = [[int(row[0]), int(row[1]),int(row[2]),int(row[3])] for row in reader if len(row)>1]

However, it resulted with the same error.

Thanks in advance!

Body:
The problem is that if you don't have an int or it is empty the cast will fail.

The below example inserts a zero '0' in case the value is not an int or is empty. Replace it by what you want.

You can optimize the code but this should work:

Edit: Shorter version

import csv

def RepresentsInt(s):
    try:
        int(s)
        return True
    except ValueError:
        return False
l = []
with open('test.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')

    for row in reader:
        l.append([int(r) if RepresentsInt(r) else 0 for r in row])

for row in l:
   print(row)


问:
Perl + Apache + CGI
How do I run perl script from local host?

I have installed Apache 2.2 and Active Perl 5.16.3.
I am able to run the perl scrip from command prompt.
But since i am dealing with web application, i want it to be run from localhost.

However, I am getting the following error in the browser

Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.

Please help me out!

答:
if someone is looking for an answer in year 2017 then follow this on windows 2010 machine.

Download Strawberry perl from perl site
Install in default directory.C:\Strawberry

Download Apache from https://httpd.apache.org/download.cgi#apache24

Once you successfully get apache server running then

Place your perl scripts in your Apache24/cgi-bin/ folder.
firstline of your perl script should point to path where perl is installed for my case it is #!C:/Strawberry/perl/bin/perl.exe
you should change your path according your installation folder

Filename - first.pl

```<code>#!C:/Strawberry/perl/bin/perl.exe
print "Content-type: text/html\n\n";
print "Hello, World.";
</code>```

Now you can run your script from browser http://localhost/cgi-bin/first.pl

Title: Perl + Apache + CGI

Body:
if someone is looking for an answer in year 2017 then follow this on windows 2010 machine.

Download Strawberry perl from perl site
Install in default directory.C:\Strawberry

Download Apache from https://httpd.apache.org/download.cgi#apache24

Once you successfully get apache server running then

Place your perl scripts in your Apache24/cgi-bin/ folder.
firstline of your perl script should point to path where perl is installed for my case it is #!C:/Strawberry/perl/bin/perl.exe
you should change your path according your installation folder

Filename - first.pl

#!C:/Strawberry/perl/bin/perl.exe
print "Content-type: text/html\n\n";
print "Hello, World.";

Now you can run your script from browser http://localhost/cgi-bin/first.pl


问:
Excel concatenate with IF statement
What I am trying to do is concatenate two cells, then check that concatenated value against a column of values, and put an X in a cell if such a value exists.  The following equation is what I'm using:

```<code>{=IF(CONCATENATE(A2, " ", B2) = 'MasterList'!$C:$C, "x", "")}
</code>```

Column A is the name of the software and Column B the version number (A="Microsoft .NET Framework 4.5.1", B="4.5.50938", for example). I know that this concatenated value exists on the MasterList worksheet so I don't understand why I'm not getting the answer I expect.

Gurus, what's my flaw here?

答:
The fastest comparison/lookup on the worksheet is a MATCH function. If you have a long column to put this formula into you could try,

```<code>=IF(ISNUMBER(MATCH(CONCATENATE(A2, " ", B2), 'MasterList'!$C:$C, 0)), "x", "")
</code>```

Fill down as necessary.

Title: Excel concatenate with IF statement

Body:
What I am trying to do is concatenate two cells, then check that concatenated value against a column of values, and put an X in a cell if such a value exists.  The following equation is what I'm using:

{=IF(CONCATENATE(A2, " ", B2) = 'MasterList'!$C:$C, "x", "")}

Column A is the name of the software and Column B the version number (A="Microsoft .NET Framework 4.5.1", B="4.5.50938", for example). I know that this concatenated value exists on the MasterList worksheet so I don't understand why I'm not getting the answer I expect.

Gurus, what's my flaw here?

Body:
The fastest comparison/lookup on the worksheet is a MATCH function. If you have a long column to put this formula into you could try,

=IF(ISNUMBER(MATCH(CONCATENATE(A2, " ", B2), 'MasterList'!$C:$C, 0)), "x", "")

Fill down as necessary.


问:
Mergesort in python - too slow?
I'm trying to learn merge sort but I'm not sure I got this quite right. It works and I've tried optimizing this e.g. with deques for leftpop but I still get times that are roughly 4 times slower than the builtin sorted() function. Is this supposed to happen? Or am I missing some obvious bottlenecks?

```<code>import random
from time import time
from collections import deque

unsorted = [random.randint(0, 1000) for r in xrange(101101)]

def merge_sort(unsorted_list):
    length = len(unsorted_list)
    if length <= 1:
        return unsorted_list

    left = unsorted_list[:length / 2]
    right = unsorted_list[length / 2:]

    left_sorted = deque(merge_sort(left))
    right_sorted = deque(merge_sort(right))

    new = []
    while left_sorted and right_sorted:
        if left_sorted[0] < right_sorted[0]:
            new.append(left_sorted.popleft())
            if not left_sorted:
                new += right_sorted
        else:
            new.append(right_sorted.popleft())
            if not right_sorted:
                new += left_sorted
    return new

s = time()
print merge_sort(unsorted)
e = time()
print e - s

s = time()
print sorted(unsorted)
e = time()
print e - s
</code>```

Edit: A somewhat optimized version below:

```<code>def merge_sort(unsorted_list):
    length = len(unsorted_list)
    if length <= 1:
        return unsorted_list

    left = unsorted_list[:length / 2]
    right = unsorted_list[length / 2:]

    left_sorted = deque(merge_sort(left))
    right_sorted = deque(merge_sort(right))

    new = []

    new_append = new.append
    left_pop = left_sorted.popleft
    right_pop = right_sorted.popleft

    while left_sorted and right_sorted:
        if left_sorted[0] < right_sorted[0]:
            new_append(left_pop())
        else:
            new_append(right_pop())

    if not left_sorted:
        new += right_sorted
    if not right_sorted:
        new += left_sorted

    return new
</code>```

答:
I tried to optimize the code as shown below, but it's only a bit faster.

I did a one time "allocation" for a working list, then avoided copy back by using two merge sort functions, one that sorts into original list, the other that sorts into working list.

On my system, Intel 3770K 3.5ghz, Windows 7 64 bit, Python 2.7, when sorting 100,000 integers, the "optimized" version above takes about 0.468 seconds, while the version below takes about 0.320 seconds. The overhead for interpreting code seems to be the bottle neck. The same algorithm as shown below compiled in C++ takes about .0067 seconds, about 47 times as fast.

```<code>import random
from time import time

def sort(a):
    b = a                               # "allocate" b
    msa2a(a, b, 0, len(a))              # merge sort a to a

def msa2a(a, b, low, end):              # merge sort a to a
    if((end - low) < 2):                # if < 2 elements
        return                          #   return
    mid = (low+end)//2                  # set mid point
    msa2b(a, b, low, mid)               # merge sort left  half to b
    msa2b(a, b, mid, end)               # merge sort right half to b
    mrg(b, a, low, mid, end)            # merge halves   from b to a

def msa2b(a, b, low, end):              # merge sort a to b
    if((end - low) < 2):                # if < 2 elements
        b[low] = a[low]                 #   copy 1 element from a to b
        return                          #   return
    mid = (low+end)//2                  # set mid point
    msa2a(a, b, low, mid)               # merge sort left  half to a
    msa2a(a, b, mid, end)               # merge sort right half to a
    mrg(a, b, low, mid, end)            # merge halves   from a to b

def mrg(a, b, ll, rr, ee):              # merge a pair of runs from a to b
    o = ll                              # o = b[]        index
    l = ll                              # l = a[] left   index
    r = rr                              # r = a[] right  index
    while True:
        if(a[l] <= a[r]):               # if a[l] <= a[r]
            b[o] = a[l]                 #   copy a[l]
            o += 1
            l += 1
            if(l < rr):                 #   if not end of left run
                continue                #     continue (back to while)
            b[o:ee] = a[r:ee]           #   else copy rest of right run
            return                      #     and return
        else:                           # else a[l] > a[r]
            b[o] = a[r]                 #   copy a[r]
            o += 1
            r += 1
            if(r < ee):                 #   if not end of right run
                continue                #     continue (back to while)
            b[o:ee] = a[l:rr]           #   else copy rest of left run
            return                      #     and return

# test sort
a = [random.randint(0, 1000) for r in xrange(100000)]
s = time()
sort(a)
e = time()
print e - s

# check to see if data was sorted
f = 0
for i in range (1 ,len(a)-1):
    if(a[i-1] > a[i]):
        f = 1
        break
if(f == 0):
    print("sorted")
else:
    print("error")
</code>```

Title: Mergesort in python - too slow?

Body:
I'm trying to learn merge sort but I'm not sure I got this quite right. It works and I've tried optimizing this e.g. with deques for leftpop but I still get times that are roughly 4 times slower than the builtin sorted() function. Is this supposed to happen? Or am I missing some obvious bottlenecks?

import random
from time import time
from collections import deque

unsorted = [random.randint(0, 1000) for r in xrange(101101)]

def merge_sort(unsorted_list):
    length = len(unsorted_list)
    if length <= 1:
        return unsorted_list

    left = unsorted_list[:length / 2]
    right = unsorted_list[length / 2:]

    left_sorted = deque(merge_sort(left))
    right_sorted = deque(merge_sort(right))

    new = []
    while left_sorted and right_sorted:
        if left_sorted[0] < right_sorted[0]:
            new.append(left_sorted.popleft())
            if not left_sorted:
                new += right_sorted
        else:
            new.append(right_sorted.popleft())
            if not right_sorted:
                new += left_sorted
    return new

s = time()
print merge_sort(unsorted)
e = time()
print e - s

s = time()
print sorted(unsorted)
e = time()
print e - s

Edit: A somewhat optimized version below:

def merge_sort(unsorted_list):
    length = len(unsorted_list)
    if length <= 1:
        return unsorted_list

    left = unsorted_list[:length / 2]
    right = unsorted_list[length / 2:]

    left_sorted = deque(merge_sort(left))
    right_sorted = deque(merge_sort(right))

    new = []

    new_append = new.append
    left_pop = left_sorted.popleft
    right_pop = right_sorted.popleft

    while left_sorted and right_sorted:
        if left_sorted[0] < right_sorted[0]:
            new_append(left_pop())
        else:
            new_append(right_pop())

    if not left_sorted:
        new += right_sorted
    if not right_sorted:
        new += left_sorted

    return new

Body:
I tried to optimize the code as shown below, but it's only a bit faster.

I did a one time "allocation" for a working list, then avoided copy back by using two merge sort functions, one that sorts into original list, the other that sorts into working list.

On my system, Intel 3770K 3.5ghz, Windows 7 64 bit, Python 2.7, when sorting 100,000 integers, the "optimized" version above takes about 0.468 seconds, while the version below takes about 0.320 seconds. The overhead for interpreting code seems to be the bottle neck. The same algorithm as shown below compiled in C++ takes about .0067 seconds, about 47 times as fast.

import random
from time import time

def sort(a):
    b = a                               # "allocate" b
    msa2a(a, b, 0, len(a))              # merge sort a to a

def msa2a(a, b, low, end):              # merge sort a to a
    if((end - low) < 2):                # if < 2 elements
        return                          #   return
    mid = (low+end)//2                  # set mid point
    msa2b(a, b, low, mid)               # merge sort left  half to b
    msa2b(a, b, mid, end)               # merge sort right half to b
    mrg(b, a, low, mid, end)            # merge halves   from b to a

def msa2b(a, b, low, end):              # merge sort a to b
    if((end - low) < 2):                # if < 2 elements
        b[low] = a[low]                 #   copy 1 element from a to b
        return                          #   return
    mid = (low+end)//2                  # set mid point
    msa2a(a, b, low, mid)               # merge sort left  half to a
    msa2a(a, b, mid, end)               # merge sort right half to a
    mrg(a, b, low, mid, end)            # merge halves   from a to b

def mrg(a, b, ll, rr, ee):              # merge a pair of runs from a to b
    o = ll                              # o = b[]        index
    l = ll                              # l = a[] left   index
    r = rr                              # r = a[] right  index
    while True:
        if(a[l] <= a[r]):               # if a[l] <= a[r]
            b[o] = a[l]                 #   copy a[l]
            o += 1
            l += 1
            if(l < rr):                 #   if not end of left run
                continue                #     continue (back to while)
            b[o:ee] = a[r:ee]           #   else copy rest of right run
            return                      #     and return
        else:                           # else a[l] > a[r]
            b[o] = a[r]                 #   copy a[r]
            o += 1
            r += 1
            if(r < ee):                 #   if not end of right run
                continue                #     continue (back to while)
            b[o:ee] = a[l:rr]           #   else copy rest of left run
            return                      #     and return

# test sort
a = [random.randint(0, 1000) for r in xrange(100000)]
s = time()
sort(a)
e = time()
print e - s

# check to see if data was sorted
f = 0
for i in range (1 ,len(a)-1):
    if(a[i-1] > a[i]):
        f = 1
        break
if(f == 0):
    print("sorted")
else:
    print("error")


问:
how to use lokijs-cordova-fs-adapter in ionic 2
I am trying to use lokijs in my ionic 2 app. i am able to use lokijs.js.
when trying to persist using adapter i am not able to. i ready lokijs-cordova-fs-adapter can be used. but when i refer it in my app as below: getting an error that its not able to locate.

```<code>var LokiCordovaFSAdapter = require("./cordova-file-system-adapter");
</code>```

tried adding it in my index.html and tried creating adapter in my ts file as below:

```<code>var adapter = new LokiCordovaFSAdapter({"prefix": "loki"});
</code>```

getting syntax error in this case. can someone give an example on how to use it?

答:
Ciao, this works on Ionic 2, so step-by-step (I did this inside a service):

Check if both dependencies are installed:

```<code>npm install lokijs --save
npm install loki-cordova-fs-adapter --save
</code>```

Declare and import the following (before the class declaration):

```<code>declare var require: any;
var loki = require('lokijs');
var LokiCordovaFSAdapter = require("loki-cordova-fs-adapter");
var adapter = new LokiCordovaFSAdapter({"prefix": "loki"});
</code>```

Use the following inside the service class:

```<code>db: any; // LokiJS database
pandas: any; // our DB's document collection object

constructor() {
  console.log("* inicializando...");

  this.db = new loki('pandas.db', {
    autoload: true,
    autoloadCallback: function() {
      console.log("* database loaded...")
    },
    autosave: true,
    autosaveInterval: 10 * 1000, //every 10 seconds
    adapter: adapter
  });
}
</code>```

Use it (this code is also inside the service class):

```<code>load() {
  let collection = this.db.getCollection('pandas');
  if (collection == null) {
    this.pandas = this.db.addCollection('pandas');
  } else {
    this.pandas = collection;
  }
}

pandaKamasutra() {
  console.log("* Save the pandas...");
  for (let i=0; i < 100; i++)
    this.pandas.insert({ name: 'Panda ' + (i+1), surename: "Whurgh " + i });
}

showPandas() {
  var results = this.pandas.find({});
  for (let r of results)
    console.log(`% id: ${r.$loki}, Panda: ${r.name}`);
}
</code>```

I spent this afternoon solving this, after swimming around both LokiJS and lokijs-cordova-fs-adapter code, I found the 'light' in the Ionic documentation here.

Hope it works for you too. =]

Body:
I am trying to use lokijs in my ionic 2 app. i am able to use lokijs.js.
when trying to persist using adapter i am not able to. i ready lokijs-cordova-fs-adapter can be used. but when i refer it in my app as below: getting an error that its not able to locate.

var LokiCordovaFSAdapter = require("./cordova-file-system-adapter");

tried adding it in my index.html and tried creating adapter in my ts file as below:

var adapter = new LokiCordovaFSAdapter({"prefix": "loki"});

getting syntax error in this case. can someone give an example on how to use it?

Body:
Ciao, this works on Ionic 2, so step-by-step (I did this inside a service):

Check if both dependencies are installed:

npm install lokijs --save
npm install loki-cordova-fs-adapter --save

Declare and import the following (before the class declaration):

declare var require: any;
var loki = require('lokijs');
var LokiCordovaFSAdapter = require("loki-cordova-fs-adapter");
var adapter = new LokiCordovaFSAdapter({"prefix": "loki"});

Use the following inside the service class:

db: any; // LokiJS database
pandas: any; // our DB's document collection object

constructor() {
  console.log("* inicializando...");

  this.db = new loki('pandas.db', {
    autoload: true,
    autoloadCallback: function() {
      console.log("* database loaded...")
    },
    autosave: true,
    autosaveInterval: 10 * 1000, //every 10 seconds
    adapter: adapter
  });
}

Use it (this code is also inside the service class):

load() {
  let collection = this.db.getCollection('pandas');
  if (collection == null) {
    this.pandas = this.db.addCollection('pandas');
  } else {
    this.pandas = collection;
  }
}

pandaKamasutra() {
  console.log("* Save the pandas...");
  for (let i=0; i < 100; i++)
    this.pandas.insert({ name: 'Panda ' + (i+1), surename: "Whurgh " + i });
}

showPandas() {
  var results = this.pandas.find({});
  for (let r of results)
    console.log(`% id: ${r.$loki}, Panda: ${r.name}`);
}

I spent this afternoon solving this, after swimming around both LokiJS and lokijs-cordova-fs-adapter code, I found the 'light' in the Ionic documentation here.

Hope it works for you too. =]


问:
Connecting to a remote instance of Clojure
I read that is possible to connect to a remote, production instance of Clojure via the REPL.

Would you please explain this to me? and how to do it?

What "instance of Clojure" means?

答:
For REPL specifically, you can use swank-clojure library.
Once your clojure application is up and running and has a swank server running in it, you can connect to it from emacs editor using its package called SLIME.

There's also NetBeans IDE plugin enclojure that has exactly the same functionality. It has a server part, which you include and run in your clojure application, and it has a client part which connects to it from NetBeans.


问:
Arranging data to make a 3d surface plot
I am trying to make 3D surface plot, but I'm having trouble transforming my data into the right format.

Reshaping my Z variable gives me: 'ValueError: total size of new array must be unchanged'. The shape for Z is (2500,50). The shapes for X and Y are both (50,50). I'm not sure why this is so. Is there something obviously wrong with my code that I'm missing?

```<code>import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

def Mountain(F, P):
    TA = ((TAmax-TAmin) * (((FF**g)/((FF**g)+FFhm**g)**a)/((((FF**g)/((FF**g)+FFhm**g))**a)+(SP/SPe)**a)))
    return TA

F = np.linspace(0,120)
P = np.linspace(0,100)
Fb= int(21)
Fro= int(362)
FFhm = int(63)
g= int(3)
a = int(3)
SPmin = float(1.82)
SPbend = float(0.5)
SPe = int(10)
TAmax= int(1)
TAmin = int(0)

SP = SPmin + SPbend * np.log(1 + np.exp((P - SPmin)/SPbend))

FF= (Fb * (np.log(1 + np.exp(Fro/Fb)) - np.log(1 + np.exp((Fro-F)/Fb))))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y = np.meshgrid(F, P)
gh= list(zip(np.ravel(X), np.ravel(Y)))
zs = np.array(Mountain(F,P) for F,P in gh)
Z = zs.reshape(X.shape)

ax.plot_surface(X, Y, Z)

ax.set_xlabel('F')
ax.set_ylabel('P')
ax.set_zlabel('TA')

plt.show()
</code>```

答:
You have to put z value for every pair of (X,Y). It mean you do not need numpy.ravel. The sizes of X, Y and Z must be the same:

```<code>import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

def Mountain(F, P):
    TA = ((TAmax-TAmin) * (((FF**g)/((FF**g)+FFhm**g)**a)/((((FF**g)/((FF**g)+FFhm**g))**a)+(SP/SPe)**a)))
    return TA

F = np.linspace(0,120)
P = np.linspace(0,100)
Fb= int(21)
Fro= int(362)
FFhm = int(63)
g= int(3)
a = int(3)
SPmin = float(1.82)
SPbend = float(0.5)
SPe = int(10)
TAmax= int(1)
TAmin = int(0)

SP = SPmin + SPbend * np.log(1 + np.exp((P - SPmin)/SPbend))
FF= (Fb * (np.log(1 + np.exp(Fro/Fb)) - np.log(1 + np.exp((Fro-F)/Fb))))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y = np.meshgrid(F, P)
Z = np.array(Mountain(F,P))

ax.plot_surface(X, Y, Z)

ax.set_xlabel('F')
ax.set_ylabel('P')
ax.set_zlabel('TA')

plt.show()
</code>```

Body:
I am trying to make 3D surface plot, but I'm having trouble transforming my data into the right format.

Reshaping my Z variable gives me: 'ValueError: total size of new array must be unchanged'. The shape for Z is (2500,50). The shapes for X and Y are both (50,50). I'm not sure why this is so. Is there something obviously wrong with my code that I'm missing?

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

def Mountain(F, P):
    TA = ((TAmax-TAmin) * (((FF**g)/((FF**g)+FFhm**g)**a)/((((FF**g)/((FF**g)+FFhm**g))**a)+(SP/SPe)**a)))
    return TA

F = np.linspace(0,120)
P = np.linspace(0,100)
Fb= int(21)
Fro= int(362)
FFhm = int(63)
g= int(3)
a = int(3)
SPmin = float(1.82)
SPbend = float(0.5)
SPe = int(10)
TAmax= int(1)
TAmin = int(0)

SP = SPmin + SPbend * np.log(1 + np.exp((P - SPmin)/SPbend))

FF= (Fb * (np.log(1 + np.exp(Fro/Fb)) - np.log(1 + np.exp((Fro-F)/Fb))))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y = np.meshgrid(F, P)
gh= list(zip(np.ravel(X), np.ravel(Y)))
zs = np.array(Mountain(F,P) for F,P in gh)
Z = zs.reshape(X.shape)

ax.plot_surface(X, Y, Z)

ax.set_xlabel('F')
ax.set_ylabel('P')
ax.set_zlabel('TA')

plt.show()

Body:
You have to put z value for every pair of (X,Y). It mean you do not need numpy.ravel. The sizes of X, Y and Z must be the same:

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

def Mountain(F, P):
    TA = ((TAmax-TAmin) * (((FF**g)/((FF**g)+FFhm**g)**a)/((((FF**g)/((FF**g)+FFhm**g))**a)+(SP/SPe)**a)))
    return TA

F = np.linspace(0,120)
P = np.linspace(0,100)
Fb= int(21)
Fro= int(362)
FFhm = int(63)
g= int(3)
a = int(3)
SPmin = float(1.82)
SPbend = float(0.5)
SPe = int(10)
TAmax= int(1)
TAmin = int(0)

SP = SPmin + SPbend * np.log(1 + np.exp((P - SPmin)/SPbend))
FF= (Fb * (np.log(1 + np.exp(Fro/Fb)) - np.log(1 + np.exp((Fro-F)/Fb))))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y = np.meshgrid(F, P)
Z = np.array(Mountain(F,P))

ax.plot_surface(X, Y, Z)

ax.set_xlabel('F')
ax.set_ylabel('P')
ax.set_zlabel('TA')

plt.show()


问:
Funnel chart with bars separated
what is the best way to create funnel chart with bars separated and as a funnel (as below image- click image link) using css, html, javascript.

答:
I usually use amcharts to create charts. They're easy to use and beautiful to look at. Do give them a try :)

https://www.amcharts.com/demos/funnel-chart/

I created a plunker link so that you can see how this works and maybe explore it a little bit.

https://plnkr.co/edit/tp6oOpoxChMoYlpwEroC?p=preview

All you need in you html is this

```<code><div id="chartdiv"></div>
</code>```

If you want to go for something even more visually appealing, you can use 3d funnel charts that amcharts provides.

https://www.amcharts.com/demos/3d-funnel-chart/

Title: Funnel chart with bars separated

Body:
I usually use amcharts to create charts. They're easy to use and beautiful to look at. Do give them a try :)

https://www.amcharts.com/demos/funnel-chart/

I created a plunker link so that you can see how this works and maybe explore it a little bit.

https://plnkr.co/edit/tp6oOpoxChMoYlpwEroC?p=preview

All you need in you html is this

<div id="chartdiv"></div>

If you want to go for something even more visually appealing, you can use 3d funnel charts that amcharts provides.

https://www.amcharts.com/demos/3d-funnel-chart/


问:
How to use bypassSecurityTrustStyle correctly
I am trying to work with some simple CSS and JavaScript examples in an Angular way.

The plain JavaScript way to change the background color on an element would look something like this:

```<code>this.container.style.backgroundColor = color;
</code>```

The color is created randomly in JavaScript.
The template could look like this:

```<code><div id="container"
  (click)="changeColor($event)"
  [style]="{'color': color}">
</div>
</code>```

However, this will give the following error:

```<code>WARNING: sanitizing unsafe style value [object Object] (see http://g.co/ng/security#xss).
</code>```

Using this function does not work:

```<code>this.color = this.sanitizer.bypassSecurityTrustStyle(this.color);
</code>```

Creating a function to do it also does not work using this style [style.color]="transform(color)"

```<code>transform(value) {
   return this.sanitizer.bypassSecurityTrustStyle(value);
}
</code>```

I have created a plunker to demonstrate this problem.

The correct behaviour using plain JavaScript is shown in the first example on this page

What is the correct way to do this?  Any help would be much appreciated.

答:
The example plunker
was using bypassSecurityTrustStyle correctly:

```<code> this.color = this.sanitizer.bypassSecurityTrustStyle(this.color);
</code>```

However, the template needed to set the value like this:

```<code>[style.background]="color"
</code>```

Body:
I am trying to work with some simple CSS and JavaScript examples in an Angular way.

The plain JavaScript way to change the background color on an element would look something like this:

this.container.style.backgroundColor = color;

The color is created randomly in JavaScript.
The template could look like this:

However, this will give the following error:

WARNING: sanitizing unsafe style value [object Object] (see http://g.co/ng/security#xss).

Using this function does not work:

this.color = this.sanitizer.bypassSecurityTrustStyle(this.color);

Creating a function to do it also does not work using this style [style.color]="transform(color)"

transform(value) {
   return this.sanitizer.bypassSecurityTrustStyle(value);
}

I have created a plunker to demonstrate this problem.

The correct behaviour using plain JavaScript is shown in the first example on this page

What is the correct way to do this?  Any help would be much appreciated.

Body:
The example plunker
was using bypassSecurityTrustStyle correctly:

 this.color = this.sanitizer.bypassSecurityTrustStyle(this.color);

However, the template needed to set the value like this:

[style.background]="color"


问:
How to use an interface with methods that has in input or return type the reference of the interface?
I have an interface like that:

```<code>public interface IntTree {
    public int getValue();
    public int childrenNumber();
    public int nodes ();
    public int height ();
    public boolean equals (IntTree t);
    public void addChild (IntTree child);
    public IntTree followPath(int[] path);
    public void visit ();
    public void printIntTree ();
}
</code>```

And I don't know how to implement MyTree because there are a lot of references on the interface: for example:

```<code>public void addChild (IntTree child);
public IntTree followPath(int[] path);
public boolean equals (IntTree t);
</code>```

So I don't understand how to use IntTree reference. I did all my methods with a cast for example:

```<code>public class MyTree implements IntTree {
    private int data;
    private LinkedList<MyTree> children; //I have to declare it IntTree or MyTree?

    public MyTree(int data) {
        this.data = data;
        this.children = new LinkedList<>();
    }
    public void addChild(IntTree child){
        this.children.addFirst((MyTree) child);
    }
    public LinkedList<MyTree> getChildren() {
        return this.children;
    }
}
</code>```

But my teacher said that is wrong to do that, how can I get access for example to my children list etc if I can't cast it to MyTree object? how can I do a method public IntTree followPath(int[] path); if MyTree object = this and it's != from IntTree? Please explain me, I am getting mad:

And for the other methods that have nothing in input and not return a reference of the Interface I can implement it with the constructor of MyTree?

答:
private LinkedList children; //I have to declare it IntTree or MyTree?

You should use IntTree here as then you'll add elements that implements IntTree interface so it could be a different class object then MyTree. What you're doing is not type safe, take this as example:

```<code>public class SomeTree implements IntTree {
    //some code
}
</code>```

And then lets use SomeTree with our MyTree.

```<code>MyTree myTree = new MyTree();
SomeTree child = new SomeTree();

myTree.addChild(child); //Here we get ClassCastException
</code>```

If you need to implement IntTree interface without changing it then you should leave it as it is without casting. Your code should always be type safe if it is possible.

Body:
I have an interface like that:

public interface IntTree {
    public int getValue();
    public int childrenNumber();
    public int nodes ();
    public int height ();
    public boolean equals (IntTree t);
    public void addChild (IntTree child);
    public IntTree followPath(int[] path);
    public void visit ();
    public void printIntTree ();
}

And I don't know how to implement MyTree because there are a lot of references on the interface: for example:

public void addChild (IntTree child);
public IntTree followPath(int[] path);
public boolean equals (IntTree t);

So I don't understand how to use IntTree reference. I did all my methods with a cast for example:

public class MyTree implements IntTree {
    private int data;
    private LinkedList<MyTree> children; //I have to declare it IntTree or MyTree?

    public MyTree(int data) {
        this.data = data;
        this.children = new LinkedList<>();
    }
    public void addChild(IntTree child){
        this.children.addFirst((MyTree) child);
    }
    public LinkedList<MyTree> getChildren() {
        return this.children;
    }
}

But my teacher said that is wrong to do that, how can I get access for example to my children list etc if I can't cast it to MyTree object? how can I do a method public IntTree followPath(int[] path); if MyTree object = this and it's != from IntTree? Please explain me, I am getting mad:

And for the other methods that have nothing in input and not return a reference of the Interface I can implement it with the constructor of MyTree?

Body:
private LinkedList children; //I have to declare it IntTree or MyTree?

You should use IntTree here as then you'll add elements that implements IntTree interface so it could be a different class object then MyTree. What you're doing is not type safe, take this as example:

public class SomeTree implements IntTree {
    //some code
}

And then lets use SomeTree with our MyTree.

MyTree myTree = new MyTree();
SomeTree child = new SomeTree();

myTree.addChild(child); //Here we get ClassCastException

If you need to implement IntTree interface without changing it then you should leave it as it is without casting. Your code should always be type safe if it is possible.


问:
Mongoose, populate items that do not match specified value
So let's say I wanted to just populate 'galleries' with the status 'published' I would run:

```<code>Project.populate(project, [{path: 'galleries', match: {status: 'published'}
</code>```

This works fine. But let's say I want to populate with all galleries except those with status 'published'..I tried running the following but it does not work:

```<code>Project.populate(project, [{path: 'galleries', not: {status: 'published'}...
</code>```

答:
Answered my own question:</p>

```<code>Project.populate(project, [{path: 'galleries', match: {status: {$ne: 'published'}}}
</code>```

Body:
So let's say I wanted to just populate 'galleries' with the status 'published' I would run:

Project.populate(project, [{path: 'galleries', match: {status: 'published'}

This works fine. But let's say I want to populate with all galleries except those with status 'published'..I tried running the following but it does not work:

Project.populate(project, [{path: 'galleries', not: {status: 'published'}...

Body:
Answered my own question:

Project.populate(project, [{path: 'galleries', match: {status: {$ne: 'published'}}}


问:
One Gitlab CI runner per project?
We upgraded from Gitlab 7.11.4 to 9 in one fell swoop (by accident).  Now we are trying to get CI set up the way it use to run for us before.  I understand that CI is an integrated thing now.

One of my coworkers got a multi-runner thing going.  The running command looks like so:

```<code>/usr/bin/gitlab-ci-multi-runner run --working-directory /home/gitlab-runner --config /etc/gitlab-runner/config.toml --service gitlab-runner --syslog --user gitlab-runner
</code>```

But previously we had 1 runner for each project and we had a user associated for each project.  So, if we have 2 projects called "portal" and "engine", we would have users created thusly:

```<code>gitlab-runner-fps-portal
gitlab-runner-fps-engine
</code>```

And being users, they would have home folders like:

```<code>/home/gitlab-runner-fps-portal
/home/gitlab-runner-fps-engine
</code>```

In the older version of CI, you'd have a config.yml with the url of CI and the runners token.  Now you have config.toml.

I want to "divorce" the engine runner from this multi setup which runs under user "gitlab-runner" and have its own runner that runs under "gitlab-runner-fps-engine".

Easy to do?  Right now since all of this docker business is new to us, we're continuing on to use "shell" as our executor in gitlab, if that information is useful.

答:
There are at least two ways you can do it:

Register a specific runner in each of the projects and disable the shared runners.

Use tags to specify the job must be run on a specific runner. This way you can have some CI jobs run on your defined environment while others (like lint for example) can be run on tagged shared runners.

Title: One Gitlab CI runner per project?

Body:
We upgraded from Gitlab 7.11.4 to 9 in one fell swoop (by accident).  Now we are trying to get CI set up the way it use to run for us before.  I understand that CI is an integrated thing now.

One of my coworkers got a multi-runner thing going.  The running command looks like so:

/usr/bin/gitlab-ci-multi-runner run --working-directory /home/gitlab-runner --config /etc/gitlab-runner/config.toml --service gitlab-runner --syslog --user gitlab-runner

But previously we had 1 runner for each project and we had a user associated for each project.  So, if we have 2 projects called "portal" and "engine", we would have users created thusly:

gitlab-runner-fps-portal
gitlab-runner-fps-engine

And being users, they would have home folders like:

/home/gitlab-runner-fps-portal
/home/gitlab-runner-fps-engine

In the older version of CI, you'd have a config.yml with the url of CI and the runners token.  Now you have config.toml.

I want to "divorce" the engine runner from this multi setup which runs under user "gitlab-runner" and have its own runner that runs under "gitlab-runner-fps-engine".

Easy to do?  Right now since all of this docker business is new to us, we're continuing on to use "shell" as our executor in gitlab, if that information is useful.


问:
TypeScript union type between "newable" or function
I have a function, foo, which I want to accept a parameter bar which is either a "newable" ({ new(...args: Array<any>): any; }) or a function returning type any.

I have tried the following two methods, but in the first example bar has a type of () => any according to the compiler, and in the second example I get a syntax parsing error on the ) of () => any with the message "Type expected".

```<code>type Newable = { new (...args: Array<any>): any; };

function foo1(bar: () => any | Newable) {

}

function foo2(bar: Newable | () => any) {

}
</code>```

Please note I do not want to use the Function type - I want to have finer control over the function specifics.

答:
You need to enclose the () => any in parentheses. Like this:

```<code>type Newable = { new (...args: Array<any>): any; };

function foo1(bar: (() => any) | Newable) {
    //...
}

function foo2(bar: Newable | (() => any)) {
    //...
}
</code>```

Body:
I have a function, foo, which I want to accept a parameter bar which is either a "newable" ({ new(...args: Array<any>): any; }) or a function returning type any.

I have tried the following two methods, but in the first example bar has a type of () => any according to the compiler, and in the second example I get a syntax parsing error on the ) of () => any with the message "Type expected".

type Newable = { new (...args: Array<any>): any; };

function foo1(bar: () => any | Newable) {

}

function foo2(bar: Newable | () => any) {

}

Please note I do not want to use the Function type - I want to have finer control over the function specifics.

Body:
You need to enclose the () => any in parentheses. Like this:

type Newable = { new (...args: Array<any>): any; };

function foo1(bar: (() => any) | Newable) {
    //...
}

function foo2(bar: Newable | (() => any)) {
    //...
}


问:
Image gallery from folder with limit of images
I have some code below, but I cant get the array_splice to limit the number of images shown.

```<code><?php
$id = $_GET['id'];
  if (empty($id)) {
    $clientname = 'tazz';
} else {
    $clientname = $_GET['id'];
}

$total = $_GET['limit'];
  if (empty($total)) {
    $limit = '100';
} else {
    $limit = $_GET['limit'];
}

$basefolder = "client/client-galleries/";
$dirname = $basefolder.$clientname."/";

    $images = scandir($dirname);
    sort($images);
    //shuffle($images);
    $ignore = array(".", "..");
    $output = array_splice($ignore, 0, $limit);

foreach($images as $curimg) {
        if(!in_array($curimg, $output)) {

echo "
    <div class='gallery'>
        <img src='[[pThumb? &input=`$dirname$curimg` &options=`&w=300&h=300&zc=1&q=95&fltr[]=wmi|./client/images/gallery-watermark-white.png|BL|50|25|200`]]' alt='$curimg'>
        <div class='desc'></div>
    </div>\n ";

        }
    }
</code>```

This correctly shows the images in the gallery but doesnt limit the amount of images as set by http://website.address?id=client&limit=5

答:
A few issues with your code, such as using the $ignore array instead of your $images array. I've made a few changes which is probably closer to what you're after. </p>

```<code>$limit = 5;
$dirname = "...";
$images = array_diff(scandir($dirname), [".", ".."]);
sort($images);
$limitedImages = array_slice($images, 0, 5);
foreach ($limitedImages as $curimg) {
   var_dump($curimg);
}
</code>```

Body:
I have some code below, but I cant get the array_splice to limit the number of images shown.

<?php
$id = $_GET['id'];
  if (empty($id)) {
    $clientname = 'tazz';
} else {
    $clientname = $_GET['id'];
}

$total = $_GET['limit'];
  if (empty($total)) {
    $limit = '100';
} else {
    $limit = $_GET['limit'];
}

$basefolder = "client/client-galleries/";
$dirname = $basefolder.$clientname."/";

    $images = scandir($dirname);
    sort($images);
    //shuffle($images);
    $ignore = array(".", "..");
    $output = array_splice($ignore, 0, $limit);

foreach($images as $curimg) {
        if(!in_array($curimg, $output)) {

echo "

        <img src='[[pThumb? &input=`$dirname$curimg` &options=`&w=300&h=300&zc=1&q=95&fltr[]=wmi|./client/images/gallery-watermark-white.png|BL|50|25|200`]]' alt='$curimg'>

\n ";

        }
    }

This correctly shows the images in the gallery but doesnt limit the amount of images as set by http://website.address?id=client&limit=5

Body:
A few issues with your code, such as using the $ignore array instead of your $images array. I've made a few changes which is probably closer to what you're after.

$limit = 5;
$dirname = "...";
$images = array_diff(scandir($dirname), [".", ".."]);
sort($images);
$limitedImages = array_slice($images, 0, 5);
foreach ($limitedImages as $curimg) {
   var_dump($curimg);
}


问:
How to skip lifecycle phase in multi maven module
I have a maven multi module project which call two sub modules. please note that this child module do not use the  parent markup tag. Now I need to have the deploy phase executed only on one child module but not the other one. Could someone provide any advice on the best way of doing this ?

Thanks

答:
multiple-module maven project can specify on which submodule to execute phases with parent pom.xml.

Go to where the parent pom.xml is

execute: mvn --projects [target-module-artifactId] [phase/goal]. For example: mvn --projects submodule1 deploy


问:
Oracle - Extract multiple substrings from a string
I need to extract all e-mail accounts mentioned on a single string, so far I've tried with SUBSTR and INSTR, but with no success, here an example:

The string looks like this:

```<code>()
string = "User_1" {user_1@domain.com};"User_2" {user_2@domain.com};"User_3" {user_3@domain.com};"User_4" {user_4@domain.com};

select SUBSTR(string ,INSTR(string ,'<',-1,2)) EMAIL
from dual;
</code>```

What I need is something like this:

```<code>user_1@domain.com;user_2@domain.com;user_3@domain.com;user_4@domain.com;
</code>```

答:
Something like this will work for a single input string. It can be adapted to work with more than one input string.</p>

```<code>with
     inputs (str) as (
       select '"User_1" {user_1@domain.com};"User_2" {user_2@domain.com};"User_3" {user_3@domain.com};"User_4" {user_4@domain.com};'
       from   dual
     )
select level as ord,
       substr(str, instr(str, '{', 1, level) + 1,
              instr(str, '}', 1, level) - instr(str, '{', 1, level) - 1) as email
from   inputs
connect by level <= length(str) - length(replace(str, '{'))
;

ORD  EMAIL
---  -----------------
  1  user_1@domain.com
  2  user_2@domain.com
  3  user_3@domain.com
  4  user_4@domain.com
</code>```

Body:
I need to extract all e-mail accounts mentioned on a single string, so far I've tried with SUBSTR and INSTR, but with no success, here an example:

The string looks like this:

()
string = "User_1" {user_1@domain.com};"User_2" {user_2@domain.com};"User_3" {user_3@domain.com};"User_4" {user_4@domain.com};

select SUBSTR(string ,INSTR(string ,'<',-1,2)) EMAIL
from dual;

What I need is something like this:

user_1@domain.com;user_2@domain.com;user_3@domain.com;user_4@domain.com;

Body:
Something like this will work for a single input string. It can be adapted to work with more than one input string.

with
     inputs (str) as (
       select '"User_1" {user_1@domain.com};"User_2" {user_2@domain.com};"User_3" {user_3@domain.com};"User_4" {user_4@domain.com};'
       from   dual
     )
select level as ord,
       substr(str, instr(str, '{', 1, level) + 1,
              instr(str, '}', 1, level) - instr(str, '{', 1, level) - 1) as email
from   inputs
connect by level <= length(str) - length(replace(str, '{'))
;

ORD  EMAIL
---  -----------------
  1  user_1@domain.com
  2  user_2@domain.com
  3  user_3@domain.com
  4  user_4@domain.com


问:
Uncaught TypeError: Cannot read property 'post' of undefined VueJS
In Laravel 5.4 I am trying to make a payment with Stripe. I am following the video on laracast if you have an account you can watch the video here:
https://laracasts.com/series/how-to-accept-payments-with-stripe/episodes/3

I changed it up to fit my needs and there are somethings he does that does not work with version 0.3 of vue which I was able to fix except for this problem.

I have this code:

```<code>data: function data() {
  return {
     stripeEmail: '',
     stripeToken: ''
  };
},
created: function created() {

  this.stripe = StripeCheckout.configure({

    key: "my_key",
    image: "https://stripe.com/img/documentation/checkout/marketplace.png",
    locale: "auto",
    token: (token) => {
      this.stripeToken = token.id;
      this.stripeEmail = token.email;

      this.$http.post('/payment', this.$data).then(response => alert('Message'));
    }
  });
},

methods: {
  buy: function buy() {
    this.stripe.open({
      name: "One Month Subscription",
      description: "Having your business displayed for one month.",
      zipcode: true,
      amount: 1000

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

I am able to put the information in but as soon as I hit submit it returns the error:

```<code>Uncaught TypeError: Cannot read property 'post' of undefined
</code>```

I installed vue-resource in my bootstrap.js here:

```<code>window.Vue = require('vue');
require('vue-resource');
</code>```

This solved the $http problem but now I get the post problem.

If there is any other information you need let me know.

答:
I think there might be a problem with this.  Specifically, the this in created is likely not the same as the this in token.  Try ... this:

```<code>created: function created() {
  var self = this;

  self.stripe = StripeCheckout.configure({
    key: "my_key",
    image: "https://stripe.com/img/documentation/checkout/marketplace.png",
    locale: "auto",
    token: (token) => {
      self.stripeToken = token.id;
      self.stripeEmail = token.email;

      self.$http.post('/payment', self.$data).then(response => alert('Message'));
    }
  });
},
</code>```

I know you're using arrow functions so this shouldn't be the case, but I'd give it a try anyways and see how it goes.

Body:
In Laravel 5.4 I am trying to make a payment with Stripe. I am following the video on laracast if you have an account you can watch the video here:
https://laracasts.com/series/how-to-accept-payments-with-stripe/episodes/3

I changed it up to fit my needs and there are somethings he does that does not work with version 0.3 of vue which I was able to fix except for this problem.

I have this code:

data: function data() {
  return {
     stripeEmail: '',
     stripeToken: ''
  };
},
created: function created() {

  this.stripe = StripeCheckout.configure({

    key: "my_key",
    image: "https://stripe.com/img/documentation/checkout/marketplace.png",
    locale: "auto",
    token: (token) => {
      this.stripeToken = token.id;
      this.stripeEmail = token.email;

      this.$http.post('/payment', this.$data).then(response => alert('Message'));
    }
  });
},

methods: {
  buy: function buy() {
    this.stripe.open({
      name: "One Month Subscription",
      description: "Having your business displayed for one month.",
      zipcode: true,
      amount: 1000

    });
  }
}

I am able to put the information in but as soon as I hit submit it returns the error:

Uncaught TypeError: Cannot read property 'post' of undefined

I installed vue-resource in my bootstrap.js here:

window.Vue = require('vue');
require('vue-resource');

This solved the $http problem but now I get the post problem.

If there is any other information you need let me know.

Body:
I think there might be a problem with this.  Specifically, the this in created is likely not the same as the this in token.  Try ... this:

created: function created() {
  var self = this;

  self.stripe = StripeCheckout.configure({
    key: "my_key",
    image: "https://stripe.com/img/documentation/checkout/marketplace.png",
    locale: "auto",
    token: (token) => {
      self.stripeToken = token.id;
      self.stripeEmail = token.email;

      self.$http.post('/payment', self.$data).then(response => alert('Message'));
    }
  });
},

I know you're using arrow functions so this shouldn't be the case, but I'd give it a try anyways and see how it goes.


问:
How to count vowels and consonants and capitalizing first letter in a string while output using a method and return result
If a user enters a string:  hello there

it should output

```<code>Hello has 2 vowels
There has 3 consonants.
</code>```

I know this is a fairly simple code but I am getting too many ideas and getting confused.
I need a to make sure I have 2 methods for numberofVowels and capitalizeWord and both returns a result

I am getting an error and I am still trying to figure out to capitalize after I got counting vowels work

```<code>import java.util.Scanner;

public class Hwk9
{
        public static void main (String args[])
        {
                Scanner stdin = new Scanner(System.in);
                String string1;
                System.out.println("Enter a string");
                string1 = stdin.nextLine();
                string1 = string1.toLowerCase();

        }
        public static int numberVowels(String string1)
        {

                int count = 0;
                int vowels = 0;
                int consonants = 0;
                for (int i = 0; i < string1.length(); i++)
                {
                        char ch = string1.charAt(i);
                        if (ch == 'a' || ch == 'e' || ch == 'i' ||
                                        ch == 'o' || ch == 'u')
                        {
                                vowels++;
                        }
                        else
                        {
                                consonants++;
                        }
                }
        }
}
</code>```

答:
This looks way simple than above answers. It gets the input, converts it to lowercase then to an array of characters. A simple for loop will do the trick onwards. </p>

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

public class FindVowelsConsonents {

  public static void main(String[] args) {
    int vowels_count = 0;
    int consonents_count = 0;
    Scanner sc = new Scanner(System.in);
    String str = sc.nextLine();
    String str2 = str.toLowerCase();
    char[] chr = str2.toCharArray();

    for(int i=0;i<chr.length;i++){
        if(chr[i] == 'a' || chr[i]== 'e' || chr[i] == 'i' ||
                              chr[i] == 'o' || chr[i] == 'u')
            vowels_count++;
        else
            consonents_count++;
    }

    System.out.println(vowels_count+ " "+consonents_count);
    sc.close();
   }
}
</code>```

Body:
If a user enters a string:  hello there

it should output

Hello has 2 vowels
There has 3 consonants.

I know this is a fairly simple code but I am getting too many ideas and getting confused.
I need a to make sure I have 2 methods for numberofVowels and capitalizeWord and both returns a result

I am getting an error and I am still trying to figure out to capitalize after I got counting vowels work

import java.util.Scanner;

public class Hwk9
{
        public static void main (String args[])
        {
                Scanner stdin = new Scanner(System.in);
                String string1;
                System.out.println("Enter a string");
                string1 = stdin.nextLine();
                string1 = string1.toLowerCase();

        }
        public static int numberVowels(String string1)
        {

                int count = 0;
                int vowels = 0;
                int consonants = 0;
                for (int i = 0; i < string1.length(); i++)
                {
                        char ch = string1.charAt(i);
                        if (ch == 'a' || ch == 'e' || ch == 'i' ||
                                        ch == 'o' || ch == 'u')
                        {
                                vowels++;
                        }
                        else
                        {
                                consonants++;
                        }
                }
        }
}

Body:
This looks way simple than above answers. It gets the input, converts it to lowercase then to an array of characters. A simple for loop will do the trick onwards.

import java.util.*;

public class FindVowelsConsonents {

  public static void main(String[] args) {
    int vowels_count = 0;
    int consonents_count = 0;
    Scanner sc = new Scanner(System.in);
    String str = sc.nextLine();
    String str2 = str.toLowerCase();
    char[] chr = str2.toCharArray();

    for(int i=0;i<chr.length;i++){
        if(chr[i] == 'a' || chr[i]== 'e' || chr[i] == 'i' ||
                              chr[i] == 'o' || chr[i] == 'u')
            vowels_count++;
        else
            consonents_count++;
    }

    System.out.println(vowels_count+ " "+consonents_count);
    sc.close();
   }
}


问:
Testing will paginate gem with Rspec/Capybara
In my application there is an admin part, which is restricted to superadmins (users with a property superadmin: true). I've got a shop list, which I want to get paginated and tested.

When debugging the current code with save_and_open_page I get a blank page. If I log in not as a superadmin, I get redirected to application's root and when trying to debug with save_and_open_page is see the root page.. If I do not log in at all, then I'll get redirected to the sign in page. So the basic functionality should work.

I'm having no clue why it does not work with superadmin and why I do not see the shops list when debugging with save_and_open_page.

This is my spec/controllers/shops_controller_spec.rb (copied basically from here) :

```<code>require 'rails_helper'

RSpec.describe Admin::ShopsController, type: :controller do

  context "GET methods" do

    describe "#index action" do
      before(:all) {
        amount = Rails.application.config.page_size
        amount.times { FactoryGirl.create(:shop) }
      }

      before(:each) {
        login_as(FactoryGirl.create(:user, superadmin: true), :scope => :user)
      }

      context "with entries == config.page_size" do
        it "has no second page" do
          get :index
          expect(response).not_to have_selector("a", :href => "/shops?page=2", :content => "2")
          # visit admin_shops_path
          # expect(page).to have_no_xpath("//*[@class='pagination']//a[text()='2']")
        end
      end

      context "with entries > config.page_size" do
        before { FactoryGirl.create(:shop) }

        it "has a second page with too many entries" do
          visit "/admin/shops"
          save_and_open_page
          expect(page).to have_xpath("//*[@class='pagination']//a[text()='2']")
        end

        it "correctly redirects to next page" do
          visit admin_shops_path
          find("//*[@class='pagination']//a[text()='2']").click
          expect(page.status_code).to eq(200)
        end
      end
    end
  end
end
</code>```

As you can see, I tried to test in different ways (the "expect block" is taken from this SO-question), but none of them work. Using get :index I receive

```<code>Admin::ShopsController GET methods #index action with entries == config.page_size has no second page
     Failure/Error: expect(page).not_to have_selector("a", :href => "/shops?page=2", :content => "2")

     ArgumentError:
       invalid keys :href, :content, should be one of :count, :minimum, :maximum, :between, :text, :id, :class, :visible, :exact, :exact_text, :match, :wait, :filter_set
</code>```

Here is my AdminController.rb if it helps:

```<code>class AdminController < ApplicationController
    layout 'admin'

  before_action :authenticate_user!, :verify_is_superadmin

    before_action :set_locale
    before_action :get_breadcrumbs

    private

    def get_breadcrumbs
        splitted_url = request.original_fullpath.split("/")
        # Remove first object
        splitted_url.shift
        result = splitted_url.map { |element| element.humanize.capitalize }
        session[:breadcrumbs] = result
        # debug
    end

    def set_locale
        I18n.locale =  params[:locale] || session[:locale] || I18n.default_locale
        # session[:locale] = I18n.locale
    end

  def verify_is_superadmin
    (current_user.nil?) ? redirect_to(root_path) : (redirect_to(root_path) unless current_user.superadmin?)
  end

end
</code>```

Update
Using Thomas' answer I ended up putting my code in spec/features and it looks like this right now:

```<code>require "rails_helper"

RSpec.feature "Widget management", :type => :feature do

  before(:each) {
    amount = Rails.application.config.page_size
    amount.times { FactoryGirl.create(:shop) }
  }

  before(:each) {
    login_as(FactoryGirl.create(:user, superadmin: true), :scope => :user)
  }

  scenario "with entries == config.page_size" do

    visit admin_shops_path
    #save_and_open_page
    expect(page).to have_no_xpath("//*[@class='pagination']//a[text()='2']")
  end

  scenario "with entries > config.page_size" do
    FactoryGirl.create(:shop)
    visit admin_shops_path
    expect(page).to have_xpath("//*[@class='pagination']//a[text()='2']")
  end

  scenario "with entries > config.page_size it correctly redirects to next page" do
    FactoryGirl.create(:shop)
    visit admin_shops_path
    find("//*[@class='pagination']//a[text()='2']").click
    expect(page.status_code).to eq(200)
  end
end
</code>```

Everything works!

答:
You've got a number of issues here.

Firstly the other SO question you linked to isn't using Capybara so copying its examples for matchers is wrong.

Secondly you are writing controller tests, not view tests or feature tests. controller tests don't render the page by default, so to test elements on the page you want to be writing either view tests or feature tests. Capybara is designed for feature tests and isn't designed for controller tests. This is why the default capybara/rspec configuration file only includes the Capybara DSL into tests of type 'feature'.  It also includes the Capybara RSpec matchers into view tests since they are useful with the rendered strings provided there.

Thirdly, you are mixing usage of get/response, and visit/page in the same file which just confuses things.

If you rewrite these as feature tests, then to check you don't have a link with a specific href in capybara you would do

```<code>expect(page).not_to have_link(href: '...')
</code>```

If you want to make sure that a link doesn't exist with specific text and a specific href

```<code>expect(page).not_to have_link('link text', href: '...')
</code>```

Note: that checks there is not a link with both the given text and the given href, there could still be links with the text or the href

Body:
In my application there is an admin part, which is restricted to superadmins (users with a property superadmin: true). I've got a shop list, which I want to get paginated and tested.

When debugging the current code with save_and_open_page I get a blank page. If I log in not as a superadmin, I get redirected to application's root and when trying to debug with save_and_open_page is see the root page.. If I do not log in at all, then I'll get redirected to the sign in page. So the basic functionality should work.

I'm having no clue why it does not work with superadmin and why I do not see the shops list when debugging with save_and_open_page.

This is my spec/controllers/shops_controller_spec.rb (copied basically from here) :

require 'rails_helper'

RSpec.describe Admin::ShopsController, type: :controller do

  context "GET methods" do

    describe "#index action" do
      before(:all) {
        amount = Rails.application.config.page_size
        amount.times { FactoryGirl.create(:shop) }
      }

      before(:each) {
        login_as(FactoryGirl.create(:user, superadmin: true), :scope => :user)
      }

      context "with entries == config.page_size" do
        it "has no second page" do
          get :index
          expect(response).not_to have_selector("a", :href => "/shops?page=2", :content => "2")
          # visit admin_shops_path
          # expect(page).to have_no_xpath("//*[@class='pagination']//a[text()='2']")
        end
      end

      context "with entries > config.page_size" do
        before { FactoryGirl.create(:shop) }

        it "has a second page with too many entries" do
          visit "/admin/shops"
          save_and_open_page
          expect(page).to have_xpath("//*[@class='pagination']//a[text()='2']")
        end

        it "correctly redirects to next page" do
          visit admin_shops_path
          find("//*[@class='pagination']//a[text()='2']").click
          expect(page.status_code).to eq(200)
        end
      end
    end
  end
end

As you can see, I tried to test in different ways (the "expect block" is taken from this SO-question), but none of them work. Using get :index I receive

Admin::ShopsController GET methods #index action with entries == config.page_size has no second page
     Failure/Error: expect(page).not_to have_selector("a", :href => "/shops?page=2", :content => "2")

     ArgumentError:
       invalid keys :href, :content, should be one of :count, :minimum, :maximum, :between, :text, :id, :class, :visible, :exact, :exact_text, :match, :wait, :filter_set

Here is my AdminController.rb if it helps:

class AdminController < ApplicationController
    layout 'admin'

  before_action :authenticate_user!, :verify_is_superadmin

    before_action :set_locale
    before_action :get_breadcrumbs

    private

    def get_breadcrumbs
        splitted_url = request.original_fullpath.split("/")
        # Remove first object
        splitted_url.shift
        result = splitted_url.map { |element| element.humanize.capitalize }
        session[:breadcrumbs] = result
        # debug
    end

    def set_locale
        I18n.locale =  params[:locale] || session[:locale] || I18n.default_locale
        # session[:locale] = I18n.locale
    end

  def verify_is_superadmin
    (current_user.nil?) ? redirect_to(root_path) : (redirect_to(root_path) unless current_user.superadmin?)
  end

end

Update
Using Thomas' answer I ended up putting my code in spec/features and it looks like this right now:

require "rails_helper"

RSpec.feature "Widget management", :type => :feature do

  before(:each) {
    amount = Rails.application.config.page_size
    amount.times { FactoryGirl.create(:shop) }
  }

  before(:each) {
    login_as(FactoryGirl.create(:user, superadmin: true), :scope => :user)
  }

  scenario "with entries == config.page_size" do

    visit admin_shops_path
    #save_and_open_page
    expect(page).to have_no_xpath("//*[@class='pagination']//a[text()='2']")
  end

  scenario "with entries > config.page_size" do
    FactoryGirl.create(:shop)
    visit admin_shops_path
    expect(page).to have_xpath("//*[@class='pagination']//a[text()='2']")
  end

  scenario "with entries > config.page_size it correctly redirects to next page" do
    FactoryGirl.create(:shop)
    visit admin_shops_path
    find("//*[@class='pagination']//a[text()='2']").click
    expect(page.status_code).to eq(200)
  end
end

Everything works!

Body:
You've got a number of issues here.

Firstly the other SO question you linked to isn't using Capybara so copying its examples for matchers is wrong.

Secondly you are writing controller tests, not view tests or feature tests. controller tests don't render the page by default, so to test elements on the page you want to be writing either view tests or feature tests. Capybara is designed for feature tests and isn't designed for controller tests. This is why the default capybara/rspec configuration file only includes the Capybara DSL into tests of type 'feature'.  It also includes the Capybara RSpec matchers into view tests since they are useful with the rendered strings provided there.

Thirdly, you are mixing usage of get/response, and visit/page in the same file which just confuses things.

If you rewrite these as feature tests, then to check you don't have a link with a specific href in capybara you would do

expect(page).not_to have_link(href: '...')

If you want to make sure that a link doesn't exist with specific text and a specific href

expect(page).not_to have_link('link text', href: '...')

Note: that checks there is not a link with both the given text and the given href, there could still be links with the text or the href


问:
Need Help in send news letter using PHP mail function
Need your help in over coming the following issues.

i need to send opt-in newsletters to the user. But using "gmail SMTP", i will not be able to send more than 400 mails per day.

Even if i use the mail option given in the shared server, i will not be able to send mails more than 300 mails per day.

Can you please suggest any other way i can handle this issue. Is it possible to use PHP mail functions? are there any limitations in sending the number of mails to the users.

can a server control the mails sent using PHP mail function.

Thanks for reading.

thanks a lot

答:
The limitation on the number of mails you can send per day/hour is set by your SMTP server. In case of the mail() function, it is once again set by your host. If you wish to remove this limitation, generally you would:

Talk to your host's tech support and
ask them to raise the limit. Some
hosts like Fatcow raise your limit
from 500 to about 5000 (don't remember the exact numbers).

You can buy a dedicated virtual
server with no such restriction,
where the limit would only be the
speed at which you could send your
emails.

You can try newsletter mailing
software/add-ons like
ConstantContact that help you manage
your newsletters effectively.