问:
How to get selected word index in Textbox in jQuery/Javascript

I am trying to get the index of selected word on mouse click from the textbox using jQuery.

I should get an index of the word on click like this:

```<code>WIFI -> 0
, -> 1
Parking -> 2
Available -> 3
! -> 4
! -> 5
Internet -> 6
Includes -> 7
? -> 8
? -> 9
. -> 10
IS -> 11
Internet -> 12
Working -> 13
</code>```

So on selection of Internet it should return me 12 as index position.

Currently I am using the using the following approach, but using this approach I am getting only the selected word's character position.

```<code>$("#idTable1 > tbody > tr").on('click', function (e)
{
var start = document.getElementById("inputTxt").selectionStart;
var end = document.getElementById("inputTxt").selectionEnd;
</code>```

But on click of the word I should get the index of the tokenized word in the sentence.

Any pointers would be helpful to solve this.

答:
You could try to split the string in the textbox by " " and then using var start = document.getElementById("inputTxt").selectionStart; calculate which element of your array contains the word you are looking for...

```<code>var arr = Split(document.getElementById("inputTxt").value, " ");
var start = document.getElementById("inputTxt").selectionStart;
var arrpos = 0;
var idx = 0;
for(idx=0; arrpos<start & idx < arr.lenght; idx++){
    arrpos += arr[idx].lenght;
}
return idx;
</code>```

Body:
I am trying to get the index of selected word on mouse click from the textbox using jQuery.

I should get an index of the word on click like this:

WIFI -> 0
, -> 1
Parking -> 2
Available -> 3
! -> 4
! -> 5
Internet -> 6
Includes -> 7
? -> 8
? -> 9
. -> 10
IS -> 11
Internet -> 12
Working -> 13

So on selection of Internet it should return me 12 as index position.

Currently I am using the using the following approach, but using this approach I am getting only the selected word's character position.

$("#idTable1 > tbody > tr").on('click', function (e)
{
var start = document.getElementById("inputTxt").selectionStart;
var end = document.getElementById("inputTxt").selectionEnd;

But on click of the word I should get the index of the tokenized word in the sentence.

Any pointers would be helpful to solve this.

Body:
You could try to split the string in the textbox by " " and then using var start = document.getElementById("inputTxt").selectionStart; calculate which element of your array contains the word you are looking for...

var arr = Split(document.getElementById("inputTxt").value, " ");
var start = document.getElementById("inputTxt").selectionStart;
var arrpos = 0;
var idx = 0;
for(idx=0; arrpos<start & idx < arr.lenght; idx++){
    arrpos += arr[idx].lenght;
}
return idx;


来源: stackexchange

问:
Rotating divs on click
I am hope someone is able to help. I have been struggling with this for a couple of days now. I am using jQuery to rotate divs on click. It worked until I needed two functionalities on one page. So, I have two groups of divs to rotate in two places on one page and it is rotating both groups regardless of where I click. For example, I am using arrows to rotate div content and if I use the second set of arrows it is rotating both sets of div content at the same time. I would like these two to be independent - be able to rotate one group of divs without the other.

    $(document).ready(function(){
        $("#cslide-slides").cslide();
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    /*=Slides
    ----------------------------------------------- */
    .cslide-slides-master {
      overflow: hidden;
     }

    .cslide-slides-master:last-child {
      margin-bottom: 0; }

    .cslide-slides-container {
      visibility: hidden; }

    .cslide-slide {
      float: left;
     }
    /* prev next buttons */
    .cslide-prev-next {
      display: none;
      -webkit-touch-callout: none;
      -webkit-user-select: none;
      -khtml-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none; }

    .cslide-prev, .cslide-next {
      display: inline-block;
      float: right;

      padding: 10px 5px;

      cursor: pointer; }

    .cslide-prev.cslide-disabled:hover,
    .cslide-next.cslide-disabled:hover {
     }

    .cslide-disabled {
      opacity: 0.3; }</code>```

h4>Insert update headline here

Some text that describes this update

h4>Update 2

Some text that describes this update

Update 3

Some text that describes this update

h4>Update 4

Some text that describes this update

Update 5

Some text that describes this update

Insert update headline here

Some text that describes this update

Update 2

Some text that describes this update
Read more

Update 3

Some text that describes this update

Update 4

Some text that describes this update

Update 5

Some text that describes this update

答:
You need to initialize a separate instance of cslide for each slider. Also, IDs should be unique and not reused on the same page. That is what classes are for.

Create a unique ID for each slider and initialize with the class if the plugin allows. Otherwise, use the unique IDs.

```<code><script type="text/javascript" src="jquery.cslide.js"></script>
<script>
$( document ).ready( function () {
  $( '.cslide-slides-master' ).cslide();
} );
</script>
</code>```

FWIW use a newer slider, the one you are using has not been updated in 4 years.

ContentLicense: CC BY-SA 3.0

Title: Rotating divs on click

Body:
I am hope someone is able to help. I have been struggling with this for a couple of days now. I am using jQuery to rotate divs on click. It worked until I needed two functionalities on one page. So, I have two groups of divs to rotate in two places on one page and it is rotating both groups regardless of where I click. For example, I am using arrows to rotate div content and if I use the second set of arrows it is rotating both sets of div content at the same time. I would like these two to be independent - be able to rotate one group of divs without the other.

    $(document).ready(function(){
        $("#cslide-slides").cslide();
    });

    /*=Slides
    ----------------------------------------------- */
    .cslide-slides-master {
      overflow: hidden;
     }

    .cslide-slides-master:last-child {
      margin-bottom: 0; }

    .cslide-slides-container {
      visibility: hidden; }

    .cslide-slide {
      float: left;
     }
    /* prev next buttons */
    .cslide-prev-next {
      display: none;
      -webkit-touch-callout: none;
      -webkit-user-select: none;
      -khtml-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none; }

    .cslide-prev, .cslide-next {
      display: inline-block;
      float: right;

      padding: 10px 5px;

      cursor: pointer; }

    .cslide-prev.cslide-disabled:hover,
    .cslide-next.cslide-disabled:hover {
     }

    .cslide-disabled {
      opacity: 0.3; }

h4>Insert update headline here

Some text that describes this update

h4>Update 2

Some text that describes this update

Update 3

Some text that describes this update

h4>Update 4

Some text that describes this update

Update 5

Some text that describes this update

Insert update headline here

Some text that describes this update

Update 2

Some text that describes this update
Read more

Update 3

Some text that describes this update

Update 4

Some text that describes this update

Update 5

Some text that describes this update

Body:
You need to initialize a separate instance of cslide for each slider. Also, IDs should be unique and not reused on the same page. That is what classes are for.

Create a unique ID for each slider and initialize with the class if the plugin allows. Otherwise, use the unique IDs.

<script type="text/javascript" src="jquery.cslide.js"></script>
<script>
$( document ).ready( function () {
  $( '.cslide-slides-master' ).cslide();
} );
</script>

FWIW use a newer slider, the one you are using has not been updated in 4 years.


问:
Unable to get @Input() to work inside the constructor
I created two components, a parent and a child.

The parent has a member variable called applications:

```<code>import { Component, OnInit } from '@angular/core';
import { CoreService } from 'app/core.service';
import { Application } from 'app/models/application.model';

@Component({
  selector: 'app-applicationbrowser',
  templateUrl: './applicationbrowser.component.html',
  styleUrls: ['./applicationbrowser.component.css'],
  providers: [CoreService]
})
export class ApplicationbrowserComponent {
  applications: Application[] = [
    new Application(1, false, "beef"),
    new Application(2, false, "teef"),
    new Application(3, false, "feef")
  ];
  constructor() {

  }
}
</code>```

and uses the child component in its template:

```<code><div>
  <app-resourceitem *ngFor="let item of applications" [item]="item"></app-resourceitem>
</div>
</code>```

I assumed that this gets called for each application in my applications variable.

But the child component only ever has an 'undefined' item variable:

```<code>  @Input()
   item: any;
  constructor() {
    debugger;
    console.log(this.item); //item is always undefined....
  }
</code>```

What am I doing wrong?

答:
Don't try to access @Input() in the constructor, do it in the ngOnInit life-cycle hook. The constructor has nothing to do with the Angular application life-cycle. Change your code as,

```<code>@Component({
})
export class SomeChildComponent implements OnInit {
  @Input() item: any;
  constructor(){}
  ngOnInit() {
    console.log(this.item);
  }
}
</code>```

DEMO WITH STACKBLITZ

Body:
I created two components, a parent and a child.

The parent has a member variable called applications:

import { Component, OnInit } from '@angular/core';
import { CoreService } from 'app/core.service';
import { Application } from 'app/models/application.model';

@Component({
  selector: 'app-applicationbrowser',
  templateUrl: './applicationbrowser.component.html',
  styleUrls: ['./applicationbrowser.component.css'],
  providers: [CoreService]
})
export class ApplicationbrowserComponent {
  applications: Application[] = [
    new Application(1, false, "beef"),
    new Application(2, false, "teef"),
    new Application(3, false, "feef")
  ];
  constructor() {

  }
}

and uses the child component in its template:

  <app-resourceitem *ngFor="let item of applications" [item]="item"></app-resourceitem>

I assumed that this gets called for each application in my applications variable.

But the child component only ever has an 'undefined' item variable:

  @Input()
   item: any;
  constructor() {
    debugger;
    console.log(this.item); //item is always undefined....
  }

What am I doing wrong?

Body:
Don't try to access @Input() in the constructor, do it in the ngOnInit life-cycle hook. The constructor has nothing to do with the Angular application life-cycle. Change your code as,

@Component({
})
export class SomeChildComponent implements OnInit {
  @Input() item: any;
  constructor(){}
  ngOnInit() {
    console.log(this.item);
  }
}

DEMO WITH STACKBLITZ


问:
fibonacci series - recursive summation
Ok, I initially wrote a simple code to return the Fibonacci number from the series based on the user input..

n=5 will produce 3..

```<code>static int fibonacci(int n) {
        if (n == 1)
            return 0;
        else if (n == 2)
            return 1;
        else
            return (fibonacci(n - 1) + fibonacci(n - 2));
    }
</code>```

I was thinking of modifying the code to return the sum of the series rather than just returning the value from the series and while trying to do the sum I accidentally added 1 to the return statement and to my surprise, it returned the sum correctly.

The below code will return 7 for n=5.

I am not sure if this is a right way to calculate the sum...

I still couldn't figure out how the summation of the series works if I add 1. Can someone please explain??

```<code>static int fibonacci(int n) {
    if (n == 1)
        return 0;
    else if (n == 2)
        return 1;
    else
        return (fibonacci(n - 1) + fibonacci(n - 2)+(1));
}
</code>```

EDIT:

For Fibonacci series..0,1,1,2,3,5,8,13,21,34,55,89,144....

I tried for some random n

n=13

The function returns 376

0+1+1+2+3+5+8+13+21+34+55+89+144 = 376

n=10

The function returns 88

0+1+1+2+3+5+8+13+21+34= 88

答:
another approach to print Fibonacci series using recursive function.</p>

```<code>#include <iostream>

// 0 1 1 2 3 5 8 13...
//

void fibb (int idx, int curr = 0, int next = 0)
{
        std::cout << curr << ", ";
        if(!idx) return;
        if(curr == 0) {
                curr = 1;
                fibb(--idx, curr, next);
                return;
        }
        next += curr;
        fibb(--idx, next, curr);
}

int main()
{
        fibb(10);
}
</code>```

Title: fibonacci series - recursive summation

Body:
Ok, I initially wrote a simple code to return the Fibonacci number from the series based on the user input..

n=5 will produce 3..

static int fibonacci(int n) {
        if (n == 1)
            return 0;
        else if (n == 2)
            return 1;
        else
            return (fibonacci(n - 1) + fibonacci(n - 2));
    }

I was thinking of modifying the code to return the sum of the series rather than just returning the value from the series and while trying to do the sum I accidentally added 1 to the return statement and to my surprise, it returned the sum correctly.

The below code will return 7 for n=5.

I am not sure if this is a right way to calculate the sum...

I still couldn't figure out how the summation of the series works if I add 1. Can someone please explain??

static int fibonacci(int n) {
    if (n == 1)
        return 0;
    else if (n == 2)
        return 1;
    else
        return (fibonacci(n - 1) + fibonacci(n - 2)+(1));
}

EDIT:

For Fibonacci series..0,1,1,2,3,5,8,13,21,34,55,89,144....

I tried for some random n

n=13

The function returns 376

0+1+1+2+3+5+8+13+21+34+55+89+144 = 376

n=10

The function returns 88

0+1+1+2+3+5+8+13+21+34= 88

Body:
another approach to print Fibonacci series using recursive function.

#include <iostream>

// 0 1 1 2 3 5 8 13...
//

void fibb (int idx, int curr = 0, int next = 0)
{
        std::cout << curr << ", ";
        if(!idx) return;
        if(curr == 0) {
                curr = 1;
                fibb(--idx, curr, next);
                return;
        }
        next += curr;
        fibb(--idx, next, curr);
}

int main()
{
        fibb(10);
}


问:
Expressions as replacement for Frontpage... How use it for the simple minded?
I have been using Frontpage to build three less than professional but usable  web pages since the late 90’s.  MS no longer makes Frontpage, but others told me Expressions was their replacement.  So, I purchased it, but it looks very complex and it does not indicate to me how I can use it to maintain our web sites as my new computer with Windows 7 leaves Frontpage in the disappearing XP era.

Could someone tell me how to gently learn and step into Expressions enough to use it to maintain and update our web sites?

答:
This book might help:
Microsoft Expressions Visual QuickStart Guide

Although it goes against every code/programmer part in me, if you must use it, start with building a simple site before editing your older sites with it.  Also, always, always back everything up prior to making any changes.

ContentLicense: CC BY-SA 2.5


问:
SQL_NEED_DATA returned on simple integer
I modified one of my queries adding the 3rd parameter of type int and now trying to bind the integer value to it. The call is as follows:

```<code>ret = SQLBindParameter( stmt_tableProp, 3, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_INTEGER, 0, 0, &tableId, 0, &cbId );
</code>```

The value of the tableId is 171147655.

After adding this function the call to SQLExecute() starts returning SQL_NEED_DATA.

In the table the column is of the type integer.

I don't understand this - I am not passing big data to the query and I am not using BLOB.

Why am I getting the SQL_NEED_DATA?

If I take the 3 parameter out everything works again.

答:
This behaviour occurs if the last parameter of the SQLBindParameter function (StrLen_or_IndPtr) is set to SQL_DATA_AT_EXEC.

You should check the value of your cbId variable.

The error also seems to occur if you do not initialize the provided variable.

ContentLicense: CC BY-SA 4.0

Body:
I modified one of my queries adding the 3rd parameter of type int and now trying to bind the integer value to it. The call is as follows:

ret = SQLBindParameter( stmt_tableProp, 3, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_INTEGER, 0, 0, &tableId, 0, &cbId );

The value of the tableId is 171147655.

After adding this function the call to SQLExecute() starts returning SQL_NEED_DATA.

In the table the column is of the type integer.

I don't understand this - I am not passing big data to the query and I am not using BLOB.

Why am I getting the SQL_NEED_DATA?

If I take the 3 parameter out everything works again.


问:
Custom media type Consume rest call post operation
Need to consume rest service which as below. jersy client

```<code>@POST
@Produces("application/vnd.app.mail-service+json")
@Consumes("application/vnd.app.mail-service+json")
public TempResponse submit(TempRequest request) {

}
</code>```

Here the TempRequest is JAXB object.

To consume the service from javascript. have set the Accept and Content-Type as "application/vnd.app.mail-service+json" and sending the json request

```<code>{
  "TempRequest" :{
       "TempR1" : {
          "id" : "1212",
          "name" : "app",
        }
  }
}
</code>```

On submitting request, the received request body in the Service application is empty, if i try with "+xml" in both consumes and produces and change content type the request body is not empty.

Using Jersy-cleint and jax-rs with deployed in spring 4.3.7 application with jacson-core and asl - 1.19.3

答:
I'm not sure why are you using application/vnd.app.mail-service+json instead of application/json.

Same needs to be changed to

```<code>@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
</code>```

And I hope, you have similar changes in TempRequest class, which is a JAXB class.

```<code>@XmlRootElement(name="TempRequest")
@XmlAccessorType(XmlAccessType.FIELD)
public class TempRequest {

    @XmlElement(name="TempR1")
    private TempR1 temp;

    public TempRequest() {}

    // Getter and setter methods
    // ...
}
</code>```

Body:
Need to consume rest service which as below. jersy client

@POST
@Produces("application/vnd.app.mail-service+json")
@Consumes("application/vnd.app.mail-service+json")
public TempResponse submit(TempRequest request) {

}

Here the TempRequest is JAXB object.

To consume the service from javascript. have set the Accept and Content-Type as "application/vnd.app.mail-service+json" and sending the json request

{
  "TempRequest" :{
       "TempR1" : {
          "id" : "1212",
          "name" : "app",
        }
  }
}

On submitting request, the received request body in the Service application is empty, if i try with "+xml" in both consumes and produces and change content type the request body is not empty.

Using Jersy-cleint and jax-rs with deployed in spring 4.3.7 application with jacson-core and asl - 1.19.3

Body:
I'm not sure why are you using application/vnd.app.mail-service+json instead of application/json.

Same needs to be changed to

@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)

And I hope, you have similar changes in TempRequest class, which is a JAXB class.

@XmlRootElement(name="TempRequest")
@XmlAccessorType(XmlAccessType.FIELD)
public class TempRequest {

    @XmlElement(name="TempR1")
    private TempR1 temp;

    public TempRequest() {}

    // Getter and setter methods
    // ...
}


问:
Pandas - fast DataFrame transformation for neural nets ("gausrank")
Firstly, thank you for helping

I have large pandas DataFrame and I need fast "rank" transformation for each column:

1] if column is only 0-1, do nothing

2] else (for each column):

a] find unique values in the column

b] sort them

c] for each element of the column replace its value with the position in sort-unique "ranking" list

optional:

d] transform this new values to interval [-0.99, 0.99]

e] apply scipy.special.erfinv to each element (to get "normal" like distribution)

How can I do this with Pandas, when need to take care about speed..

Thanx

答:
Getting columns containing only 0 or 1:

```<code>columns_to_handle = (~df.isin([0,1])).any()
</code>```

Converting column type to categorical conveniently handles steps a, b and c:

```<code>df.some_column.astype('category').cat.codes
</code>```

Unfortunately this does seem to require a loop (through apply) over the columns, but if you don't have too many columns this should still be reasonably fast.

Rescaling can just be done by subtracting the minimum and dividing by the maximum for each column. However, as the minimum of each column is 0 already the first step is redundant.

Scipy's erfinv can just take a dataframe as input. However, the values must be between -1 and 1, exclusive. So the range will be epsilon smaller.

Combining it all

```<code>import pandas as pd
from scipy.special import erfinv

df = pd.DataFrame(
    [['a', 10, 0],
     ['b', 11, 1],
     ['c',  9, 0],
     ['d', 12, 1]],
    columns=['val1', 'val2', 'val3']
)

columns_to_handle = (~df.isin([0, 1])).any()

intermediate = df.loc[:, columns_to_handle].apply(lambda x: x.astype('category').cat.codes)

epsilon = 0.0001

# intermediate -= intermediate.min() # the minimum is 0 for every column already
intermediate /= intermediate.max()/(2-2*epsilon)
intermediate -= (1-epsilon)

intermediate = erfinv(intermediate)

result = pd.concat(
   [intermediate,
    df.loc[:, ~columns_to_handle]],
  axis=1)
</code>```

result being the following dataframe:

```<code>       val1      val2  val3
0 -2.751064 -0.304538     0
1 -0.304538  0.304538     1
2  0.304538 -2.751064     0
3  2.751064  2.751064     1
</code>```

Body:
Getting columns containing only 0 or 1:

columns_to_handle = (~df.isin([0,1])).any()

Converting column type to categorical conveniently handles steps a, b and c:

df.some_column.astype('category').cat.codes

Unfortunately this does seem to require a loop (through apply) over the columns, but if you don't have too many columns this should still be reasonably fast.

Rescaling can just be done by subtracting the minimum and dividing by the maximum for each column. However, as the minimum of each column is 0 already the first step is redundant.

Scipy's erfinv can just take a dataframe as input. However, the values must be between -1 and 1, exclusive. So the range will be epsilon smaller.

Combining it all

import pandas as pd
from scipy.special import erfinv

df = pd.DataFrame(
    [['a', 10, 0],
     ['b', 11, 1],
     ['c',  9, 0],
     ['d', 12, 1]],
    columns=['val1', 'val2', 'val3']
)

columns_to_handle = (~df.isin([0, 1])).any()

intermediate = df.loc[:, columns_to_handle].apply(lambda x: x.astype('category').cat.codes)

epsilon = 0.0001

# intermediate -= intermediate.min() # the minimum is 0 for every column already
intermediate /= intermediate.max()/(2-2*epsilon)
intermediate -= (1-epsilon)

intermediate = erfinv(intermediate)

result = pd.concat(
   [intermediate,
    df.loc[:, ~columns_to_handle]],
  axis=1)

result being the following dataframe:

       val1      val2  val3
0 -2.751064 -0.304538     0
1 -0.304538  0.304538     1
2  0.304538 -2.751064     0
3  2.751064  2.751064     1


问:
How to set file's default suffix in webpack-dev-server?
I use webpack-dev-server to server my project.Here is the question, When the browser send a request like http://localhost:9000/test/menuList,  acutally I want it to find http://localhost:9000/test/menuList.json. How should I do?

答:
You can try tweaking Webpack-dev-server proxy object pathRewrite property

```<code>devServer: {
    contentBase: <Your-Value>,
    proxy = {
        '/test/menuList': {
            target: http://localhost:9000/test/menuList,
            pathRewrite(req, options) {
                    return req + '.json';
            }
        }
    }
    ...
}
</code>```

Body:
You can try tweaking Webpack-dev-server proxy object pathRewrite property

devServer: {
    contentBase: <Your-Value>,
    proxy = {
        '/test/menuList': {
            target: http://localhost:9000/test/menuList,
            pathRewrite(req, options) {
                    return req + '.json';
            }
        }
    }
    ...
}


问:
Restart exception handling if one part fails
I have the following snippet:

```<code>def check1(n):
    if len(n) != 4:
        return raw_input("Enter 4 digits only")
    else:
        return True

def check2(n):
    if n.isdigit() != True:
        return raw_input("Enter digits only")
    else:
        return True

def check3(n):
    if len(set(str(n))) != 4:
        return raw_input("Enter non duplicate numbers only")
    else:
        return True

sturn = 1
lturn = 8

a = raw_input("Enter the 4 numbers you want to play with: ")

for turn in range(sturn, lturn):
    b = raw_input("Enter your guess: ")
    if (check1(b) != True or check2(b) != True or check3(b) != True):
        if check1(b) != True:
            print check1(b)
        elif check2(b) != True:
            print check2(b)
        elif check3(b) != True:
            print check3(b)
    else:
        print b
</code>```

How can I rewrite this such that if any of the check functions fail, it starts from the b = raw_input line again and retests all the checks.

UPDATE
I've improved the code after heeding the advice from keithjgrant and m1k3y02 but it doesn't work properly. If I enter '1' consecutively, it bounces between different exceptions instead of staying on the first check.

```<code>def checks(n):
    if len(n) != 4 or n.isdigit() != True or len(set(str(n))) != 4:
        return False
    else:
        return True

sturn = 1
lturn = 8

a = raw_input("Enter the 4 numbers you want to play with: ")

for turn in range(sturn, lturn):
    b = raw_input("Enter your guess: ")
    while checks(b) != True:
        if len(b) != 4:
            b = raw_input("Enter 4 digits only")
        if b.isdigit() != True:
            b = raw_input("Enter digits only")
        if len(set(str(b))) != 4:
            b = raw_input("Enter non duplicate numbers only")

    print b
</code>```

答:
Your question, as it stands, has nothing to do with exceptions. Try the following:

```<code>checks = [
    lambda n: (len(n)==4, "Enter 4 digits only."),
    lambda n: (n.isdigit(), "Enter digits only."),
    lambda n: (len(set(str(n)))==4, "Enter non duplicate numbers only.")
]

a = raw_input("Enter the 4 numbers you want to play with: ")

sturn = 1
lturn = 8
for turn in range(sturn, lturn):
    b = raw_input("Enter your guess: ")
    all_good = True

    for check in checks:
        good,msg = check(b)
        if not good:
            print msg
            all_good = False
            break

    if all_good:
        print "{0} is correct!".format(b)
        break
</code>```

You could rewrite it to use exceptions as follows:

```<code>class CheckError(Exception): pass

class WrongLengthError(CheckError): pass
def check1(n):
    if len(n) != 4:
        raise WrongLengthError("Enter 4 digits only.")

class NonDigitCharError(CheckError): pass
def check2(n):
    if not n.isdigit():
        raise NonDigitCharError("Enter digits only.")

class HasDuplicatesError(CheckError): pass
def check3(n):
    if len(set(str(n))) != 4:
        raise HasDuplicatesError("Enter non duplicate numbers only.")

a = raw_input("Enter the 4 numbers you want to play with: ")

sturn = 1
lturn = 8
for turn in range(sturn, lturn):
    b = raw_input("Enter your guess: ")

    try:
        for check in (check1, check2, check3):
            check(b)

        print "{0} is correct!".format(b)
        break
    except CheckError, c:
        print c
</code>```

Body:
I have the following snippet:

def check1(n):
    if len(n) != 4:
        return raw_input("Enter 4 digits only")
    else:
        return True

def check2(n):
    if n.isdigit() != True:
        return raw_input("Enter digits only")
    else:
        return True

def check3(n):
    if len(set(str(n))) != 4:
        return raw_input("Enter non duplicate numbers only")
    else:
        return True

sturn = 1
lturn = 8

a = raw_input("Enter the 4 numbers you want to play with: ")

for turn in range(sturn, lturn):
    b = raw_input("Enter your guess: ")
    if (check1(b) != True or check2(b) != True or check3(b) != True):
        if check1(b) != True:
            print check1(b)
        elif check2(b) != True:
            print check2(b)
        elif check3(b) != True:
            print check3(b)
    else:
        print b

How can I rewrite this such that if any of the check functions fail, it starts from the b = raw_input line again and retests all the checks.

UPDATE
I've improved the code after heeding the advice from keithjgrant and m1k3y02 but it doesn't work properly. If I enter '1' consecutively, it bounces between different exceptions instead of staying on the first check.

def checks(n):
    if len(n) != 4 or n.isdigit() != True or len(set(str(n))) != 4:
        return False
    else:
        return True

sturn = 1
lturn = 8

a = raw_input("Enter the 4 numbers you want to play with: ")

for turn in range(sturn, lturn):
    b = raw_input("Enter your guess: ")
    while checks(b) != True:
        if len(b) != 4:
            b = raw_input("Enter 4 digits only")
        if b.isdigit() != True:
            b = raw_input("Enter digits only")
        if len(set(str(b))) != 4:
            b = raw_input("Enter non duplicate numbers only")

    print b

Body:
Your question, as it stands, has nothing to do with exceptions. Try the following:

checks = [
    lambda n: (len(n)==4, "Enter 4 digits only."),
    lambda n: (n.isdigit(), "Enter digits only."),
    lambda n: (len(set(str(n)))==4, "Enter non duplicate numbers only.")
]

a = raw_input("Enter the 4 numbers you want to play with: ")

sturn = 1
lturn = 8
for turn in range(sturn, lturn):
    b = raw_input("Enter your guess: ")
    all_good = True

    for check in checks:
        good,msg = check(b)
        if not good:
            print msg
            all_good = False
            break

    if all_good:
        print "{0} is correct!".format(b)
        break

You could rewrite it to use exceptions as follows:

class CheckError(Exception): pass

class WrongLengthError(CheckError): pass
def check1(n):
    if len(n) != 4:
        raise WrongLengthError("Enter 4 digits only.")

class NonDigitCharError(CheckError): pass
def check2(n):
    if not n.isdigit():
        raise NonDigitCharError("Enter digits only.")

class HasDuplicatesError(CheckError): pass
def check3(n):
    if len(set(str(n))) != 4:
        raise HasDuplicatesError("Enter non duplicate numbers only.")

a = raw_input("Enter the 4 numbers you want to play with: ")

sturn = 1
lturn = 8
for turn in range(sturn, lturn):
    b = raw_input("Enter your guess: ")

    try:
        for check in (check1, check2, check3):
            check(b)

        print "{0} is correct!".format(b)
        break
    except CheckError, c:
        print c


问:
What is causing this nativescript installation error on Macbook Pro
I have installed, uninstalled, cleaned npm cache and reinstalled.  Still getting the following error and being new to MacBook Pro, I have no idea what is going on.

Johns-MBP:~ jbaird$ npm install -g nativescript npm WARN optional
  SKIPPING OPTIONAL DEPENDENCY: abbrev@1.1.0
  (node_modules/nativescript/node_modules/fsevents/node_modules/abbrev):
  npm WARN enoent SKIPPING OPTIONAL DEPENDENCY: ENOENT: no such file or
  directory, rename
  '/usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules/abbrev'
  -> '/usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules/.abbrev.DELETE'

npm ERR! path
  /usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules/ansi-regex
  npm ERR! code ENOENT npm ERR! errno -2 npm ERR! syscall rename npm
  ERR! enoent ENOENT: no such file or directory, rename
  '/usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules/ansi-regex'
  -> '/usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules/.ansi-regex.DELETE'
  npm ERR! enoent This is related to npm not being able to find a file.
  npm ERR! enoent

npm ERR! A complete log of this run can be found in: npm ERR!

  /Users/jbaird/.npm/_logs/2017-08-24T14_34_26_019Z-debug.log
  Johns-MBP:~ jbaird$

答:
I also got the same error.

I did simply removed nativescript module using sudo npm remove -g nativescript.

And now installed nativescript module using sudo npm install -g nativescript.


问:
Can I start a Spring Boot WAR with PropertiesLauncher?
I have a Spring  Boot 1.2 app packaged as a WAR because I need to be able to deploy the app in an app server.

I also want to configure an external path which will contain jars to be added to the classpath. After reading the Launcher documentation, I configured the build to use PropertiesLauncher to this end :

```<code><plugin>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-maven-plugin</artifactId>
  <configuration>
    ...
    <layout>ZIP</layout>
  </configuration>
</plugin>
</code>```

I tried to start the app with various combinations of this additional system property : -Dloader.path=lib/,lib-provided/,WEB-INF/classes,<my additional path>

But I always end up with this error :

```<code>java.lang.IllegalArgumentException: Invalid source folder C:\<path to my war>\<my war>.war
    at org.springframework.boot.loader.archive.ExplodedArchive.<init> ExplodedArchive.java:78)
    at org.springframework.boot.loader.archive.ExplodedArchive.<init>(ExplodedArchive.java:66)
    at org.springframework.boot.loader.PropertiesLauncher.addParentClassLoaderEntries(PropertiesLauncher.java:530)
    at org.springframework.boot.loader.PropertiesLauncher.getClassPathArchives(PropertiesLauncher.java:451)
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:60)
    at org.springframework.boot.loader.PropertiesLauncher.main(PropertiesLauncher.java:609)
</code>```

I looked at the source code and it seems that PropertiesLauncher can only handle jar archives (ending with ".jar" or ".zip") and "exploded archives" (not ending with the former)

Is it possible to do achieve what I want ? Am I doing it wrong ?

If it's not possible, which alternative is there ?

答:
If somebody end up here this might be useful:

```<code>java -cp yourSpringBootWebApp.war -Dloader.path=yourSpringBootWebApp.war!/WEB-INF/classes/,yourSpringBootWebApp.war!/WEB-INF/,externalLib.jar org.springframework.boot.loader.PropertiesLauncher
</code>```

(Spring-Boot 1.5.9)

https://docs.spring.io/spring-boot/docs/1.5.x/reference/html/executable-jar.html#executable-jar-launching

Body:
I have a Spring  Boot 1.2 app packaged as a WAR because I need to be able to deploy the app in an app server.

I also want to configure an external path which will contain jars to be added to the classpath. After reading the Launcher documentation, I configured the build to use PropertiesLauncher to this end :

<plugin>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-maven-plugin</artifactId>
  <configuration>
    ...
    <layout>ZIP</layout>
  </configuration>
</plugin>

I tried to start the app with various combinations of this additional system property : -Dloader.path=lib/,lib-provided/,WEB-INF/classes,<my additional path>

But I always end up with this error :

java.lang.IllegalArgumentException: Invalid source folder C:\<path to my war>\<my war>.war
    at org.springframework.boot.loader.archive.ExplodedArchive.<init> ExplodedArchive.java:78)
    at org.springframework.boot.loader.archive.ExplodedArchive.<init>(ExplodedArchive.java:66)
    at org.springframework.boot.loader.PropertiesLauncher.addParentClassLoaderEntries(PropertiesLauncher.java:530)
    at org.springframework.boot.loader.PropertiesLauncher.getClassPathArchives(PropertiesLauncher.java:451)
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:60)
    at org.springframework.boot.loader.PropertiesLauncher.main(PropertiesLauncher.java:609)

I looked at the source code and it seems that PropertiesLauncher can only handle jar archives (ending with ".jar" or ".zip") and "exploded archives" (not ending with the former)

Is it possible to do achieve what I want ? Am I doing it wrong ?

If it's not possible, which alternative is there ?

Body:
If somebody end up here this might be useful:

java -cp yourSpringBootWebApp.war -Dloader.path=yourSpringBootWebApp.war!/WEB-INF/classes/,yourSpringBootWebApp.war!/WEB-INF/,externalLib.jar org.springframework.boot.loader.PropertiesLauncher

(Spring-Boot 1.5.9)

https://docs.spring.io/spring-boot/docs/1.5.x/reference/html/executable-jar.html#executable-jar-launching


问:
AngularJS 1.6 - On a config phase $http defaults requestError, broadcast event to main scope?
I need to broadcast an event after receiving a $http.defaults request error (400 status code, mainly) but I cannot access $rootScope within config phase.

Code:

```<code>var app = angular.module('app', []);
app.config(['$httpProvider','$injector', function($httpProvider, $injector) {
    $httpProvider.interceptors.push(['$q', function($q) {
        return {
            'responseError': function (rejection) {
                /*
                Doesn't work:
                $rootScope = $injector.get("$rootScope");
                $rootScope.$emit("RESPONSE_ERROR");
                */
                return $q.reject(rejection);
            }
        };
    }]);
}]);
app.controller("Controller",function($scope){
    $scope.$on("RESPONSE_ERROR",function(event,params){
        alert("WORKING!");
    });
});
</code>```

Any suggestions? Thanks.

答:
The problem is caused by the fact that there are two different injectors, as explained in this answer. In the code above $injector is the one that was injected during config phase, it deals with service providers.

Another one should be injected during run phase in order to get access to service instances like $rootScope:

```<code>$httpProvider.interceptors.push(function($q, $injector) { ... });
</code>```

As another answer already explains, $rootScope can be injected into the interceptor directly. While $injector is a common way to avoid circular dependencies in interceptors and inject $http there.

Body:
I need to broadcast an event after receiving a $http.defaults request error (400 status code, mainly) but I cannot access $rootScope within config phase.

Code:

var app = angular.module('app', []);
app.config(['$httpProvider','$injector', function($httpProvider, $injector) {
    $httpProvider.interceptors.push(['$q', function($q) {
        return {
            'responseError': function (rejection) {
                /*
                Doesn't work:
                $rootScope = $injector.get("$rootScope");
                $rootScope.$emit("RESPONSE_ERROR");
                */
                return $q.reject(rejection);
            }
        };
    }]);
}]);
app.controller("Controller",function($scope){
    $scope.$on("RESPONSE_ERROR",function(event,params){
        alert("WORKING!");
    });
});

Any suggestions? Thanks.

Body:
The problem is caused by the fact that there are two different injectors, as explained in this answer. In the code above $injector is the one that was injected during config phase, it deals with service providers.

Another one should be injected during run phase in order to get access to service instances like $rootScope:

$httpProvider.interceptors.push(function($q, $injector) { ... });

As another answer already explains, $rootScope can be injected into the interceptor directly. While $injector is a common way to avoid circular dependencies in interceptors and inject $http there.


问:
SQL Remove row when other rows are subset, keep row when no subset
I have a data set of 300,000 rows, looking at harvested acreage in the United States. Some, but not all of my data is double counted and I am trying to remove the double counting. The data looks like this:

```<code>Year  | State  | Crop | Practice | Acres Harvested | Acres
-------------------------------------------------------------
2008      1      1       1         1000 or more       40
2008      1      1       1         1000 to 1999       10
2008      1      1       1         2000 to 2999       30
2008      2      1       1         1000 or more       87
2008      3      2       2         1.0 to 14.9        15
2008      3      2       2         1.0 to 4.9          5
2008      3      2       2         5.0 to 14.9        10
</code>```

Some of the rows are subsets for other rows in the [Acres Harvested] column (rows 2 and 3 are a subset of row 1 and rows 6 and 7 are a subset of row 5). In situations where I have more detailed information for [Acres Harvested] (rows 2 and 3 provide more detail than row 1), I would like to keep the detailed information (row 2 and 3) and omit the general information (row 1). In other scenarios, I only have the general information (row 4), so that is what I will keep.

I am having trouble writing the code to omit the general information when the detailed information is present, but to keep the general information when the more detailed information does not exist.

I've been trying to write an "inner join" to join my table back with itself, but am unsure of how to omit rows when certain conditions are met. What I have:

```<code>SELECT *
FROM A
INNER JOIN (SELECT *
            FROM A
            GROUP BY [YEAR], [STATE], [CROP], [PRACTICE]
            HAVING COUNT (*) > 1) AS B

ON  A.Year     =    B.Year
AND A.State    =    B.State
AND A.Crop     =    B.Crop
AND A.Practice =    B.Practice
</code>```

And now I'm stuck...

Results should look like:

```<code>    Year  | State  | Crop | Practice | Acres Harvested | Acres
    -------------------------------------------------------------
    2008      1      1       1         1000 to 1999       10
    2008      1      1       1         2000 to 2999       30
    2008      2      1       1         1000 or more       87
    2008      3      2       2         1.0 to 4.9          5
    2008      3      2       2         5.0 to 14.9        10
</code>```

Appreciate any help!

答:
Assuming your criteria for "more detailed information" is records for a matched set that don't end in "or more" as I guessed in my comment, you can get your desired output this way.  You do the records sets with only one record and those with multiple records separately and UNION them instead of trying to do it with one SELECT.

```<code>SELECT A.*
FROM A
GROUP BY [YEAR], [STATE], [CROP], [PRACTICE]
HAVING
    COUNT (*) = 1

UNION

SELECT A.*
FROM A
INNER JOIN
    (SELECT [YEAR], [STATE], [CROP], [PRACTICE]
        FROM A
        GROUP BY [YEAR], [STATE], [CROP], [PRACTICE]
        HAVING
            COUNT (*) > 1
    ) AS B
ON  A.[Year]     =    B.[Year]
AND A.[State]    =    B.[State]
AND A.[Crop]     =    B.[Crop]
AND A.[Practice] =    B.[Practice]
WHERE [ACRES HARVESTED] not like '%%or more'
</code>```

If your criteria aren't what I guess just change the WHERE clause.

Given your updated sample data you're also going to have to check for overlapping number ranges.  This question has some options on how to do that: Discard existing dates that are included in the result, SQL Server.  You'll need to split your "X to Y" values into two numeric fields as well.

Body:
I have a data set of 300,000 rows, looking at harvested acreage in the United States. Some, but not all of my data is double counted and I am trying to remove the double counting. The data looks like this:

Year  | State  | Crop | Practice | Acres Harvested | Acres
-------------------------------------------------------------
2008      1      1       1         1000 or more       40
2008      1      1       1         1000 to 1999       10
2008      1      1       1         2000 to 2999       30
2008      2      1       1         1000 or more       87
2008      3      2       2         1.0 to 14.9        15
2008      3      2       2         1.0 to 4.9          5
2008      3      2       2         5.0 to 14.9        10

Some of the rows are subsets for other rows in the [Acres Harvested] column (rows 2 and 3 are a subset of row 1 and rows 6 and 7 are a subset of row 5). In situations where I have more detailed information for [Acres Harvested] (rows 2 and 3 provide more detail than row 1), I would like to keep the detailed information (row 2 and 3) and omit the general information (row 1). In other scenarios, I only have the general information (row 4), so that is what I will keep.

I am having trouble writing the code to omit the general information when the detailed information is present, but to keep the general information when the more detailed information does not exist.

I've been trying to write an "inner join" to join my table back with itself, but am unsure of how to omit rows when certain conditions are met. What I have:

SELECT *
FROM A
INNER JOIN (SELECT *
            FROM A
            GROUP BY [YEAR], [STATE], [CROP], [PRACTICE]
            HAVING COUNT (*) > 1) AS B

ON  A.Year     =    B.Year
AND A.State    =    B.State
AND A.Crop     =    B.Crop
AND A.Practice =    B.Practice

And now I'm stuck...

Results should look like:

    Year  | State  | Crop | Practice | Acres Harvested | Acres
    -------------------------------------------------------------
    2008      1      1       1         1000 to 1999       10
    2008      1      1       1         2000 to 2999       30
    2008      2      1       1         1000 or more       87
    2008      3      2       2         1.0 to 4.9          5
    2008      3      2       2         5.0 to 14.9        10

Appreciate any help!

Body:
Assuming your criteria for "more detailed information" is records for a matched set that don't end in "or more" as I guessed in my comment, you can get your desired output this way.  You do the records sets with only one record and those with multiple records separately and UNION them instead of trying to do it with one SELECT.

SELECT A.*
FROM A
GROUP BY [YEAR], [STATE], [CROP], [PRACTICE]
HAVING
    COUNT (*) = 1

UNION

SELECT A.*
FROM A
INNER JOIN
    (SELECT [YEAR], [STATE], [CROP], [PRACTICE]
        FROM A
        GROUP BY [YEAR], [STATE], [CROP], [PRACTICE]
        HAVING
            COUNT (*) > 1
    ) AS B
ON  A.[Year]     =    B.[Year]
AND A.[State]    =    B.[State]
AND A.[Crop]     =    B.[Crop]
AND A.[Practice] =    B.[Practice]
WHERE [ACRES HARVESTED] not like '%%or more'

If your criteria aren't what I guess just change the WHERE clause.

Given your updated sample data you're also going to have to check for overlapping number ranges.  This question has some options on how to do that: Discard existing dates that are included in the result, SQL Server.  You'll need to split your "X to Y" values into two numeric fields as well.


问:
Prevent partial argument matching
I have an R function:

```<code>myFunc <- function(x, base='') {
}
</code>```

I am now extending the function, allowing a set of arbitrary extra arguments:

```<code>myFunc <- function(x, base='', ...) {
}
</code>```

How may I disable partial argument matching on the base parameter? I cannot put the ... before base='' because I'd like to maintain backwards compatibility of the function (it is often called as myFunction('somevalue', 'someothervalue') without base being explicitly named).

I got stung by calling my function like so:

```<code>myFunc(x, b='foo')
</code>```

I want this to mean base='', b='foo', but R uses partial matching and assumes base='foo'.

Is there some code I can insert in myFunc to determine what argument names were passed in and only match the exact "base" to the base parameter, otherwise grouping it in as part of the ...?

答:
It is possible to use sys.call() to get access to function arguments as given by the caller. Care must be taken since sys.call() does not evaluate the arguments and instead gives you the expression of the call. This gets especially difficult when the function is called with ... as an argument: The sys.call() will only contain the ..., not their value. It is, however, possible to take the sys.call() and evaluate it as an argument list for another function, for example list(). This evaluates all promises and throws away some information, but I can't see how to get around this when trying to circumvent R's internal matching.

One idea would be to simulate strict matching. I appended a helper function that does exactly this if called as the first command in a function:

```<code>fun = function(x, base='', ...) {
  strictify()  # make matching strict

  list(x, base, ...)
}
</code>```

This filters out nonmatching args:

```<code>> fun(10, b = 20)
[[1]]
[1] 10

[[2]]
[1] ""

$b
[1] 20
</code>```

and should also work in most other cases (with or without ..., with arguments to the right of the ..., with argument default values). The only thing it does not work with is non-standard evaluation, e.g. when trying to get the expression of an argument using substitute(arg).

The Helper Function

```<code>strictify <- function() {
  # remove argument values from the function
  # since matching already happened
  parenv <- parent.frame()  # environment of the calling function
  rm(list=ls(parenv), envir=parenv)  # clear that environment

  # get the arguments
  scall <- sys.call(-1)  # 'call' of the calling function
  callingfun <- scall[[1]]
  scall[[1]] <- quote(`list`)
  args <- eval.parent(scall, 2)  # 'args' is now a list with all arguments

  # if none of the argument are named, we need to set the
  # names() of args explicitly
  if (is.null(names(args))) {
    names(args) <- rep("", length(args))
  }

  # get the function header ('formals') of the calling function
  callfun.object <- eval.parent(callingfun, 2)
  callfun.header <- formals(callfun.object)
  # create a dummy function that just gives us a link to its environment.
  # We will use this environment to access the parameter values. We
  # are not using the parameter values directly, since the default
  # parameter evaluation of R is pretty complicated.
  # (Consider fun <- function(x=y, y=x) { x } -- fun(x=3) and
  # fun(y=3) both return 3)
  dummyfun <- call("function", callfun.header, quote(environment()))
  dummyfun <- eval(dummyfun, envir=environment(callfun.object))
  parnames <- names(callfun.header)

  # Sort out the parameters that didn't match anything
  argsplit <- split(args, names(args) %in% c("", parnames))
  matching.args <- c(list(), argsplit$`TRUE`)
  nonmatching.arg.names <- names(argsplit$`FALSE`)

  # collect all arguments that match something (or are just
  # positional) into 'parenv'. If this includes '...', it will
  # be overwritten later.
  source.env <- do.call(dummyfun, matching.args)
  for (varname in ls(source.env, all.names=TRUE)) {
    parenv[[varname]] <- source.env[[varname]]
  }

  if (!"..." %in% parnames) {
    # Check if some parameters did not match. It is possible to get
    # here if an argument only partially matches.
    if (length(nonmatching.arg.names)) {
      stop(sprintf("Nonmatching arguments: %s",
          paste(nonmatching.arg.names, collapse=", ")))
    }
  } else {
    # we manually collect all arguments that fall into '...'. This is
    # not trivial. First we look how many arguments before the '...'
    # were not matched by a named argument:
    open.args <- setdiff(parnames, names(args))
    taken.unnamed.args <- min(which(open.args == "...")) - 1
    # We throw all parameters that are unmatched into the '...', but we
    # remove the first `taken.unnamed.args` from this, since they go on
    # filling the unmatched parameters before the '...'.
    unmatched <- args[!names(args) %in% parnames]
    unmatched[which(names(unmatched) == "")[seq_len(taken.unnamed.args)]] <- NULL
    # we can just copy the '...' from a dummy environment that we create
    # here.
    dotsenv <- do.call(function(...) environment(), unmatched)
    parenv[["..."]] <- dotsenv[["..."]]
  }
}
</code>```

It would also be possible to have a function that converts a normally matching function into a strictly matching function, e.g.

```<code>strict.fun = strictificate(fun)
</code>```

but that would use the same kinds of tricks.

Title: Prevent partial argument matching

Body:
I have an R function:

myFunc <- function(x, base='') {
}

I am now extending the function, allowing a set of arbitrary extra arguments:

myFunc <- function(x, base='', ...) {
}

How may I disable partial argument matching on the base parameter? I cannot put the ... before base='' because I'd like to maintain backwards compatibility of the function (it is often called as myFunction('somevalue', 'someothervalue') without base being explicitly named).

I got stung by calling my function like so:

myFunc(x, b='foo')

I want this to mean base='', b='foo', but R uses partial matching and assumes base='foo'.

Is there some code I can insert in myFunc to determine what argument names were passed in and only match the exact "base" to the base parameter, otherwise grouping it in as part of the ...?

Body:
It is possible to use sys.call() to get access to function arguments as given by the caller. Care must be taken since sys.call() does not evaluate the arguments and instead gives you the expression of the call. This gets especially difficult when the function is called with ... as an argument: The sys.call() will only contain the ..., not their value. It is, however, possible to take the sys.call() and evaluate it as an argument list for another function, for example list(). This evaluates all promises and throws away some information, but I can't see how to get around this when trying to circumvent R's internal matching.

One idea would be to simulate strict matching. I appended a helper function that does exactly this if called as the first command in a function:

fun = function(x, base='', ...) {
  strictify()  # make matching strict

  list(x, base, ...)
}

This filters out nonmatching args:

> fun(10, b = 20)
[[1]]
[1] 10

[[2]]
[1] ""

$b
[1] 20

and should also work in most other cases (with or without ..., with arguments to the right of the ..., with argument default values). The only thing it does not work with is non-standard evaluation, e.g. when trying to get the expression of an argument using substitute(arg).

The Helper Function

strictify <- function() {
  # remove argument values from the function
  # since matching already happened
  parenv <- parent.frame()  # environment of the calling function
  rm(list=ls(parenv), envir=parenv)  # clear that environment

  # get the arguments
  scall <- sys.call(-1)  # 'call' of the calling function
  callingfun <- scall[[1]]
  scall[[1]] <- quote(`list`)
  args <- eval.parent(scall, 2)  # 'args' is now a list with all arguments

  # if none of the argument are named, we need to set the
  # names() of args explicitly
  if (is.null(names(args))) {
    names(args) <- rep("", length(args))
  }

  # get the function header ('formals') of the calling function
  callfun.object <- eval.parent(callingfun, 2)
  callfun.header <- formals(callfun.object)
  # create a dummy function that just gives us a link to its environment.
  # We will use this environment to access the parameter values. We
  # are not using the parameter values directly, since the default
  # parameter evaluation of R is pretty complicated.
  # (Consider fun <- function(x=y, y=x) { x } -- fun(x=3) and
  # fun(y=3) both return 3)
  dummyfun <- call("function", callfun.header, quote(environment()))
  dummyfun <- eval(dummyfun, envir=environment(callfun.object))
  parnames <- names(callfun.header)

  # Sort out the parameters that didn't match anything
  argsplit <- split(args, names(args) %in% c("", parnames))
  matching.args <- c(list(), argsplit$`TRUE`)
  nonmatching.arg.names <- names(argsplit$`FALSE`)

  # collect all arguments that match something (or are just
  # positional) into 'parenv'. If this includes '...', it will
  # be overwritten later.
  source.env <- do.call(dummyfun, matching.args)
  for (varname in ls(source.env, all.names=TRUE)) {
    parenv[[varname]] <- source.env[[varname]]
  }

  if (!"..." %in% parnames) {
    # Check if some parameters did not match. It is possible to get
    # here if an argument only partially matches.
    if (length(nonmatching.arg.names)) {
      stop(sprintf("Nonmatching arguments: %s",
          paste(nonmatching.arg.names, collapse=", ")))
    }
  } else {
    # we manually collect all arguments that fall into '...'. This is
    # not trivial. First we look how many arguments before the '...'
    # were not matched by a named argument:
    open.args <- setdiff(parnames, names(args))
    taken.unnamed.args <- min(which(open.args == "...")) - 1
    # We throw all parameters that are unmatched into the '...', but we
    # remove the first `taken.unnamed.args` from this, since they go on
    # filling the unmatched parameters before the '...'.
    unmatched <- args[!names(args) %in% parnames]
    unmatched[which(names(unmatched) == "")[seq_len(taken.unnamed.args)]] <- NULL
    # we can just copy the '...' from a dummy environment that we create
    # here.
    dotsenv <- do.call(function(...) environment(), unmatched)
    parenv[["..."]] <- dotsenv[["..."]]
  }
}

It would also be possible to have a function that converts a normally matching function into a strictly matching function, e.g.

strict.fun = strictificate(fun)

but that would use the same kinds of tricks.


问:
How to convert multiple arrays into one array of multiple objects?
Given the following arrays:

```<code>let x = [a, b, c, d];
let y = [e, f, g, h];
let w = [i, j, k, l];
</code>```

How to generated a new array of objects that look like that:

```<code>let z = [
    {x: a, y: e, w: i},
    {x: b, y: f, w: j},
    {x: c, y: g, w: k},
    {x: d, y: h, w: l}
];
</code>```

This is what I came up so far:

```<code>for(var i; i < x.length; i++) {

    x = x[i];
    y = y[i];
    w = w[i];

    obj = {
        x: x,
        y: y,
        w: w
    };

    z = [];
    z.push(obj);
}
</code>```

Thanks!

答:
let items = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l" ];
for (let i = 0; i < items.length; i++)
  Object.defineProperty(window, items[i], {
    value: items[i],
    writable: false
  });
//The code above there is just to define the variables in your arrays.

let x = [a, b, c, d];
let y = [e, f, g, h];
let w = [i, j, k, l];

let keys = [ "x", "y", "w" ]; //This array contains the name for accessing to your arrays.
let dimension = Math.max(...keys.map(function(array) {
  return eval(array).length;
}));
let z = new Array(dimension);
for (let i = 0; i < dimension; i++) {
  let obj = {};
  for (let ii = 0; ii < keys.length; ii++) {
    let key = keys[ii];
    obj[key] = eval(key)[i];
  }
  z[i] = obj;
}

console.log(JSON.stringify(z));```

You can also look at this fiddle.

Body:
Given the following arrays:

let x = [a, b, c, d];
let y = [e, f, g, h];
let w = [i, j, k, l];

How to generated a new array of objects that look like that:

let z = [
    {x: a, y: e, w: i},
    {x: b, y: f, w: j},
    {x: c, y: g, w: k},
    {x: d, y: h, w: l}
];

This is what I came up so far:

for(var i; i < x.length; i++) {

    x = x[i];
    y = y[i];
    w = w[i];

    obj = {
        x: x,
        y: y,
        w: w
    };

    z = [];
    z.push(obj);
}

Thanks!

Body:
let items = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l" ];
for (let i = 0; i < items.length; i++)
  Object.defineProperty(window, items[i], {
    value: items[i],
    writable: false
  });
//The code above there is just to define the variables in your arrays.

let x = [a, b, c, d];
let y = [e, f, g, h];
let w = [i, j, k, l];

let keys = [ "x", "y", "w" ]; //This array contains the name for accessing to your arrays.
let dimension = Math.max(...keys.map(function(array) {
  return eval(array).length;
}));
let z = new Array(dimension);
for (let i = 0; i < dimension; i++) {
  let obj = {};
  for (let ii = 0; ii < keys.length; ii++) {
    let key = keys[ii];
    obj[key] = eval(key)[i];
  }
  z[i] = obj;
}

console.log(JSON.stringify(z));

You can also look at this fiddle.


问:
Excel VBA: Need to Delete Rows in which Cells contain a Date within 7 days of the current Date
I have tried this with using a r1c1 formula and autofilter.  I have also tried piecing together code I've found on the internet, but nothing is working properly.  I am very much an amateur looking for help, please.

I need the code to look in a specific column and delete all rows in which cells in that column are within 7 days of today's date.  So today's date 12/5/2017, I need to delete all rows containing dates 11/28 through 12/5.

This must always evaluate based on current date.  Any help is so greatly appreciated. Thanks

```<code>Sub DeleteLastContact()

Dim ws As Worksheet, cel As Range, compRng As Range

Set ws = ThisWorkbook.Worksheets("Data")
Set compRng = ws.UsedRange.Columns("AE")

Dim delRng As Range, tmpVal As Date

For Each cel In compRng.Cells
Debug.Print cel.value
    tmpVal = cel.value
    If tmpVal < Date - 7 Then
        If delRng Is Nothing Then
            Set delRng = cel
        Else
            Set delRng = Union(cel, delRng)
        End If
    End If
Next cel

If Not delRng Is Nothing Then delRng.EntireRow.Delete

End Sub
</code>```

答:
This is untested, let me know if you have errors.

You can iterate through all cells in column AE, add each cell that meets your criteria to a special range, then at the end delete all rows in your special range.

```<code>Sub DeleteLastContact()

    Dim ws As Worksheet, cel As Range, compRng As Range
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    Set compRng = ws.UsedRange.Columns("AE")

    Dim delRng As Range, tmpVal As Date

    For Each cel In compRng.Cells
        tmpVal = cel.Value
        If tmpVal < Date - 7 Then
            If delRng Is Nothing Then
                Set delRng = cel
            Else
                Set delRng = Union(cel, delRng)
            End If
        End If
    Next cel

    If Not delRng Is Nothing Then delRng.EntireRow.Delete

End Sub
</code>```

Body:
I have tried this with using a r1c1 formula and autofilter.  I have also tried piecing together code I've found on the internet, but nothing is working properly.  I am very much an amateur looking for help, please.

I need the code to look in a specific column and delete all rows in which cells in that column are within 7 days of today's date.  So today's date 12/5/2017, I need to delete all rows containing dates 11/28 through 12/5.

This must always evaluate based on current date.  Any help is so greatly appreciated. Thanks

Sub DeleteLastContact()

Dim ws As Worksheet, cel As Range, compRng As Range

Set ws = ThisWorkbook.Worksheets("Data")
Set compRng = ws.UsedRange.Columns("AE")

Dim delRng As Range, tmpVal As Date

For Each cel In compRng.Cells
Debug.Print cel.value
    tmpVal = cel.value
    If tmpVal < Date - 7 Then
        If delRng Is Nothing Then
            Set delRng = cel
        Else
            Set delRng = Union(cel, delRng)
        End If
    End If
Next cel

If Not delRng Is Nothing Then delRng.EntireRow.Delete

End Sub

Body:
This is untested, let me know if you have errors.

You can iterate through all cells in column AE, add each cell that meets your criteria to a special range, then at the end delete all rows in your special range.

Sub DeleteLastContact()

    Dim ws As Worksheet, cel As Range, compRng As Range
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    Set compRng = ws.UsedRange.Columns("AE")

    Dim delRng As Range, tmpVal As Date

    For Each cel In compRng.Cells
        tmpVal = cel.Value
        If tmpVal < Date - 7 Then
            If delRng Is Nothing Then
                Set delRng = cel
            Else
                Set delRng = Union(cel, delRng)
            End If
        End If
    Next cel

    If Not delRng Is Nothing Then delRng.EntireRow.Delete

End Sub


问:
Audit or change logs on Google Cloud DNS?
We've been evaluating Google Cloud DNS and ran into this question: How do you keep track of changes?

For GCE an activity log is kept but I could not find any DNS related logs.

From the CLI there is some more:

```<code>$ gcloud dns record-sets changes list --zone="my-zone"
ID  START_TIME                STATUS
2   2016-02-18T09:29:35.314Z  done
1   2016-02-18T09:10:42.253Z  done
</code>```

and

```<code>$ gcloud dns record-sets changes describe 2 --zone="my-zone"
additions:
(yaml transaction file)
</code>```

Neither shows the ID/user/key of the system or person that performed the change. That is kind of essential for an audit trail.

How can I get an audit trail from Google Cloud, what command am I missing?

Or isn't it there (yet) and would I need to generate it via (very) limited access procedures, front-proxy or the like?

Much appreciated,

Gérard

答:
This ID of the actor that did the change is not available from the Cloud DNS API and probably never will.

Instead we are working on exposing it in the Stackdriver Logging logs. However there is no ETA for the release date.

Body:
We've been evaluating Google Cloud DNS and ran into this question: How do you keep track of changes?

For GCE an activity log is kept but I could not find any DNS related logs.

From the CLI there is some more:

$ gcloud dns record-sets changes list --zone="my-zone"
ID  START_TIME                STATUS
2   2016-02-18T09:29:35.314Z  done
1   2016-02-18T09:10:42.253Z  done

and

$ gcloud dns record-sets changes describe 2 --zone="my-zone"
additions:
(yaml transaction file)

Neither shows the ID/user/key of the system or person that performed the change. That is kind of essential for an audit trail.

How can I get an audit trail from Google Cloud, what command am I missing?

Or isn't it there (yet) and would I need to generate it via (very) limited access procedures, front-proxy or the like?

Much appreciated,

Gérard


问:
Objects are not valid as a React child (found: [object Promise])
I am trying to render a list of posts by mapping through an array. I've done this many times before but for some reason

```<code>renderPosts = async () => {
    try {
      let res = await axios.get('/posts');
      let posts = res.data;
      return  posts.map((post, i) => {
        return (
          <li key={i} className="list-group-item">{post.text}</li>
        );
      });
    } catch (err) {
      console.log(err);
    }
  }

  render () {
    return (
      <div>
        <ul className="list-group list-group-flush">
          {this.renderPosts()}
        </ul>
      </div>
    );
  }
</code>```

All I get is:

Uncaught Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

I've checked the data returned from renderPosts and it is an array with the correct values and no promises. What's going on here?

答:
this.renderPosts() will return a Promise not the actual data, and AFAIK Reactjs will not resolve Promises implicitly in render.

You need to do it like this

```<code>componentDidMount() {
  this.renderPosts();
}

renderPosts = async() => {
  try {
    const res = await axios.get('/posts');
    const posts = res.data;

    // this will re render the view with new data
    this.setState({
      Posts: posts
    });
  } catch (err) {
    console.log(err);
  }
}

render() {
  const posts = this.state.Posts?.map((post, i) => (
    <li key={i} className="list-group-item">{post.text}</li>
  ));

  return (
    <div>
      <ul className="list-group list-group-flush">
        {posts}
      </ul>
    </div>
  );
}
</code>```

Body:
I am trying to render a list of posts by mapping through an array. I've done this many times before but for some reason

renderPosts = async () => {
    try {
      let res = await axios.get('/posts');
      let posts = res.data;
      return  posts.map((post, i) => {
        return (

{post.text}

        );
      });
    } catch (err) {
      console.log(err);
    }
  }

  render () {
    return (

          {this.renderPosts()}

    );
  }

All I get is:

Uncaught Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

I've checked the data returned from renderPosts and it is an array with the correct values and no promises. What's going on here?

Body:
this.renderPosts() will return a Promise not the actual data, and AFAIK Reactjs will not resolve Promises implicitly in render.

You need to do it like this

componentDidMount() {
  this.renderPosts();
}

renderPosts = async() => {
  try {
    const res = await axios.get('/posts');
    const posts = res.data;

    // this will re render the view with new data
    this.setState({
      Posts: posts
    });
  } catch (err) {
    console.log(err);
  }
}

render() {
  const posts = this.state.Posts?.map((post, i) => (
    <li key={i} className="list-group-item">{post.text}</li>
  ));

  return (
    <div>
      <ul className="list-group list-group-flush">
        {posts}
      </ul>
    </div>
  );
}


问:
how to find the first repeated occurance of the character inside the same string in c
How do I get the first occurance of the repeated character to print only that character.it doesnt matter with it should be case sensitive or insensitive.
e.g For input= "opuott" Answer=o/O
        input= "kuttu" Answer=t/T</p>

```<code>#include<stdio.h>
#include<string.h>
int main(){
        int i,j,diff=0,min=0;
        char arr[100],var;
        printf("Enter the string to check for: ");
        scanf("%s",&arr);
        for(i=0;i<strlen(arr);i++){
                arr[i]=toupper(arr[i]);
                printf("%c ",arr[i]);
        }
        printf("\n");
        for(i=0;i<strlen(arr);i++){
                for(j=i+1;j<strlen(arr);j++){
                        if(arr[i]==arr[j]){
                                diff=j-i;
                                //THIS IF BLOCK IS USED FOR FIRST CONDITION FAILURE OF MIN AND DIFFERENCE
                                if(diff > min){
                                        min=diff;
                                        var=arr[i];
                                }
                                //THIS ELSE BLOCK IS USED FOR REGULAR CHECK FOR THE MIN AND DIFF AND ADJUST MIN TO DIFF ACCORDINGLY
                                else if(diff < min){
                                        min=diff;
                                        var=arr[i];
                                }
                        }
                }
        }
        printf("Final Answer : %c\n",var);
        return 0;
}
</code>```

答:
Something like</p>

```<code>std::string input;
std::cin>>input;
std::regex re("(.).*\\1");
std::smatch m;
if (std::regex_search(input,m,re)){
    std::cout << "Repeated " << m[0].str()[0] << "\n";
else
    std::cout << "No repeat\n";
</code>```

Body:
How do I get the first occurance of the repeated character to print only that character.it doesnt matter with it should be case sensitive or insensitive.
e.g For input= "opuott" Answer=o/O
        input= "kuttu" Answer=t/T

#include<stdio.h>
#include<string.h>
int main(){
        int i,j,diff=0,min=0;
        char arr[100],var;
        printf("Enter the string to check for: ");
        scanf("%s",&arr);
        for(i=0;i<strlen(arr);i++){
                arr[i]=toupper(arr[i]);
                printf("%c ",arr[i]);
        }
        printf("\n");
        for(i=0;i<strlen(arr);i++){
                for(j=i+1;j<strlen(arr);j++){
                        if(arr[i]==arr[j]){
                                diff=j-i;
                                //THIS IF BLOCK IS USED FOR FIRST CONDITION FAILURE OF MIN AND DIFFERENCE
                                if(diff > min){
                                        min=diff;
                                        var=arr[i];
                                }
                                //THIS ELSE BLOCK IS USED FOR REGULAR CHECK FOR THE MIN AND DIFF AND ADJUST MIN TO DIFF ACCORDINGLY
                                else if(diff < min){
                                        min=diff;
                                        var=arr[i];
                                }
                        }
                }
        }
        printf("Final Answer : %c\n",var);
        return 0;
}

Body:
Something like

std::string input;
std::cin>>input;
std::regex re("(.).*\\1");
std::smatch m;
if (std::regex_search(input,m,re)){
    std::cout << "Repeated " << m[0].str()[0] << "\n";
else
    std::cout << "No repeat\n";


问:
Akka Stream - Pausable GraphStage (Akka 2.5.7)
I would like to write a GraphStage which can be paused/unpaused by sending a message from another actor.

The code snipped below shows a simple GraphStage which generates random numbers. When the stage gets materialized the GraphStageLogic sends a message (within preStart()) containing the StageActor to a supervisor. The supervisor keeps the stage's ActorRef and can therefore be used to control the stage.

```<code>object RandomNumberSource {
  case object Pause
  case object UnPause
}

class RandomNumberSource(supervisor: ActorRef) extends GraphStage[SourceShape[Int]] {

  val out: Outlet[Int] = Outlet("rnd.out")

  override val shape: SourceShape[Int] = SourceShape(out)

  override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = {
    new RandomNumberSourceLogic(shape)
  }

  private class RandomNumberSourceLogic(shape: Shape) extends GraphStageLogic(shape) with StageLogging {

    lazy val self: StageActor = getStageActor(onMessage)

    val numberGenerator: Random = Random
    var isPaused: Boolean = true

      override def preStart(): Unit = {
        supervisor ! AssignStageActor(self.ref)
      }

      setHandler(out, new OutHandler {
        override def onPull(): Unit = {
          if (!isPaused) {
            push(out, numberGenerator.nextInt())
            Thread.sleep(1000)
          }
        }
      })

      private def onMessage(x: (ActorRef, Any)): Unit =
      {
        x._2 match {
          case Pause =>
            isPaused = true
            log.info("Stream paused")
          case UnPause =>
            isPaused = false
            getHandler(out).onPull()
            log.info("Stream unpaused!")
          case _ =>
        }
      }
    }
}
</code>```

This is a very simple implementation of the supervisor actor:

```<code>object Supervisor {
  case class AssignStageActor(ref: ActorRef)
}

class Supervisor extends Actor with ActorLogging {

  var stageActor: Option[ActorRef] = None

  override def receive: Receive = {

    case AssignStageActor(ref) =>
      log.info("Stage assigned!")
      stageActor = Some(ref)
      ref ! Done

    case Pause =>
      log.info("Pause stream!")
      stageActor match {
        case Some(ref) => ref ! Pause
        case _ =>
      }

    case UnPause =>
      log.info("UnPause stream!")
      stageActor match {
        case Some(ref) => ref ! UnPause
        case _ =>
      }
  }
}
</code>```

I'm using the following application to run the stream:

```<code>object Application extends App {

  implicit val system = ActorSystem("my-actor-system")
  implicit val materializer = ActorMaterializer()

  val supervisor = system.actorOf(Props[Supervisor], "supervisor")

  val sourceGraph: Graph[SourceShape[Int], NotUsed] = new RandomNumberSource(supervisor)
  val randomNumberSource: Source[Int, NotUsed] = Source.fromGraph(sourceGraph)

  randomNumberSource.take(100).runForeach(println)

  println("Start stream by pressing any key")

  StdIn.readLine()

  supervisor ! UnPause

  StdIn.readLine()

  supervisor ! Pause

  StdIn.readLine()

  println("=== Terminating ===")
  system.terminate()
}
</code>```

When the application starts the stage ia in 'paused' state and does not produce any number. When i press a key my stage starts to emit numbers. But my problem is that all messages sent to the stage after it has been started are ignored. I can not pause the stage.

I'm interested in changing the behavior of a stage based on a message received from an actor, but all examples i found pass an actor's message into the stream.

Does somebody has a guess why my code does not work or has an idea how to build such a GraphStage?

Thank you very much!

答:
The Akka Stream Contrib project has a Valve stage that materializes a value that can pause and resume a flow. From the Scaladoc for this class:

Materializes into a Future of ValveSwitch which provides a the method flip that stops or restarts the flow of elements passing through the stage. As long as the valve is closed it will backpressure.

For example:

```<code>val (switchFut, seqSink) = Source(1 to 10)
  .viaMat(new Valve(SwitchMode.Close))(Keep.right)
  .toMat(Sink.seq)(Keep.both)
  .run()
</code>```

switchFut is a Future[ValveSwitch], and since the switch is closed initially, the valve backpressures and nothing is emitted downstream. To open the valve:

```<code>switchFut.onComplete {
  case Success(switch) =>
    switch.flip(SwitchMode.Open) // Future[Boolean]
  case _ =>
    log.error("the valve failed")
}
</code>```

More examples are in ValveSpec.

Body:
I would like to write a GraphStage which can be paused/unpaused by sending a message from another actor.

The code snipped below shows a simple GraphStage which generates random numbers. When the stage gets materialized the GraphStageLogic sends a message (within preStart()) containing the StageActor to a supervisor. The supervisor keeps the stage's ActorRef and can therefore be used to control the stage.

object RandomNumberSource {
  case object Pause
  case object UnPause
}

class RandomNumberSource(supervisor: ActorRef) extends GraphStage[SourceShape[Int]] {

  val out: Outlet[Int] = Outlet("rnd.out")

  override val shape: SourceShape[Int] = SourceShape(out)

  override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = {
    new RandomNumberSourceLogic(shape)
  }

  private class RandomNumberSourceLogic(shape: Shape) extends GraphStageLogic(shape) with StageLogging {

    lazy val self: StageActor = getStageActor(onMessage)

    val numberGenerator: Random = Random
    var isPaused: Boolean = true

      override def preStart(): Unit = {
        supervisor ! AssignStageActor(self.ref)
      }

      setHandler(out, new OutHandler {
        override def onPull(): Unit = {
          if (!isPaused) {
            push(out, numberGenerator.nextInt())
            Thread.sleep(1000)
          }
        }
      })

      private def onMessage(x: (ActorRef, Any)): Unit =
      {
        x._2 match {
          case Pause =>
            isPaused = true
            log.info("Stream paused")
          case UnPause =>
            isPaused = false
            getHandler(out).onPull()
            log.info("Stream unpaused!")
          case _ =>
        }
      }
    }
}

This is a very simple implementation of the supervisor actor:

object Supervisor {
  case class AssignStageActor(ref: ActorRef)
}

class Supervisor extends Actor with ActorLogging {

  var stageActor: Option[ActorRef] = None

  override def receive: Receive = {

    case AssignStageActor(ref) =>
      log.info("Stage assigned!")
      stageActor = Some(ref)
      ref ! Done

    case Pause =>
      log.info("Pause stream!")
      stageActor match {
        case Some(ref) => ref ! Pause
        case _ =>
      }

    case UnPause =>
      log.info("UnPause stream!")
      stageActor match {
        case Some(ref) => ref ! UnPause
        case _ =>
      }
  }
}

I'm using the following application to run the stream:

object Application extends App {

  implicit val system = ActorSystem("my-actor-system")
  implicit val materializer = ActorMaterializer()

  val supervisor = system.actorOf(Props[Supervisor], "supervisor")

  val sourceGraph: Graph[SourceShape[Int], NotUsed] = new RandomNumberSource(supervisor)
  val randomNumberSource: Source[Int, NotUsed] = Source.fromGraph(sourceGraph)

  randomNumberSource.take(100).runForeach(println)

  println("Start stream by pressing any key")

  StdIn.readLine()

  supervisor ! UnPause

  StdIn.readLine()

  supervisor ! Pause

  StdIn.readLine()

  println("=== Terminating ===")
  system.terminate()
}

When the application starts the stage ia in 'paused' state and does not produce any number. When i press a key my stage starts to emit numbers. But my problem is that all messages sent to the stage after it has been started are ignored. I can not pause the stage.

I'm interested in changing the behavior of a stage based on a message received from an actor, but all examples i found pass an actor's message into the stream.

Does somebody has a guess why my code does not work or has an idea how to build such a GraphStage?

Thank you very much!

Body:
The Akka Stream Contrib project has a Valve stage that materializes a value that can pause and resume a flow. From the Scaladoc for this class:

Materializes into a Future of ValveSwitch which provides a the method flip that stops or restarts the flow of elements passing through the stage. As long as the valve is closed it will backpressure.

For example:

val (switchFut, seqSink) = Source(1 to 10)
  .viaMat(new Valve(SwitchMode.Close))(Keep.right)
  .toMat(Sink.seq)(Keep.both)
  .run()

switchFut is a Future[ValveSwitch], and since the switch is closed initially, the valve backpressures and nothing is emitted downstream. To open the valve:

switchFut.onComplete {
  case Success(switch) =>
    switch.flip(SwitchMode.Open) // Future[Boolean]
  case _ =>
    log.error("the valve failed")
}

More examples are in ValveSpec.


问:
External style sheets not applying styles
I have this page, to test a new layout for a category on a website at my new job:

```<code><!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="http://cdnjs.cloudflare.com/ajax/libs/pure/1.0.0/grids-responsive-min.css" media="all" />
  </head>
  <body>
    <div id="category-desc-grid" class="pure-g">

      <div class="pure-u">
        <p class="title"></p>

        <p class="details">
          Throw Style & Fitted Style<br>
          71 Fabric Color Choices<br>
          Fire resistant. Passes NFPA 701-2010<br>
          Full Color Dye Sublimation
        </p>

        <a href="#" class="button">Buy/View 24 Hour Tablecloths</a>
      </div>

      <div class="pure-u-1-2">
        <p class="title">Single Color Front Panel, Fitted Table Colors & Throws</p>

        <p class="details">
          4ft, 5ft, 6ft, 8ft<br>
          74 Fabric Color Choices,<br>
          including neon colors.<br>
          Fire resistant. Passes<br>
          NFPA 701-2010
        </p>

        <a href="#" class="button">Available in 1, 2, or 3 Day Production</a>
      </div>

      <div class="pure-u-1-2">
        <p class="title">Full Color Print Front Panel</p>

        <p class="details">
          Additional Panel Print $99<br>
          Fitted & Throw Style<br>
          4ft, 5ft, 6ft, 8ft<br>
          71 Fabric Choices<br>
          F.R. - NFPA 701-2010
        </p>

        <a href="#" class="button">Available in 1, 2, or 3 Day Production</a>
      </div>

    </div>

  </body>
</html>
</code>```

All of the stylesheets included are the mass that they have included in the head of the page that this code is to be inserted into, save for the last one, the Pure Grid. This is the one in question which will not apply any of its styles. As you can see I have the classes from that stylesheet in my HTML, but no styles are being attributed to them upon inspection. Styles from the stylesheets prior, however, are being applied.

Why

I've removed the grid stylesheet altogether and added one simple line: .display-grid .half { display: inline-block; width: 50%; max-width: 50%; } but it will only split into halves if I exclude the width rule. Unbelievable.

I just added the Bootstrap grid standalone.

答:
I replicated your code on my system. The inspect console complained that no character encoding was declared, so i inserted a <meta charset="utf-8"/> snippet in the  tags.

Also, I looked at the Pure Grid css file. It looks like some elements are missing when you used the class names. For example, I changed "pure-u" to "pure-u-sm-1-24" and it worked in my browser.

Body:
I have this page, to test a new layout for a category on a website at my new job:

<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="http://cdnjs.cloudflare.com/ajax/libs/pure/1.0.0/grids-responsive-min.css" media="all" />

          Throw Style & Fitted Style

          71 Fabric Color Choices

          Fire resistant. Passes NFPA 701-2010

          Full Color Dye Sublimation

        Buy/View 24 Hour Tablecloths

Single Color Front Panel, Fitted Table Colors & Throws

          4ft, 5ft, 6ft, 8ft

          74 Fabric Color Choices,

          including neon colors.

          Fire resistant. Passes

          NFPA 701-2010

        Available in 1, 2, or 3 Day Production

Full Color Print Front Panel

          Additional Panel Print $99

          Fitted & Throw Style

          4ft, 5ft, 6ft, 8ft

          71 Fabric Choices

          F.R. - NFPA 701-2010

        Available in 1, 2, or 3 Day Production

All of the stylesheets included are the mass that they have included in the head of the page that this code is to be inserted into, save for the last one, the Pure Grid. This is the one in question which will not apply any of its styles. As you can see I have the classes from that stylesheet in my HTML, but no styles are being attributed to them upon inspection. Styles from the stylesheets prior, however, are being applied.

Why

I've removed the grid stylesheet altogether and added one simple line: .display-grid .half { display: inline-block; width: 50%; max-width: 50%; } but it will only split into halves if I exclude the width rule. Unbelievable.

I just added the Bootstrap grid standalone.

Body:
I replicated your code on my system. The inspect console complained that no character encoding was declared, so i inserted a <meta charset="utf-8"/> snippet in the <head> tags.

Also, I looked at the Pure Grid css file. It looks like some elements are missing when you used the class names. For example, I changed "pure-u" to "pure-u-sm-1-24" and it worked in my browser.


问:
ORA-06413 error when try to open connection in a MVC 4 application
I have an DLL which is responsible to make the queries on the database. In that DLL I have a method that opens the connection between the application and the database, as seen below:

```<code>private OracleConnection _InitConnection()
{
    this.LastException = null;
    this.Errors        = new List<Exception>();

    OracleConnection conn = null;

    try
    {
        conn = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=***)(PORT=***)))(CONNECT_DATA=(SERVICE_NAME=****)(SERVER = DEDICATED))); User Id=***; Password=***;");

        conn.Open();
    }
    catch (Exception ex)
    {
        this.LastException= ex;
        this.Errors.Add(ex);
    }

    return conn;
}
</code>```

I use the System.Data.OracleClient.dll,  version 2.0.50727, to manage the connection.

This DLL is used by an MVC 4 Web Application, implemented using C# and .Net Framework 4.0.

When I use this DLL in a Windows Forms project I can connect to the database without any trouble. However, when I try to use the same DLL in a MVC system or using WebForms, I get an error.

The error that I get is the ORA-06413 - Connection not Open.This happen when I run the application in an ISS Express, set to run as 32 bits.

When I change the ISS Express to 64 bits I get the error OCIEnvCreate failed with return code -1 but error message text was not available.

答:
I guess I've found the problem.

In the project I was using some libraries from another project. One of those was configured as follows in the .csproj file

```<code><PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
 <DebugSymbols>true</DebugSymbols>
 <DebugType>full</DebugType>
 <Optimize>false</Optimize>
 <OutputPath>bin\Debug\</OutputPath>
 <DefineConstants>TRACE;DEBUG</DefineConstants>
 <ErrorReport>prompt</ErrorReport>
 <WarningLevel>4</WarningLevel>
 <PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
</code>```

That means that the compiled version of this program woul'd be stored in the \bin\Debug path.
However, the console application that I've using to test the library has the following configuration:

```<code><PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
 <DebugType>pdbonly</DebugType>
 <Optimize>true</Optimize>
 <OutputPath>bin\Release\</OutputPath>
 <DefineConstants>TRACE</DefineConstants>
 <ErrorReport>prompt</ErrorReport>
 <WarningLevel>4</WarningLevel>
 <Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
</code>```

Wich means that the output of the program would be stored at bin\Release.
That caused the problem, because when my console application tried to use the library, it was in another folder.
It wasn't possible to solve that inside the VS2015, but the problem disapeared when I changed the property group of my console application to the same configuration as my library was.

Body:
I have an DLL which is responsible to make the queries on the database. In that DLL I have a method that opens the connection between the application and the database, as seen below:

private OracleConnection _InitConnection()
{
    this.LastException = null;
    this.Errors        = new List<Exception>();

    OracleConnection conn = null;

    try
    {
        conn = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=***)(PORT=***)))(CONNECT_DATA=(SERVICE_NAME=****)(SERVER = DEDICATED))); User Id=***; Password=***;");

        conn.Open();
    }
    catch (Exception ex)
    {
        this.LastException= ex;
        this.Errors.Add(ex);
    }

    return conn;
}

I use the System.Data.OracleClient.dll,  version 2.0.50727, to manage the connection.

This DLL is used by an MVC 4 Web Application, implemented using C# and .Net Framework 4.0.

When I use this DLL in a Windows Forms project I can connect to the database without any trouble. However, when I try to use the same DLL in a MVC system or using WebForms, I get an error.

The error that I get is the ORA-06413 - Connection not Open.This happen when I run the application in an ISS Express, set to run as 32 bits.

When I change the ISS Express to 64 bits I get the error OCIEnvCreate failed with return code -1 but error message text was not available.

Body:
I guess I've found the problem.

In the project I was using some libraries from another project. One of those was configured as follows in the .csproj file

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
 <DebugSymbols>true</DebugSymbols>
 <DebugType>full</DebugType>
 <Optimize>false</Optimize>
 <OutputPath>bin\Debug\</OutputPath>
 <DefineConstants>TRACE;DEBUG</DefineConstants>
 <ErrorReport>prompt</ErrorReport>
 <WarningLevel>4</WarningLevel>
 <PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>

That means that the compiled version of this program woul'd be stored in the \bin\Debug path.
However, the console application that I've using to test the library has the following configuration:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
 <DebugType>pdbonly</DebugType>
 <Optimize>true</Optimize>
 <OutputPath>bin\Release\</OutputPath>
 <DefineConstants>TRACE</DefineConstants>
 <ErrorReport>prompt</ErrorReport>
 <WarningLevel>4</WarningLevel>
 <Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>

Wich means that the output of the program would be stored at bin\Release.
That caused the problem, because when my console application tried to use the library, it was in another folder.
It wasn't possible to solve that inside the VS2015, but the problem disapeared when I changed the property group of my console application to the same configuration as my library was.


问:
Rails 3 on dreamhost?
I'd like to deploy a small Rails 3 app on dreamhost (just for testing purposes, nothing serious) and I am wondering if anyone has done it already... Please choose one of the following:

I did it and it's super easy, here's how: ...

Though I didn't try it, it should be easy, here's how: ...

It's quite complicated, but this should get you started: ....

NO WAI!!!1!one!1 Set it up on slicehost or another non-shared hosting or you'll die a painful death trying to force it on DH

Thoughts?

答:
From Passenger documentation: http://www.modrails.com/documentation/Users%20guide%20Apache.html#bundler_support

Create a file config/setup_load_paths.rb in your app and add this line:

```<code>$: << "<path-where-bundler-gem-was-installed>/lib"
</code>```

I unpacked bundler gem in vendor/bundle path with this command:

```<code>gem unpack bundler --target=vendor/bundle
</code>```

And the others gems with:

```<code>bundle install --deployment
</code>```

This should work with Dreamhost and Passenger >= 2.2.14

Title: Rails 3 on dreamhost?

Body:
From Passenger documentation: http://www.modrails.com/documentation/Users%20guide%20Apache.html#bundler_support

Create a file config/setup_load_paths.rb in your app and add this line:

$: << "<path-where-bundler-gem-was-installed>/lib"

I unpacked bundler gem in vendor/bundle path with this command:

gem unpack bundler --target=vendor/bundle

And the others gems with:

bundle install --deployment

This should work with Dreamhost and Passenger >= 2.2.14


问:
Ansible API 2.3.2.0 tags passed to playbook but doesn't run task with tag
I am successfully passing the tag because the playbook is only running the task I have assign tags: always

The task that is assign the tag I am passing, doesn't run.

Three tasks for testing:

```<code>  - name: debug if tag was provided
    debug: var=tags
    tags: always

  - name: if tag restart was provided
    debug: var=tags
    tags: restart

  - name: if no tag was provided
    debug: var=tags
</code>```

Only the first task runs when I pass 'restart' as the tag, all three tasks run when no tag is provided.  I want the middle guy to run when restart is provided.

Is there a way to see what the playbook is seeing as the tag?

The output for the debug is:

```<code>{
    "tags": "VARIABLE IS NOT DEFINED!"
}
</code>```

Here is how I am sending the tag via the api

```<code>Options = namedtuple('Options', ['connection',  'forks', 'become', 'become_method', 'become_user', 'check',
                                 'listhosts', 'listtasks', 'listtags', 'syntax', 'module_path', 'diff', 'tags'])
options = Options(connection='ssh', forks=5, become=None, become_method=None, become_user=None, check=False,
                  listhosts=False, listtasks=False, listtags=False, syntax=False, module_path="", diff=True, tags=_tag)

PlaybookExecutor(playbooks=[playbook_path], inventory=inventory, variable_manager=variable_manager,
                            loader=loader, options=options, passwords=passwords)
</code>```

_tag is a string

Body:
I am successfully passing the tag because the playbook is only running the task I have assign tags: always

The task that is assign the tag I am passing, doesn't run.

Three tasks for testing:

  - name: debug if tag was provided
    debug: var=tags
    tags: always

  - name: if tag restart was provided
    debug: var=tags
    tags: restart

  - name: if no tag was provided
    debug: var=tags

Only the first task runs when I pass 'restart' as the tag, all three tasks run when no tag is provided.  I want the middle guy to run when restart is provided.

Is there a way to see what the playbook is seeing as the tag?

The output for the debug is:

{
    "tags": "VARIABLE IS NOT DEFINED!"
}

Here is how I am sending the tag via the api

Options = namedtuple('Options', ['connection',  'forks', 'become', 'become_method', 'become_user', 'check',
                                 'listhosts', 'listtasks', 'listtags', 'syntax', 'module_path', 'diff', 'tags'])
options = Options(connection='ssh', forks=5, become=None, become_method=None, become_user=None, check=False,
                  listhosts=False, listtasks=False, listtags=False, syntax=False, module_path="", diff=True, tags=_tag)

PlaybookExecutor(playbooks=[playbook_path], inventory=inventory, variable_manager=variable_manager,
                            loader=loader, options=options, passwords=passwords)

_tag is a string

Body:
Is there a way to see what the playbook is seeing as the tag?

Since Ansible 2.5 (currently available as devel branch on GitHub) you can use a new magic variable ansible_run_tags.

For example with ansible-playbook playbook.yml --tags restart:

TASK [debug if tag was provided] ***************************************************************************************************************
ok: [localhost] => {
    "ansible_run_tags": [
        "restart"
    ]
}

TASK [if tag restart was provided] *************************************************************************************************************
ok: [localhost] => {
    "ansible_run_tags": [
        "restart"
    ]
}

When you do not provide tags for ansible-playbook, the value of this variable is all:

TASK [debug if tag was provided] ***************************************************************************************************************
ok: [localhost] => {
    "ansible_run_tags": [
        "all"
    ]
}

TASK [if tag restart was provided] *************************************************************************************************************
ok: [localhost] => {
    "ansible_run_tags": [
        "all"
    ]
}

TASK [if no tag was provided] ******************************************************************************************************************
ok: [localhost] => {
    "ansible_run_tags": [
        "all"
    ]
}