问:
docker compose Logstash - specify config file and install plugin?
Im trying to copy my Logstash config and install a plugin at the same time. Ive tried multiple methods thus far with no avail, Logstash exists with errors every time

this fails:

```<code>logstash:
  image: logstash:latest
  command: logstash -f /etc/logstash/conf.d/logstash.conf
  command: bash -c bin/logstash-plugin install logstash-filter-translate
</code>```

this fails:

```<code>command: logstash -f /etc/logstash/conf.d/logstash.conf bash -c bin/logstash-plugin install logstash-filter-translate
</code>```

this fails:

```<code>command: logstash -f /etc/logstash/conf.d/logstash.conf && bash -c bin/logstash-plugin install logstash-filter-translate
</code>```

this also fails

```<code>command: bash -c logstash -f /etc/logstash/conf.d/logstash.conf && bin/logstash-plugin install logstash-filter-translate
</code>```

Im having no luck here and I bet the answer is simple... can anyone point me in the right direction?

Thanks

答:
I use the image that I am having locally with the below config, then it's working fine. Hope it helps.

```<code>version: '3'
services:
  logstash:
    image: docker.elastic.co/logstash/logstash:5.6.3
    command: bash -c "logstash -f /etc/logstash/conf.d/logstash.conf && bin/logstash-plugin install logstash-filter-translate"
</code>```

Sample output

```<code>logstash_1  | [2017-12-06T15:27:29,120][WARN ][logstash.agent           ] stopping pipeline {:id=>".monitoring-logstash"}
logstash_1  | Validating logstash-filter-translate
logstash_1  | Installing logstash-filter-translate
</code>```

Body:
Im trying to copy my Logstash config and install a plugin at the same time. Ive tried multiple methods thus far with no avail, Logstash exists with errors every time

this fails:

logstash:
  image: logstash:latest
  command: logstash -f /etc/logstash/conf.d/logstash.conf
  command: bash -c bin/logstash-plugin install logstash-filter-translate

this fails:

command: logstash -f /etc/logstash/conf.d/logstash.conf bash -c bin/logstash-plugin install logstash-filter-translate

this fails:

command: logstash -f /etc/logstash/conf.d/logstash.conf && bash -c bin/logstash-plugin install logstash-filter-translate

this also fails

command: bash -c logstash -f /etc/logstash/conf.d/logstash.conf && bin/logstash-plugin install logstash-filter-translate

Im having no luck here and I bet the answer is simple... can anyone point me in the right direction?

Thanks

Body:
I use the image that I am having locally with the below config, then it's working fine. Hope it helps.

version: '3'
services:
  logstash:
    image: docker.elastic.co/logstash/logstash:5.6.3
    command: bash -c "logstash -f /etc/logstash/conf.d/logstash.conf && bin/logstash-plugin install logstash-filter-translate"

Sample output

logstash_1  | [2017-12-06T15:27:29,120][WARN ][logstash.agent           ] stopping pipeline {:id=>".monitoring-logstash"}
logstash_1  | Validating logstash-filter-translate
logstash_1  | Installing logstash-filter-translate


来源: stackexchange

问:
How to disable default box shadow /border-color in Google-chrome
The default border color for active input tags in Google chrome is yellow, how do i disable it?

How do i change the color in css?

答: It's the CSS outline property - try outline:none; on the form fields.

ContentLicense: CC BY-SA 2.5


问:
jQuery not rebinding event to handler after unbinding
I have the following jQuery code:

```<code>$(document).on('focusout', '#element', function(e){
     alert('test');
});

$(document).on('click', '#element_b', function(e){
     $(document).off('focusout','#element');
     /* do other stuff */
     $(document).on('focusout','#element',function(){});
});
</code>```

On clicking on #element_b, the event bound to #element is supposed to get off and then back on but for some reason after it goes off, it doesn't return back on. How to get it back on?

答:
I would personally argue for a different approach so you can stop modifying the bindings.  Instead change your matcher so it is more restrictive.

```<code>$(document).on('focusout', '#element:not(.restricted)', function(e){
    alert('test');
});
</code>```

If you made the selector like this, all you would have to do to "toggle" it on or off is add/remove the restricted class to the element, or whatever more restrictive matcher you give the delegate.

ContentLicense: CC BY-SA 3.0

Body:
I have the following jQuery code:

$(document).on('focusout', '#element', function(e){
     alert('test');
});

$(document).on('click', '#element_b', function(e){
     $(document).off('focusout','#element');
     /* do other stuff */
     $(document).on('focusout','#element',function(){});
});

On clicking on #element_b, the event bound to #element is supposed to get off and then back on but for some reason after it goes off, it doesn't return back on. How to get it back on?

Body:
I would personally argue for a different approach so you can stop modifying the bindings.  Instead change your matcher so it is more restrictive.

$(document).on('focusout', '#element:not(.restricted)', function(e){
    alert('test');
});

If you made the selector like this, all you would have to do to "toggle" it on or off is add/remove the restricted class to the element, or whatever more restrictive matcher you give the delegate.


问:
Adding basic events to dynamically added controls
I have some basic code that, when a control is dropped on a Canvas, I need the user to be able to delete said control via a simple key press.

```<code>private void PlaceElementOnCavas(UIElement element, Point point) {

    Canvas.SetLeft(element, point.X);
    Canvas.SetTop(element, point.Y);

    // Add the event to allow the user to press delete and remove the control
    element.KeyDown += (sender, e) => {
        if (e.Key == Key.Delete) {
            this.designCanvas.Children.Remove(element);
        }
    };

    this.designCanvas.Children.Add(element);

}
</code>```

My code looks like that.  My control is added fine, at exactly the point on the Canvas I need it do.

The event handler does nothing, whether I try to add it via a lambda or via a traditional call to another method.

What am I missing?

答:
The following steps should be enough to make your keyboard input work:

Set Focusable="True"

Handle MouseLeftButtonUp and assign the Keyboard.Focus in it

Set a Background in order to capture the mouse events

Handle the key events

Then click into the element to focus it and use your keys. Alternative, if you don't plan to use the mouse and only want to focus it by pressing tab, you only need the Focusable and the key events.

```<code><Grid x:Name="grid1" KeyDown="grid1_KeyDown" Focusable="True" MouseLeftButtonUp="grid1_MouseLeftButtonUp" Background="Transparent">
</Grid>
</code>```

Focus handling:

```<code>private void grid1_KeyDown(object sender, KeyEventArgs e)
{
    // whatever you plan to do
}

private void grid1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    Keyboard.Focus(sender as IInputElement);
}
</code>```

Body:
I have some basic code that, when a control is dropped on a Canvas, I need the user to be able to delete said control via a simple key press.

private void PlaceElementOnCavas(UIElement element, Point point) {

    Canvas.SetLeft(element, point.X);
    Canvas.SetTop(element, point.Y);

    // Add the event to allow the user to press delete and remove the control
    element.KeyDown += (sender, e) => {
        if (e.Key == Key.Delete) {
            this.designCanvas.Children.Remove(element);
        }
    };

    this.designCanvas.Children.Add(element);

}

My code looks like that.  My control is added fine, at exactly the point on the Canvas I need it do.

The event handler does nothing, whether I try to add it via a lambda or via a traditional call to another method.

What am I missing?

Body:
The following steps should be enough to make your keyboard input work:

Set Focusable="True"

Handle MouseLeftButtonUp and assign the Keyboard.Focus in it

Set a Background in order to capture the mouse events

Handle the key events

Then click into the element to focus it and use your keys. Alternative, if you don't plan to use the mouse and only want to focus it by pressing tab, you only need the Focusable and the key events.

<Grid x:Name="grid1" KeyDown="grid1_KeyDown" Focusable="True" MouseLeftButtonUp="grid1_MouseLeftButtonUp" Background="Transparent">
</Grid>

Focus handling:

private void grid1_KeyDown(object sender, KeyEventArgs e)
{
    // whatever you plan to do
}

private void grid1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    Keyboard.Focus(sender as IInputElement);
}


问:
JavaScript Regexp replace with grouping Euro symbol's
Trying create Regexp for  € 14,50 after complete replacement must left only

14,50

maybe someone can Help ?

答:
Code

See regex in use here

The below regex simply ensures it's not preceded by a #

```<code>[^#\d](\d+(?:,\d+)?)
</code>```

Alternatively: € *(\d+(?:,\d+)?), which ensures it's preceded by € followed by any number of spaces.

Usage

var r = /[^#\d](\d+(?:,\d+)?)/g;
var s = ` € 14,50`

console.log(r.exec(s)[1]);```
</div>
</div>
</p>

<p><strong>Alternative</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var r = /€ *(\d+(?:,\d+)?)/g;
var s = ` € 14,50`

console.log(r.exec(s)[1]);</code>```

Explanation

[^#\d] Match anything not present in the set (anything except # and a digit)

(\d+(?:,\d+)?) Capture the following into capture group 1

\d+ Match any digit one or more times

(?:,\d+)? Match zero or one time the following

, Match the comma character , literally

\d+ Match any digit one or more times

Body:
Code

See regex in use here

The below regex simply ensures it's not preceded by a #

[^#\d](\d+(?:,\d+)?)

Alternatively: € *(\d+(?:,\d+)?), which ensures it's preceded by € followed by any number of spaces.

Usage

var r = /[^#\d](\d+(?:,\d+)?)/g;
var s = `&#8203; € 14,50`

console.log(r.exec(s)[1]);

Alternative

var r = /€ *(\d+(?:,\d+)?)/g;
var s = `&#8203; € 14,50`

console.log(r.exec(s)[1]);

Explanation

[^#\d] Match anything not present in the set (anything except # and a digit)

(\d+(?:,\d+)?) Capture the following into capture group 1

\d+ Match any digit one or more times

(?:,\d+)? Match zero or one time the following

, Match the comma character , literally

\d+ Match any digit one or more times


问:
Button styling not not respecting styleName=""
I am using the latest install of ShoutemUI 0.21.3 and RN 0.42.2. All buttons just have a white background. I am not using Shoutem Themes right now. I have tried styleName="confirmation" and still just a white button and no border. Am I missing something?

Here is the code on the left and the results on the right in the simulator.

Here is a screenshot of my imports.

答:
The UI package has a theme.js file with all these styleName's. In order to utilize it, you need @shoutem/theme installed. It's a dependency of @shoutem/ui.

Furthermore, the dark styleName is obsolete. You should utilize secondary instead for the desired effect.


问:
how to determine if a character vector is a valid numeric or integer vector
I am trying to turn a nested list structure into a dataframe. The list looks similar to the following (it is serialized data from parsed JSON read in using the httr package).

```<code>  myList <- list(object1 = list(w=1, x=list(y=0.1, z="cat")), object2 = list(w=NULL, x=list(z="dog")))
</code>```

EDIT: my original example data was too simple.  The actual data are ragged, meaning that not all variables exist for every object, and some of the list elements are NULL. I edited the data to reflect this.

unlist(myList) does a great job of recursively flattening the list, and I can then use lapply to flatten all the objects nicely.

```<code>  flatList <- lapply(myList, FUN= function(object) {return(as.data.frame(rbind(unlist(object))))})
</code>```

And finally, I can button it up using plyr::rbind.fill

```<code>  myDF <- do.call(plyr::rbind.fill, flatList)
  str(myDF)

  #'data.frame':    2 obs. of  3 variables:
  #$ w  : Factor w/ 2 levels "1","2": 1 2
  #$ x.y: Factor w/ 2 levels "0.1","0.2": 1 2
  #$ x.z: Factor w/ 2 levels "cat","dog": 1 2
</code>```

The problem is that w and x.y are now being interpreted as character vectors, which by default get parsed as factors in the dataframe.  I believe that unlist() is the culprit, but I can't figure out another way to recursively flatten the list structure.  A workaround would be to post-process the dataframe, and assign data types then.  What is the best way to determine if a vector is a valid numeric or integer vector?

答:
When NAs are included @josliber's original function didn't work (though it answered the question well for the sample data).  @Amy M's function should work but requires loading Hmisc package.

What about something like this:

```<code>can.be.numeric <- function(x) {
    stopifnot(is.atomic(x) || is.list(x)) # check if x is a vector
    numNAs <- sum(is.na(x))
    numNAs_new <- suppressWarnings(sum(is.na(as.numeric(x))))
    return(numNAs_new == numNAs)
}
</code>```

It counts NAs in input vector x and NAs in the output of as.numeric(x) and returns TRUE if the vector can be "safely" converted to numeric (i.e. without adding any additional NA values).

UPDATE: Request to show how to use the function. You want to call this function on each column and only convert columns that can be numeric.

```<code>myDF2 <- lapply(myDF, function(col) {
  if (can.be.numeric(col)) {
    as.numeric(col)
  } else {
    col
  }
})
str(as.data.frame(myDF2))
# 'data.frame': 2 obs. of  3 variables:
#  $ w  : num  1 NA
#  $ x.y: num  0.1 NA
#  $ x.z: chr  "cat" "dog"
</code>```

Body:
I am trying to turn a nested list structure into a dataframe. The list looks similar to the following (it is serialized data from parsed JSON read in using the httr package).

  myList <- list(object1 = list(w=1, x=list(y=0.1, z="cat")), object2 = list(w=NULL, x=list(z="dog")))

EDIT: my original example data was too simple.  The actual data are ragged, meaning that not all variables exist for every object, and some of the list elements are NULL. I edited the data to reflect this.

unlist(myList) does a great job of recursively flattening the list, and I can then use lapply to flatten all the objects nicely.

  flatList <- lapply(myList, FUN= function(object) {return(as.data.frame(rbind(unlist(object))))})

And finally, I can button it up using plyr::rbind.fill

  myDF <- do.call(plyr::rbind.fill, flatList)
  str(myDF)

  #'data.frame':    2 obs. of  3 variables:
  #$ w  : Factor w/ 2 levels "1","2": 1 2
  #$ x.y: Factor w/ 2 levels "0.1","0.2": 1 2
  #$ x.z: Factor w/ 2 levels "cat","dog": 1 2

The problem is that w and x.y are now being interpreted as character vectors, which by default get parsed as factors in the dataframe.  I believe that unlist() is the culprit, but I can't figure out another way to recursively flatten the list structure.  A workaround would be to post-process the dataframe, and assign data types then.  What is the best way to determine if a vector is a valid numeric or integer vector?

Body:
When NAs are included @josliber's original function didn't work (though it answered the question well for the sample data).  @Amy M's function should work but requires loading Hmisc package.

What about something like this:

can.be.numeric <- function(x) {
    stopifnot(is.atomic(x) || is.list(x)) # check if x is a vector
    numNAs <- sum(is.na(x))
    numNAs_new <- suppressWarnings(sum(is.na(as.numeric(x))))
    return(numNAs_new == numNAs)
}

It counts NAs in input vector x and NAs in the output of as.numeric(x) and returns TRUE if the vector can be "safely" converted to numeric (i.e. without adding any additional NA values).

UPDATE: Request to show how to use the function. You want to call this function on each column and only convert columns that can be numeric.

myDF2 <- lapply(myDF, function(col) {
  if (can.be.numeric(col)) {
    as.numeric(col)
  } else {
    col
  }
})
str(as.data.frame(myDF2))
# 'data.frame': 2 obs. of  3 variables:
#  $ w  : num  1 NA
#  $ x.y: num  0.1 NA
#  $ x.z: chr  "cat" "dog"

ContentLicense: CC BY-SA 4.0


问:
the millisUntilFinished of my countdown timer would not change according to user input
Here is my problem:
I get user input from two numberPickers. I then use the collected number to set the millisInFuture of my countdown timer. But the problem is: whatever number I choose, the millisUntilFinished of my countdown timer would not change according  to user input.
My code is simplified as follows:

```<code>int firstMin = 1;
int firstSec = 30;//initial value in the field
int i = 1; //to determine whether the remained time should be shown

private void initFirstMinPicker() {
    minPicker.setMaxValue(60);
    minPicker.setValue(firstMin);//set the current value of number picker

    minPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            firstMin = newVal;//pass the selected int to firstMin

        }
    });

//My countdown timer is supposed to start on clicking a button
firstTimer = new CountDownTimer(firstMin * 60000, 500) {//use 500 to
avoid skipping the last onTick()
        @Override
        public void onTick(long millisUntilFinished) {
            Log.d("TAG", "onTick:firstMin " + firstMin);
            if (i % 2 == 0) {
                workLeft.setText(String.valueOf(millisUntilFinished / 1000));
            }
            i++;
        }

        @Override
        public void onFinish() {

        }
    };
</code>```

My TAG:

```<code>D/TAG: onTick:firstMin 6
D/TAG: onTick:firstMin 6
D/TAG: onTick:firstMin 6
</code>```

It's clear that firstMin has been changed, but when I use firstMin * 60000 as an argument, the millisUntilFinished will always start from 60000 regardless of how much firstMin * 60000 evaluates to. That is, when my countdown timer begins to count down, it always count downwards from 60(initial value of firstMin * 60). I have no idea why this should happen. Have you guys ever come across such a problem? Any help would be very much appreciated.

答:
You are only declaring firstTimer once, meaning that it'll only ever be created when firstmin = 1. You'll need to create a new instance of firstTimer whenever onValueChanged is called, for example:

```<code>minPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
    @Override
    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
        firstMin = newVal;//pass the selected int to firstMin
        firstTimer = new CountDownTimer(firstMin * 60000, 500) { ... }
    }
});
</code>```

It might also be worth creating a function that returns a new CountDownTimer, taking only the value of firstMin and automatically populating the rest of the default values, to save on unnecessary code repetition.

Body:
Here is my problem:
I get user input from two numberPickers. I then use the collected number to set the millisInFuture of my countdown timer. But the problem is: whatever number I choose, the millisUntilFinished of my countdown timer would not change according  to user input.
My code is simplified as follows:

int firstMin = 1;
int firstSec = 30;//initial value in the field
int i = 1; //to determine whether the remained time should be shown

private void initFirstMinPicker() {
    minPicker.setMaxValue(60);
    minPicker.setValue(firstMin);//set the current value of number picker

    minPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            firstMin = newVal;//pass the selected int to firstMin

        }
    });

//My countdown timer is supposed to start on clicking a button
firstTimer = new CountDownTimer(firstMin * 60000, 500) {//use 500 to
avoid skipping the last onTick()
        @Override
        public void onTick(long millisUntilFinished) {
            Log.d("TAG", "onTick:firstMin " + firstMin);
            if (i % 2 == 0) {
                workLeft.setText(String.valueOf(millisUntilFinished / 1000));
            }
            i++;
        }

        @Override
        public void onFinish() {

        }
    };

My TAG:

D/TAG: onTick:firstMin 6
D/TAG: onTick:firstMin 6
D/TAG: onTick:firstMin 6

It's clear that firstMin has been changed, but when I use firstMin * 60000 as an argument, the millisUntilFinished will always start from 60000 regardless of how much firstMin * 60000 evaluates to. That is, when my countdown timer begins to count down, it always count downwards from 60(initial value of firstMin * 60). I have no idea why this should happen. Have you guys ever come across such a problem? Any help would be very much appreciated.

Body:
You are only declaring firstTimer once, meaning that it'll only ever be created when firstmin = 1. You'll need to create a new instance of firstTimer whenever onValueChanged is called, for example:

minPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
    @Override
    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
        firstMin = newVal;//pass the selected int to firstMin
        firstTimer = new CountDownTimer(firstMin * 60000, 500) { ... }
    }
});

It might also be worth creating a function that returns a new CountDownTimer, taking only the value of firstMin and automatically populating the rest of the default values, to save on unnecessary code repetition.


问:
ChromeOptions to change the language from US to UK
What are the ChromeOptions (C#) to change the default language of the browser from US to UK using Selenium v3 and Chrome v60+?

Thanks

答:
Try this code :- </p>

```<code>ChromeOptions options = new ChromeOptions();
options.AddArguments("--lang=es");
ChromeDriver driver = new ChromeDriver(options);
</code>```

Body:
Try this code :-

ChromeOptions options = new ChromeOptions();
options.AddArguments("--lang=es");
ChromeDriver driver = new ChromeDriver(options);


问:
Angular 4.3 HttpClient Interceptor
Please advise why the route redirection is not working when response is 401. Console.log shows the response object and status as 401 but router is not redirecting user to logout page.</p>

```<code>intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

            this.onStart();
            return next.handle(req).do((event: HttpEvent<any>) =>
                (error: any) => {
                    if (error instanceof HttpErrorResponse) {
                        if (error.status == 0 || error.status == 401 || error.status == 404 || error.status == 500 || error.status == 503) {
                            this.storageService.writeToStorage(Constants.STORAGE_KEY_ERROR, error);
                            console.log(error);
                            this.router.navigateByUrl(Constants.ROUTE_ERROR_DYNAMIC + error.status);
                        }
                    }
                    else{
                        return Observable.throw(error);
                    }

                }).finally(() =>{
                    this.onEnd();
                })
        }
</code>```

答:
adding return Observable.empty(); helped in my case

```<code>intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    this.onStart();
    return next.handle(req)
        .catch((error: any) => {
            if (error instanceof HttpErrorResponse) {
                if (error.status == 0 || error.status == 401 || error.status == 404 || error.status == 500 || error.status == 503) {
                    this.storageService.writeToStorage(Constants.STORAGE_KEY_ERROR, error);
                    this.router.navigateByUrl(Constants.ROUTE_ERROR_DYNAMIC + error.status);
                    return Observable.empty();
                }
            }
            return Observable.throw(error);
        })
        .finally(() => {
            this.onEnd();
        })
}
</code>```

Title: Angular 4.3 HttpClient Interceptor

Body:
Please advise why the route redirection is not working when response is 401. Console.log shows the response object and status as 401 but router is not redirecting user to logout page.

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

            this.onStart();
            return next.handle(req).do((event: HttpEvent<any>) =>
                (error: any) => {
                    if (error instanceof HttpErrorResponse) {
                        if (error.status == 0 || error.status == 401 || error.status == 404 || error.status == 500 || error.status == 503) {
                            this.storageService.writeToStorage(Constants.STORAGE_KEY_ERROR, error);
                            console.log(error);
                            this.router.navigateByUrl(Constants.ROUTE_ERROR_DYNAMIC + error.status);
                        }
                    }
                    else{
                        return Observable.throw(error);
                    }

                }).finally(() =>{
                    this.onEnd();
                })
        }

Body:
adding return Observable.empty(); helped in my case

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    this.onStart();
    return next.handle(req)
        .catch((error: any) => {
            if (error instanceof HttpErrorResponse) {
                if (error.status == 0 || error.status == 401 || error.status == 404 || error.status == 500 || error.status == 503) {
                    this.storageService.writeToStorage(Constants.STORAGE_KEY_ERROR, error);
                    this.router.navigateByUrl(Constants.ROUTE_ERROR_DYNAMIC + error.status);
                    return Observable.empty();
                }
            }
            return Observable.throw(error);
        })
        .finally(() => {
            this.onEnd();
        })
}


问:
Apache CXF Could not send message caused by: java.net.SocketException: Connection reset
I am running tomcat server and trying to consume .NET SOAP WS.
Doing that with apache.cxf.

The .NET WS has cluster on it's side, and when restart has performed on one of the machines, I get

```<code>javax.xml.ws.WebServiceException: Could not send Message.
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:148)
...
Caused by: java.net.SocketException: Connection reset
</code>```

To avoid this, I want to work with connection=close header only for this WS consuming.

So, on creating SOAP messages, I send

```<code>HTTPConduit conduit = (HTTPConduit) iMyFlowWSClient.getConduit();
    conduit.getClient().setConnection(ConnectionType.CLOSE);
</code>```

And I see on wireshark that the header get the right value:

```<code>Connection: close\r\n
</code>```

But, when first call to WS is performed(looks like import of xsd's) on initializating of wsdl url by constractor of java.xml.ws.Service:

```<code>protected Service(java.net.URL wsdlDocumentLocation, QName serviceName) {
    delegate = Provider.provider().createServiceDelegate(wsdlDocumentLocation,
            serviceName,
            this.getClass());
}
</code>```

I see on Wireshark the next headers:

```<code>Hypertext Transfer Protocol
    GET /MyFlow.svc?wsdl HTTP/1.1\r\n
    Content-Type: text/xml\r\n
    Accept: */*\r\n
    User-Agent: Apache CXF 3.0.0\r\n
    Cache-Control: no-cache\r\n
    Pragma: no-cache\r\n
    Host: 123.123.12.34\r\n
    Connection: keep-alive\r\n
    \r\n
    [Full request URI: http://123.123.12.34/MyFlow.svc?wsdl]
</code>```

And that I believe what keeps alive this connection to WS.

Is there any solution to configure apache.cxf headers to send connection=close on all requests that performed on HTTP level?

答: No, and it looks to me that you will only be able to reduce the problem, not eliminate it. The problem seems to be on the .NET side; closing down the connections is somehow not done right.</p>

Body:
I am running tomcat server and trying to consume .NET SOAP WS.
Doing that with apache.cxf.

The .NET WS has cluster on it's side, and when restart has performed on one of the machines, I get

javax.xml.ws.WebServiceException: Could not send Message.
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:148)
...
Caused by: java.net.SocketException: Connection reset

To avoid this, I want to work with connection=close header only for this WS consuming.

So, on creating SOAP messages, I send

HTTPConduit conduit = (HTTPConduit) iMyFlowWSClient.getConduit();
    conduit.getClient().setConnection(ConnectionType.CLOSE);

And I see on wireshark that the header get the right value:

Connection: close\r\n

But, when first call to WS is performed(looks like import of xsd's) on initializating of wsdl url by constractor of java.xml.ws.Service:

protected Service(java.net.URL wsdlDocumentLocation, QName serviceName) {
    delegate = Provider.provider().createServiceDelegate(wsdlDocumentLocation,
            serviceName,
            this.getClass());
}

I see on Wireshark the next headers:

Hypertext Transfer Protocol
    GET /MyFlow.svc?wsdl HTTP/1.1\r\n
    Content-Type: text/xml\r\n
    Accept: */*\r\n
    User-Agent: Apache CXF 3.0.0\r\n
    Cache-Control: no-cache\r\n
    Pragma: no-cache\r\n
    Host: 123.123.12.34\r\n
    Connection: keep-alive\r\n
    \r\n
    [Full request URI: http://123.123.12.34/MyFlow.svc?wsdl]

And that I believe what keeps alive this connection to WS.

Is there any solution to configure apache.cxf headers to send connection=close on all requests that performed on HTTP level?


问:
How to send data to node js server with ajax
I'm trying to read data sent to node.js server.

Client side:

```<code>const sendToDB =(date)=> {
  var xhttp = new XMLHttpRequest();
  var d = JSON.stringify(date);
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      console.log(d);
    }
  };
  xhttp.open("POST", "api/info", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send(d);
}
</code>```

and the server:

```<code>var http = require('http');
var server = http.createServer(function(req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  req.on('data', function (chunk) {
    console.log(req.body.date);
  });
  res.end();
});
server.listen(3001);
</code>```

how to receive data sent with xhttp.send(d) in node js server ?

答:
```<code>var server = http.createServer(function(req, res) {
      if(req.method == "POST"){
           var clientData = '';
           req.on('data', function (chunk) {
                clientData+=chunk;
           });
           req.on('end',function(){
                console.log(JSON.parse(clientData));
           })
      }
      res.end();
});
</code>```

Body:
I'm trying to read data sent to node.js server.

Client side:

const sendToDB =(date)=> {
  var xhttp = new XMLHttpRequest();
  var d = JSON.stringify(date);
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      console.log(d);
    }
  };
  xhttp.open("POST", "api/info", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send(d);
}

and the server:

var http = require('http');
var server = http.createServer(function(req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  req.on('data', function (chunk) {
    console.log(req.body.date);
  });
  res.end();
});
server.listen(3001);

how to receive data sent with xhttp.send(d) in node js server ?


问:
ASMX Web Service slow first request
I have a bunch of .NET Webservices running in one IIS Application. These webservices are consumed by another IIS Application (frontend). The first call is pretty slow, about 5 to 10 seconds. After that it’s just milliseconds. The first call is considered a performance problem.

We’ve tried an application that calls all these webservices but this obviously doesn’t solve anything. So it's not the default Application Recycle that is the problem. I've created an application that just initializes the service several times and measures the time it takes to create one instance. Before running this application I ensure that my webservice application is started / recycled, then I run the application. The first initialization takes between 2 to 4 seconds, all others is just milliseconds.

Another thought is that we create a page in the Frontend application that initiates all the webservices and that we call this page before any users are in. I don’t consider this as an elegant solution, what else could I try?

答:
Sorry for the necro add, but this has been an ongoing struggle for me as well, and I wanted to add some info to the picture.  VisualStudio itself adds a rather large component to the time.  Here's the basic test, involving a bare-bones forms app and an already-running webservice hosted internally on a company server (with Generate Serialization Assembly set to true for all tests):

```<code>Running in VS, Debug:
    First Call: 400 ms to set up client object, 450 to call function
    Second Call: 1 ms to set up client object, 14 to call function
Running as .exe, Release:
    First Call: 20 ms to set up client object, 70 to call function
    Second call: 1 ms to set up client object, 4 to call function
Running the Debug's .exe file outside of vs:
    First Call: 20 ms to set up client object, 80 to call function
    Second call: 1 ms to set up client object, 4 to call function
Running as Release within VS:
    Similar results to Debug in VS -- very slow
</code>```

Short story?  Visual Studio is adding a large chunk of time to the picture.  Instead of ~90 ms, it's taking nearly a second.  So if you're doing performance tuning, make sure you do your testing outside the VisualStudio environment.

Title: ASMX Web Service slow first request

Body:
Sorry for the necro add, but this has been an ongoing struggle for me as well, and I wanted to add some info to the picture.  VisualStudio itself adds a rather large component to the time.  Here's the basic test, involving a bare-bones forms app and an already-running webservice hosted internally on a company server (with Generate Serialization Assembly set to true for all tests):

Running in VS, Debug:
    First Call: 400 ms to set up client object, 450 to call function
    Second Call: 1 ms to set up client object, 14 to call function
Running as .exe, Release:
    First Call: 20 ms to set up client object, 70 to call function
    Second call: 1 ms to set up client object, 4 to call function
Running the Debug's .exe file outside of vs:
    First Call: 20 ms to set up client object, 80 to call function
    Second call: 1 ms to set up client object, 4 to call function
Running as Release within VS:
    Similar results to Debug in VS -- very slow

Short story?  Visual Studio is adding a large chunk of time to the picture.  Instead of ~90 ms, it's taking nearly a second.  So if you're doing performance tuning, make sure you do your testing outside the VisualStudio environment.


问:
start learn iphone objective-c application where from?
to all
i'm new-be in iphone sector i didn't decide to where from i start to learn and build application for iphone </p>

答:
here is lot of links are available for that.........
https://stackoverflow.com/questions/928516/best-way-to-start-learning-cococa-in-iphone-or-osx-espeicaly-getting-the-big-pic

https://stackoverflow.com/questions/535198/best-way-to-learn-objective-c

best site and way to start learning objective C for iphone

How to learn C and Objective-C

learn iphone & objective c

also read this blog i like it
http://www.raywenderlich.com/


问:
How to use divided by 1000 as CPU optimization?
I am using small embedded PCIe based hardware, which is having a very low-end processor, based on the operation and firmware size, I am consuming all of its resources. To do CPU optimization what are the steps I can do?

I have tried to move multiplication(*) and divisions(/) using bitwise.
But I have codes like this

```<code>Y = X * 3;
</code>```

or

```<code>Z = X / 1000;
</code>```

getting confused how to do these in CPU friendly ways.

答:
1. Confirm your bottlenecks

There are CPU-bound, memory-bound, IO-bound applications etc. Your low-end processor in fact may spend most of the time waiting for the data from DRAM, doing some IO, or waiting for a spinlock. So the first thing you do is to confirm your real bottleneck.

There are tools for this, like free perf for Linux or paid Intel VTune.

2. Show us the context

If you found that most of the time your CPU spends on foo(), show us this function so we could help.

3. Generic suggestions

For your generic question, you will get just generic suggestions, like:

Use more aggressive compiler optimization, like -O3

Change your algorithms.

Avoid locks.

Align your data.

Avoid false sharing.

Make your data structures more compact.

Use prefetch.

etc etc

Sorry, there is no context to suggest you a more specific technique.

Body:
I am using small embedded PCIe based hardware, which is having a very low-end processor, based on the operation and firmware size, I am consuming all of its resources. To do CPU optimization what are the steps I can do?

I have tried to move multiplication(*) and divisions(/) using bitwise.
But I have codes like this

Y = X * 3;

or

Z = X / 1000;

getting confused how to do these in CPU friendly ways.


问:
Netlogo: Moving turtles and calculate distance
I'm currently do my project about path planning.

So the step of my plans are like this:

Click "setup" to arrange all the coordinate

Click "start" to create the moving turtles

Click "go" to make the moving turtle going to nearest coordinate (label with "x")

Which mean, at step 4, the moving turtle already calculate it's distance with every coordinate.

Here I attach the interface and the coding

```<code>to setup
 clear-all
 set-default-shape turtles "x"
 create-turtles 9
 ask turtles[set color red]

 ask turtle 0[setxy 0 15]
 ask turtle 1[setxy 4 15]
 ask turtle 2[setxy -4 15]
 ask turtle 3[setxy 0 12]
 ask turtle 4[setxy 4 12]
 ask turtle 5[setxy -4 12]
 ask turtle 6[setxy 0 9]
 ask turtle 7[setxy 4 9]
 ask turtle 8[setxy -4 9]
end

to start
 set-default-shape turtles "airplane"
 create-turtles 1

 ask turtle 9[setxy 0 -15]
end
</code>```

答:
Don't forget that distance depends on your topology.

```<code>to setup
  clear-all
  let targets [
    [0 15] [4 15] [-4 15]
    [0 12] [4 12] [-4 12]
    [0 9] [4 9] [-4 9]
  ]
  foreach targets [xy -> ask patch item 0 xy item 1 xy [
    sprout 1 [set shape "x" set color red]
    ]
  ]
  create-turtles 1 [ set shape "airplane" setxy 0 -15]
end
</code>```

EDIT: If you treat all other turtles as eligible targets, then once you move turtle 9 to a target it will stay there.  If you do not want that, you say that a turtle in the same location is not eligible:

```<code>to move
  ask turtle 9 [move-to min-one-of eligibles [distance myself]]
end

to-report eligibles
  report turtles with [0 < distance myself]
end
</code>```

Body:
I'm currently do my project about path planning.

So the step of my plans are like this:

Click "setup" to arrange all the coordinate

Click "start" to create the moving turtles

Click "go" to make the moving turtle going to nearest coordinate (label with "x")

Which mean, at step 4, the moving turtle already calculate it's distance with every coordinate.

Here I attach the interface and the coding

to setup
 clear-all
 set-default-shape turtles "x"
 create-turtles 9
 ask turtles[set color red]

 ask turtle 0[setxy 0 15]
 ask turtle 1[setxy 4 15]
 ask turtle 2[setxy -4 15]
 ask turtle 3[setxy 0 12]
 ask turtle 4[setxy 4 12]
 ask turtle 5[setxy -4 12]
 ask turtle 6[setxy 0 9]
 ask turtle 7[setxy 4 9]
 ask turtle 8[setxy -4 9]
end

to start
 set-default-shape turtles "airplane"
 create-turtles 1

 ask turtle 9[setxy 0 -15]
end

Body:
Don't forget that distance depends on your topology.

to setup
  clear-all
  let targets [
    [0 15] [4 15] [-4 15]
    [0 12] [4 12] [-4 12]
    [0 9] [4 9] [-4 9]
  ]
  foreach targets [xy -> ask patch item 0 xy item 1 xy [
    sprout 1 [set shape "x" set color red]
    ]
  ]
  create-turtles 1 [ set shape "airplane" setxy 0 -15]
end

EDIT: If you treat all other turtles as eligible targets, then once you move turtle 9 to a target it will stay there.  If you do not want that, you say that a turtle in the same location is not eligible:

to move
  ask turtle 9 [move-to min-one-of eligibles [distance myself]]
end

to-report eligibles
  report turtles with [0 < distance myself]
end


问:
Does MediaPlayer have problems with playing files with # in their paths?
I've noticed recently that the audioplayer developed by me stopped playing.

It turned out that MediaPlayer.prepare() threw an exception:

```<code>"Prepare failed.: status=0x1"
</code>```

The file name contained # symbol. After I removed #, it could be played back. I just removed # symbol. The file path itself was long and contained spaces, [ etc.

```<code>final Uri uri = Uri.parse("/storage/sdcard1/audio/Die Toten Hosen/03 - Boxed Set/2007 - Die DTH Jubiläumsedition [17 CD Boxed Set Remasted]/CD 1 - Opel-Gang/18. Radio Argentina #1.mp3");
mediaPlayer.reset();
mediaPlayer.setDataSource(context, uri);
</code>```

The question is why when I transfer files to my phone with

```<code>adb push /tmp/ /storage/sdcard1/audio/
</code>```

and some of them contain ? symbols, then they are skipped (or an errors/warning occur. Don't remember exactly), but the files that had # in their names were copied successfully. If there are some escaping rules then problems should be the same with files containing ? and files containing #.

Because I don't see any logic in what happened. It looks like there is no central place defining what should be escaped and how.

答:
The solution was to use:

```<code>MediaPlayer.setDataSource(String);
</code>```

Obviously it can handle # symbol in path names.

```<code>mediaPlayer.setDataSource("/storage/sdcard1/audio/Die Toten Hosen/03 - Boxed Set/2007 - Die DTH Jubiläumsedition [17 CD Boxed Set Remasted]/CD 1 - Opel-Gang/18. Radio Argentina #1.mp3");
</code>```

Body:
I've noticed recently that the audioplayer developed by me stopped playing.

It turned out that MediaPlayer.prepare() threw an exception:

"Prepare failed.: status=0x1"

The file name contained # symbol. After I removed #, it could be played back. I just removed # symbol. The file path itself was long and contained spaces, [ etc.

final Uri uri = Uri.parse("/storage/sdcard1/audio/Die Toten Hosen/03 - Boxed Set/2007 - Die DTH Jubiläumsedition [17 CD Boxed Set Remasted]/CD 1 - Opel-Gang/18. Radio Argentina #1.mp3");
mediaPlayer.reset();
mediaPlayer.setDataSource(context, uri);

The question is why when I transfer files to my phone with

adb push /tmp/ /storage/sdcard1/audio/

and some of them contain ? symbols, then they are skipped (or an errors/warning occur. Don't remember exactly), but the files that had # in their names were copied successfully. If there are some escaping rules then problems should be the same with files containing ? and files containing #.

Because I don't see any logic in what happened. It looks like there is no central place defining what should be escaped and how.

Body:
The solution was to use:

MediaPlayer.setDataSource(String);

Obviously it can handle # symbol in path names.

mediaPlayer.setDataSource("/storage/sdcard1/audio/Die Toten Hosen/03 - Boxed Set/2007 - Die DTH Jubiläumsedition [17 CD Boxed Set Remasted]/CD 1 - Opel-Gang/18. Radio Argentina #1.mp3");


问:
conflict while installing mayavi into anaconda
Good day,
My colleague asked my to install Anaconda and mayavi and I am novice with this topic and I decided to do the tasks on a new ubuntu installation

Here are my tasks before my issue

I fresh installed a Ubuntu 16.04

I ran all update apt-get update/upgrade

I created an user account (anna) and add it in sudo group

I loged into anna account

I downloaded Anaconda2-4.4.0-Linux-x86_64.sh for python 2.7

I installed with the command sudo bash Anaconda2-4.4.0-Linux-x86_64.sh

I installed anaconda in /opt/anaconda2 instead to the /home/anna/anaconda2 (for all user usage) and I say YES to have the line export PATH="/opt/anaconda2/bin:$PATH" in .bashrc file of anna

I run source /home/anna/.bashrc

After the anaconda installation, I could see a successful message regarding the installation

Now my colleague asked me to install mayavi and she provided me the following link mayavi

Then I simply enter the following command
conda install -c anaconda mayavi=4.5.0

And here start my problem. I can not well understand the conflict but apparently there is a conflict and I have no idea how to solve it. Here is the command and the message

```<code>anna@pc17:~$ conda install -c anaconda mayavi=4.5.0
Fetching package metadata ...........
Solving package specifications: .

UnsatisfiableError: The following specifications were found to be in conflict:
  - mayavi 4.5.0* -> pyqt 4.* -> qt >=4.8.6,<5.0
  - mayavi 4.5.0* -> pyqt 4.* -> sip >=4.16.4,<4.18
  - navigator-updater -> pyqt >=5.6 -> qt 5.6.*
Use "conda info <package>" to see the dependencies for each package.
</code>```

I have no idea what does mean the above message and how to solve me problem.
Is there depencies that I have to additionally install?

For information the above command return me this:

```<code>anna@cryospc17:~$ python --version
Python 2.7.13 :: Anaconda 4.4.0 (64-bit)
anna@cryospc17:~$ python3 --version
Python 3.5.2
</code>```

Did I correctly try t install mayavi?

Thank a lot for any help you can provide me

答:
This might be helpfull to others. It must be anaconda for python 2.7 currently and the follows worked.

Install anaconda for python 2.7, then try the follows:

```<code>conda uninstall pyqt
conda uninstall navigator-updater

conda install pyqt=4
conda install vtk
conda install envisage
conda install pyside
conda install apptools=4.4.0
conda install mayavi
</code>```

Body:
Good day,
My colleague asked my to install Anaconda and mayavi and I am novice with this topic and I decided to do the tasks on a new ubuntu installation

Here are my tasks before my issue

I fresh installed a Ubuntu 16.04

I ran all update apt-get update/upgrade

I created an user account (anna) and add it in sudo group

I loged into anna account

I downloaded Anaconda2-4.4.0-Linux-x86_64.sh for python 2.7

I installed with the command sudo bash Anaconda2-4.4.0-Linux-x86_64.sh

I installed anaconda in /opt/anaconda2 instead to the /home/anna/anaconda2 (for all user usage) and I say YES to have the line export PATH="/opt/anaconda2/bin:$PATH" in .bashrc file of anna

I run source /home/anna/.bashrc

After the anaconda installation, I could see a successful message regarding the installation

Now my colleague asked me to install mayavi and she provided me the following link mayavi

Then I simply enter the following command
conda install -c anaconda mayavi=4.5.0

And here start my problem. I can not well understand the conflict but apparently there is a conflict and I have no idea how to solve it. Here is the command and the message

anna@pc17:~$ conda install -c anaconda mayavi=4.5.0
Fetching package metadata ...........
Solving package specifications: .

UnsatisfiableError: The following specifications were found to be in conflict:
  - mayavi 4.5.0* -> pyqt 4.* -> qt >=4.8.6,<5.0
  - mayavi 4.5.0* -> pyqt 4.* -> sip >=4.16.4,<4.18
  - navigator-updater -> pyqt >=5.6 -> qt 5.6.*
Use "conda info <package>" to see the dependencies for each package.

I have no idea what does mean the above message and how to solve me problem.
Is there depencies that I have to additionally install?

For information the above command return me this:

anna@cryospc17:~$ python --version
Python 2.7.13 :: Anaconda 4.4.0 (64-bit)
anna@cryospc17:~$ python3 --version
Python 3.5.2

Did I correctly try t install mayavi?

Thank a lot for any help you can provide me

Body:
This might be helpfull to others. It must be anaconda for python 2.7 currently and the follows worked.

Install anaconda for python 2.7, then try the follows:

conda uninstall pyqt
conda uninstall navigator-updater

conda install pyqt=4
conda install vtk
conda install envisage
conda install pyside
conda install apptools=4.4.0
conda install mayavi


答:
By using the lang argument

```<code>var options = new ChromeOptions();
options.AddArgument("lang=en-GB");
var driver = new ChromeDriver(options);
</code>```

Title: ChromeOptions to change the language from US to UK

Body:
What are the ChromeOptions (C#) to change the default language of the browser from US to UK using Selenium v3 and Chrome v60+?

Thanks

Body:
By using the lang argument

var options = new ChromeOptions();
options.AddArgument("lang=en-GB");
var driver = new ChromeDriver(options);


问:
Casper.js Get webpage and display
Is there any way to use casper.js to login to a page then display the page?
I can take screen shots I want it to be the actual page.

Here what I have so far, although Im sure its very wrong:

```<code>var casper = require('casper').create({
 viewportSize: {
    width: 1365,
    height: 768
},
// engine: 'slimmerjs',
verbose: true,
logLevel: "debug",
pageSettings: {
loadImages: false,//The script is much faster when this field is set to false
loadPlugins: false,
userAgent: 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36  (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'
}
});

//First step is to open
casper.start().thenOpen("http://mysite/login", function() {
console.log("mysite website opened");
});

//Now we have to populate username and password, and submit the form
casper.then(function(){
console.log("Login using username and password");
this.evaluate(function(){
document.getElementById("user_email").value="me";
document.getElementById("user_password").value="password";
document.getElementById('new_user').submit();
});
});
casper.thenOpen('http://mysite/report/70?dashboard_id=2', function(){
console.log("Make a screenshot of morning info and save it as  pic.png");
this.wait(10000, function(){
this.captureSelector('pic.png','.highcharts- container');
});
});

casper.start("http://mysite/report/70?dashboard_id=2", function() {
this.page.switchToChildFrame(0);
this.page.switchToParentFrame();
});

casper.run(function() {
  this.exit();
});

casper.run();
</code>```

答:
If you want to capture the HTML, this is how you do it in Casper.

At the point you want this capture (after login..), within the same wait you have for the snapshot..  try this:

```<code>this.wait(10000, function(){
    this.captureSelector('pic.png','.highcharts- container');

    var HTML = document.createElement('textarea);
    HTML.innerHTML = this.getHTML();
    console.log(HTML.value);  // or use the variable for something else
});
</code>```

Having used CasperJS for 4 years to perform web scraping, that was the only method I could devise that worked and gave me good parseable HTML.

Title: Casper.js Get webpage and display

Body:
Is there any way to use casper.js to login to a page then display the page?
I can take screen shots I want it to be the actual page.

Here what I have so far, although Im sure its very wrong:

var casper = require('casper').create({
 viewportSize: {
    width: 1365,
    height: 768
},
// engine: 'slimmerjs',
verbose: true,
logLevel: "debug",
pageSettings: {
loadImages: false,//The script is much faster when this field is set to false
loadPlugins: false,
userAgent: 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36  (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'
}
});

//First step is to open
casper.start().thenOpen("http://mysite/login", function() {
console.log("mysite website opened");
});

//Now we have to populate username and password, and submit the form
casper.then(function(){
console.log("Login using username and password");
this.evaluate(function(){
document.getElementById("user_email").value="me";
document.getElementById("user_password").value="password";
document.getElementById('new_user').submit();
});
});
casper.thenOpen('http://mysite/report/70?dashboard_id=2', function(){
console.log("Make a screenshot of morning info and save it as  pic.png");
this.wait(10000, function(){
this.captureSelector('pic.png','.highcharts- container');
});
});

casper.start("http://mysite/report/70?dashboard_id=2", function() {
this.page.switchToChildFrame(0);
this.page.switchToParentFrame();
});

casper.run(function() {
  this.exit();
});

casper.run();

Body:
If you want to capture the HTML, this is how you do it in Casper.

At the point you want this capture (after login..), within the same wait you have for the snapshot..  try this:

this.wait(10000, function(){
    this.captureSelector('pic.png','.highcharts- container');

    var HTML = document.createElement('textarea);
    HTML.innerHTML = this.getHTML();
    console.log(HTML.value);  // or use the variable for something else
});

Having used CasperJS for 4 years to perform web scraping, that was the only method I could devise that worked and gave me good parseable HTML.


问:
Why is code behavior different in release & debug mode?
Consider the following code:

```<code>private static void Main(string[] args)
{
    var ar = new double[]
    {
        100
    };

    FillTo(ref ar, 5);
    Console.WriteLine(string.Join(",", ar.Select(a => a.ToString()).ToArray()));
}

public static void FillTo(ref double[] dd, int N)
{
    if (dd.Length >= N)
        return;

    double[] Old = dd;
    double d = double.NaN;
    if (Old.Length > 0)
        d = Old[0];

    dd = new double[N];

    for (int i = 0; i < Old.Length; i++)
    {
        dd[N - Old.Length + i] = Old[i];
    }
    for (int i = 0; i < N - Old.Length; i++)
        dd[i] = d;
}
</code>```

The result in Debug mode is: 100,100,100,100,100.
But in Release mode it is: 100,100,100,100,0.

What is happening?

It was tested using .NET framework 4.7.1 and .NET Core 2.0.0.

答:
It's an assembly error indeed. x64, .net 4.7.1, release build.

disassembly:

```<code>            for(int i = 0; i < N - Old.Length; i++)
00007FF942690ADD  xor         eax,eax
            for(int i = 0; i < N - Old.Length; i++)
00007FF942690ADF  mov         ebx,esi
00007FF942690AE1  sub         ebx,ebp
00007FF942690AE3  test        ebx,ebx
00007FF942690AE5  jle         00007FF942690AFF
                dd[i] = d;
00007FF942690AE7  mov         rdx,qword ptr [rdi]
00007FF942690AEA  cmp         eax,dword ptr [rdx+8]
00007FF942690AED  jae         00007FF942690B11
00007FF942690AEF  movsxd      rcx,eax
00007FF942690AF2  vmovsd      qword ptr [rdx+rcx*8+10h],xmm6
            for(int i = 0; i < N - Old.Length; i++)
00007FF942690AF9  inc         eax
00007FF942690AFB  cmp         ebx,eax
00007FF942690AFD  jg          00007FF942690AE7
00007FF942690AFF  vmovaps     xmm6,xmmword ptr [rsp+20h]
00007FF942690B06  add         rsp,30h
00007FF942690B0A  pop         rbx
00007FF942690B0B  pop         rbp
00007FF942690B0C  pop         rsi
00007FF942690B0D  pop         rdi
00007FF942690B0E  pop         r14
00007FF942690B10  ret
</code>```

The issue is at address 00007FF942690AFD, the jg 00007FF942690AE7. It jumps back if ebx (which contains 4, the loop end value) is bigger (jg) than eax, the value i. This fails when it's 4 of course, so it doesn't write the last element in the array.

It fails, because it inc's i's register value (eax, at 0x00007FF942690AF9), and then checks it with 4, but it still has to write that value. It's a bit hard to pinpoint where exactly the issue is located, as it looks like it might be the result of the optimization of (N-Old.Length), as the debug build contains that code, but the release build precalculates that. So that's for the jit people to fix ;)

Body:
Consider the following code:

private static void Main(string[] args)
{
    var ar = new double[]
    {
        100
    };

    FillTo(ref ar, 5);
    Console.WriteLine(string.Join(",", ar.Select(a => a.ToString()).ToArray()));
}

public static void FillTo(ref double[] dd, int N)
{
    if (dd.Length >= N)
        return;

    double[] Old = dd;
    double d = double.NaN;
    if (Old.Length > 0)
        d = Old[0];

    dd = new double[N];

    for (int i = 0; i < Old.Length; i++)
    {
        dd[N - Old.Length + i] = Old[i];
    }
    for (int i = 0; i < N - Old.Length; i++)
        dd[i] = d;
}

The result in Debug mode is: 100,100,100,100,100.
But in Release mode it is: 100,100,100,100,0.

What is happening?

It was tested using .NET framework 4.7.1 and .NET Core 2.0.0.

Body:
It's an assembly error indeed. x64, .net 4.7.1, release build.

disassembly:

            for(int i = 0; i < N - Old.Length; i++)
00007FF942690ADD  xor         eax,eax
            for(int i = 0; i < N - Old.Length; i++)
00007FF942690ADF  mov         ebx,esi
00007FF942690AE1  sub         ebx,ebp
00007FF942690AE3  test        ebx,ebx
00007FF942690AE5  jle         00007FF942690AFF
                dd[i] = d;
00007FF942690AE7  mov         rdx,qword ptr [rdi]
00007FF942690AEA  cmp         eax,dword ptr [rdx+8]
00007FF942690AED  jae         00007FF942690B11
00007FF942690AEF  movsxd      rcx,eax
00007FF942690AF2  vmovsd      qword ptr [rdx+rcx*8+10h],xmm6
            for(int i = 0; i < N - Old.Length; i++)
00007FF942690AF9  inc         eax
00007FF942690AFB  cmp         ebx,eax
00007FF942690AFD  jg          00007FF942690AE7
00007FF942690AFF  vmovaps     xmm6,xmmword ptr [rsp+20h]
00007FF942690B06  add         rsp,30h
00007FF942690B0A  pop         rbx
00007FF942690B0B  pop         rbp
00007FF942690B0C  pop         rsi
00007FF942690B0D  pop         rdi
00007FF942690B0E  pop         r14
00007FF942690B10  ret

The issue is at address 00007FF942690AFD, the jg 00007FF942690AE7. It jumps back if ebx (which contains 4, the loop end value) is bigger (jg) than eax, the value i. This fails when it's 4 of course, so it doesn't write the last element in the array.

It fails, because it inc's i's register value (eax, at 0x00007FF942690AF9), and then checks it with 4, but it still has to write that value. It's a bit hard to pinpoint where exactly the issue is located, as it looks like it might be the result of the optimization of (N-Old.Length), as the debug build contains that code, but the release build precalculates that. So that's for the jit people to fix ;)


问:
iOS Keychain writing value results in error code -34018
I have an iOS application that stores some sensitive information in the keychain.
While writing values into the keychain, I am getting error code -34018.

I am currently using Apple's iOS KeyChainItemWrapper class.

Both of the following lines of code receive the same error code.

```<code>OSStatus res1 = SecItemCopyMatching((__bridge CFDictionaryRef)genericPasswordQuery, (CFTypeRef *)&attributes);
OSStatus res = SecItemUpdate((__bridge CFDictionaryRef)updateItem, (__bridge CFDictionaryRef)tempCheck);
</code>```

This issue does not occur every time, but intermittently. Once I get this error, I am no longer able to write any values to the keychain.

I have printed the error description like so:

```<code>NSError *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:res userInfo:nil];
</code>```

and this is what the error prints out:

```<code>Error: Error Domain=NSOSStatusErrorDomain Code=-34018 "The operation couldn’t be completed. (OSStatus error -34018.)"
</code>```

答:
I am using GenericKeychain classes from apple:

https://developer.apple.com/library/content/samplecode/GenericKeychain/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007797-Intro-DontLinkElementID_2

```<code>struct KeychainConfiguration {

static let serviceName = "MyAppService"

/*

    Specifying an access group to use with `KeychainPasswordItem` instances will create items shared accross both apps.

    For information on App ID prefixes, see:

        https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/AppID.html
    and:
        https://developer.apple.com/library/ios/technotes/tn2311/_index.html
*/

//    static let accessGroup = "[YOUR APP ID PREFIX].com.example.apple-samplecode.GenericKeychainShared"

/*

    Not specifying an access group to use with `KeychainPasswordItem` instances

    will create items specific to each app.

*/

static let accessGroup: String? = nil

}
</code>```

In this file I was specifying my custom accessGroup in this line static let accessGroup = "[YOUR APP ID PREFIX].com.example.apple-samplecode.GenericKeychainShared"

After returning to static let accessGroup: String? = nil the problem was gone. :)

Body:
I have an iOS application that stores some sensitive information in the keychain.
While writing values into the keychain, I am getting error code -34018.

I am currently using Apple's iOS KeyChainItemWrapper class.

Both of the following lines of code receive the same error code.

OSStatus res1 = SecItemCopyMatching((__bridge CFDictionaryRef)genericPasswordQuery, (CFTypeRef *)&attributes);
OSStatus res = SecItemUpdate((__bridge CFDictionaryRef)updateItem, (__bridge CFDictionaryRef)tempCheck);

This issue does not occur every time, but intermittently. Once I get this error, I am no longer able to write any values to the keychain.

I have printed the error description like so:

NSError *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:res userInfo:nil];

and this is what the error prints out:

Error: Error Domain=NSOSStatusErrorDomain Code=-34018 "The operation couldn’t be completed. (OSStatus error -34018.)"

Body:
I am using GenericKeychain classes from apple:

https://developer.apple.com/library/content/samplecode/GenericKeychain/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007797-Intro-DontLinkElementID_2

struct KeychainConfiguration {

static let serviceName = "MyAppService"

/*

    Specifying an access group to use with `KeychainPasswordItem` instances will create items shared accross both apps.

    For information on App ID prefixes, see:

        https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/AppID.html
    and:
        https://developer.apple.com/library/ios/technotes/tn2311/_index.html
*/

//    static let accessGroup = "[YOUR APP ID PREFIX].com.example.apple-samplecode.GenericKeychainShared"

/*

    Not specifying an access group to use with `KeychainPasswordItem` instances

    will create items specific to each app.

*/

static let accessGroup: String? = nil

}

In this file I was specifying my custom accessGroup in this line static let accessGroup = "[YOUR APP ID PREFIX].com.example.apple-samplecode.GenericKeychainShared"

After returning to static let accessGroup: String? = nil the problem was gone. :)


问:
Distinguishing first launch on UI Tests
I want to use Fastlane Snapshot in order to generate screenshots for my app. But the behavior of the app is different when launch for the first time and launching after that.
How do I manage to get a consistent behavior in order to grab the screenshots?
(this question is also relevant for any UI test desired consistency I presume)

答:
You should be using UserDefaults class to preserve data in your app so that you can stub data in your tests.

If we assume that the Bool key you use to see if it's the first launch is isFirstTime, in order to stub it in your UI test, you should pass it to launchArguments following the value YES or NO (for Bool values). Note that I added - sign before key, this is the way it works:

```<code>class FirstTimeLaunchTest: XCTestCase {

    let app = XCUIApplication()

    override func setUp() {
        super.setUp()
        continueAfterFailure = false

        app.launchArguments += ["-isFirstTime", "YES"]
        app.launch()
    }

    func testWelcomeScreenShown() {
        XCTAssert(app.navigationBars["Welcome"].exists)
    }
}
</code>```

For tests where you'd like to have first start skipped, use this class:

```<code>class LaterLaunchesTest: XCTestCase {

    let app = XCUIApplication()

    override func setUp() {
        super.setUp()
        continueAfterFailure = false

        app.launchArguments += ["-isFirstTime", "NO"]
        app.launch()
    }

    func testMainAppScreenShown() {
        XCTAssert(app.navigationBars["My App"].exists)
    }
}
</code>```

One note though: If you are using SwiftyUserDefaults library, this solution wouldn't work. There is a problem in the current version of the library where converting YES and NO strings to true and false is not working as expected. There was a PR that solved this problem (that is rejected), but to solve this problem, you can look at the solutions #2 and #3 from this answer.

Title: Distinguishing first launch on UI Tests

Body:
You should be using UserDefaults class to preserve data in your app so that you can stub data in your tests.

If we assume that the Bool key you use to see if it's the first launch is isFirstTime, in order to stub it in your UI test, you should pass it to launchArguments following the value YES or NO (for Bool values). Note that I added - sign before key, this is the way it works:

class FirstTimeLaunchTest: XCTestCase {

    let app = XCUIApplication()

    override func setUp() {
        super.setUp()
        continueAfterFailure = false

        app.launchArguments += ["-isFirstTime", "YES"]
        app.launch()
    }

    func testWelcomeScreenShown() {
        XCTAssert(app.navigationBars["Welcome"].exists)
    }
}

For tests where you'd like to have first start skipped, use this class:

class LaterLaunchesTest: XCTestCase {

    let app = XCUIApplication()

    override func setUp() {
        super.setUp()
        continueAfterFailure = false

        app.launchArguments += ["-isFirstTime", "NO"]
        app.launch()
    }

    func testMainAppScreenShown() {
        XCTAssert(app.navigationBars["My App"].exists)
    }
}

One note though: If you are using SwiftyUserDefaults library, this solution wouldn't work. There is a problem in the current version of the library where converting YES and NO strings to true and false is not working as expected. There was a PR that solved this problem (that is rejected), but to solve this problem, you can look at the solutions #2 and #3 from this answer.


问:
c++11: Array bound is not an integer constant before a token
I have seen this question, but the solution provided there doesn't solve the issue.

```<code>static int num_instances;
std::vector<SomeClass::FunctionWithinTheClass> *mem[num_instances];
</code>```

SomeClass::FunctionWithinTheClass *mem[num_instances]; //Even this raises an error

the value num_instances is obtained by reading a configuration file.

The error I get is :
array bound is not an integer constant before ‘]’ token

This is strange because the value num_instances is fixed at compile time.

答:
the value num_instances is obtained by reading a configuration file

and

... the config file is read at runtime

That means num_instances is a variable whose value is determined at run time.

This is strange because the value num_instances is fixed at compile time

No it isn't, you're contradicting yourself.

If it's loaded from config at run time, it wasn't known at compile time. If it was known at compile time, you wouldn't be loading it from config at run time.

If you cannot fix num_instances at compile time, an array is the wrong thing to use. Just change it to

```<code>// like an array whose size can be set at runtime ...
std::vector<std::vector<SomeClass::FunctionWithinTheClass>> mem;

void configure() {
    size_t num_instances = loadNumInstancesFromConfig();
    mem.resize(num_instances);
}
</code>```

Body:
I have seen this question, but the solution provided there doesn't solve the issue.

static int num_instances;
std::vector<SomeClass::FunctionWithinTheClass> *mem[num_instances];

SomeClass::FunctionWithinTheClass *mem[num_instances]; //Even this raises an error

the value num_instances is obtained by reading a configuration file.

The error I get is :
array bound is not an integer constant before ‘]’ token

This is strange because the value num_instances is fixed at compile time.

Body:
the value num_instances is obtained by reading a configuration file

and

... the config file is read at runtime

That means num_instances is a variable whose value is determined at run time.

This is strange because the value num_instances is fixed at compile time

No it isn't, you're contradicting yourself.

If it's loaded from config at run time, it wasn't known at compile time. If it was known at compile time, you wouldn't be loading it from config at run time.

If you cannot fix num_instances at compile time, an array is the wrong thing to use. Just change it to

// like an array whose size can be set at runtime ...
std::vector<std::vector<SomeClass::FunctionWithinTheClass>> mem;

void configure() {
    size_t num_instances = loadNumInstancesFromConfig();
    mem.resize(num_instances);
}


问:
Resize one image multiple times
I am resizing a given image (saved on disk) to different sizes:

```<code>var image = 'photos/pic';
var sizes = [1440, 1080, 720, 480];

for (var i = 0; i < sizes.length; i++) {
    sharp(image + '.jpg')
    .resize(sizes[i], sizes[i])
    .toFile(image + '-' + sizes[i] + '.jpg');
}
</code>```

This works as expected, but I guess there is room for improvements.

Will the for-loop lead to any problems? If yes, is there a better way
to solve that?

Would it be faster to wait for the generated picture to be resized and use this for the next resizing process? Let's say the original picture is 2000x2000. What's the speed improvement from resizing 720x720 to 480x480 instead of 2000x2000 to 480x480, if there is any? Considering I have to read the 720x720 file first and wait for the resizing to be finished.

Should I do those resizes on the "main" node thread or fork a child process? They are running asynchronously anyways, correct?

答:
You can use the Clone method for Sharp JS

http://sharp.dimens.io/en/stable/api-input/#clone

The example gives it all you need

```<code>// Create the baseline changes
const pipeline = sharp().rotate();

pipeline.clone().resize(800, 600).pipe(firstWritableStream);
pipeline.clone().extract({ left: 20, top: 20, width: 100, height: 100
  }).pipe(secondWritableStream);

readableStream.pipe(pipeline);
</code>```

Can also use this with promises

Title: Resize one image multiple times

Body:
I am resizing a given image (saved on disk) to different sizes:

var image = 'photos/pic';
var sizes = [1440, 1080, 720, 480];

for (var i = 0; i < sizes.length; i++) {
    sharp(image + '.jpg')
    .resize(sizes[i], sizes[i])
    .toFile(image + '-' + sizes[i] + '.jpg');
}

This works as expected, but I guess there is room for improvements.

Will the for-loop lead to any problems? If yes, is there a better way
to solve that?

Would it be faster to wait for the generated picture to be resized and use this for the next resizing process? Let's say the original picture is 2000x2000. What's the speed improvement from resizing 720x720 to 480x480 instead of 2000x2000 to 480x480, if there is any? Considering I have to read the 720x720 file first and wait for the resizing to be finished.

Should I do those resizes on the "main" node thread or fork a child process? They are running asynchronously anyways, correct?

Body:
You can use the Clone method for Sharp JS

http://sharp.dimens.io/en/stable/api-input/#clone

The example gives it all you need

// Create the baseline changes
const pipeline = sharp().rotate();

pipeline.clone().resize(800, 600).pipe(firstWritableStream);
pipeline.clone().extract({ left: 20, top: 20, width: 100, height: 100
  }).pipe(secondWritableStream);

readableStream.pipe(pipeline);

Can also use this with promises


问:
Pandas DataFrames: how to wrap text with no whitespace
I'm viewing a Pandas DataFrame in a Jupyter Notebook, and my DataFrame contains URL request strings that can be hundreds of characters long without any whitespace separating characters.

Pandas seems to only wrap text in a cell when there's whitespace, as shown on the attached picture:

If there isn't whitespace, the string is displayed in a single line, and if there isn't enough space my options are either to see a '...' or I have to set display.max_colwidth to a huge number and now I have a hard-to-read table with a lot of scrolling.

Is there a way to force Pandas to wrap text, say, every 100 characters, regardless of whether there is whitespace?

答:
You can use str.wrap method:

```<code>df['user_agent'] = df['user_agent'].str.wrap(100) #to set max line width of 100
</code>```

Body:
You can use str.wrap method:

df['user_agent'] = df['user_agent'].str.wrap(100) #to set max line width of 100


问:
How to update angularjs.module.value with array and retrieving it through service?
I'm trying to update a global angularjs module.value in one controller with an array, and then retrieving that global array through in a  service. But the array doesn't exist.

app.js

```<code>  app.factory('featureClaims', function($q) {
    var featureClaims = {};

    featureClaims.init = function() {
        featureClaims.claims = [];
    }
    featureClaims.get = function() {
        return $q.when(featureClaims.claims);
    }
    featureClaims.set = function(data) {
        featureClaims.claims = data;
        return $q.when(featureClaims.claims); // I'm using the $q library to return a promise.
    }
    return featureClaims;
});
</code>```

loginController

```<code>let loginController = function($scope, loginService, toastrObj, featureClaims) {
   $scope.login = function(){
            featureClaims.init();
            featureClaims.set(result.data.FeatureClaims); // updating ok here
   }
}

app.controller("loginController", ["$scope", 'loginService', 'toastrObj', 'featureClaims',loginController]);
</code>```

home service

```<code>let homeService= function(featureClaims) {   // featureClaims.claims is null
    return{
        validateUser: function(expectedClaim) {
            if(expectedClaim !== ""){
                featureClaims.get().then(function(data){
                    return data.includes(expectedClaim);  // data is return as undefined
                })
            }

            return false;
        }
    }
};
app.factory('homeService',['featureClaims', homeService]);
</code>```

答:
I don't think you can use a value service this way. From this post the author states: "Note: Make sure that you never overwrite the value service/object as a whole otherwise your assignment is lost. Always reassign the property values of the value object. The following assignment is wrong and does not lead to the expected behavior"

Instead why don't you convert your value to a factory like so:

```<code>app.factory('featureClaims', function($q) {
    var featureClaims = {};

    featureClaims.init = function() {
        featureClaims.claims = [];
    }

    featureClaims.get = function() {
        return $q.when(featureClaims.claims);
    }

    featureClaims.set = function(data) {
        featureClaims.claims = data;
        return $q.when(featureClaims.claims); // I'm using the $q library to return a promise.
    }
    return featureClaims;
});
</code>```

In your controller:

```<code>featureClaims.init();
// you need to wait for the promise to resolve with 'then'
featureClaims.set(['foo', 'bar']).then(function(response) {
   console.log(response); // logs ["foo", "bar"]
});

featureClaims.get().then(function(response) {
   console.log(response); // logs ["foo", "bar"]
});
</code>```

Tested and working. You will want to create a get method that simply returns the data instead of setting it first.

Body:
I'm trying to update a global angularjs module.value in one controller with an array, and then retrieving that global array through in a  service. But the array doesn't exist.

app.js

  app.factory('featureClaims', function($q) {
    var featureClaims = {};

    featureClaims.init = function() {
        featureClaims.claims = [];
    }
    featureClaims.get = function() {
        return $q.when(featureClaims.claims);
    }
    featureClaims.set = function(data) {
        featureClaims.claims = data;
        return $q.when(featureClaims.claims); // I'm using the $q library to return a promise.
    }
    return featureClaims;
});

loginController

let loginController = function($scope, loginService, toastrObj, featureClaims) {
   $scope.login = function(){
            featureClaims.init();
            featureClaims.set(result.data.FeatureClaims); // updating ok here
   }
}

app.controller("loginController", ["$scope", 'loginService', 'toastrObj', 'featureClaims',loginController]);

home service

let homeService= function(featureClaims) {   // featureClaims.claims is null
    return{
        validateUser: function(expectedClaim) {
            if(expectedClaim !== ""){
                featureClaims.get().then(function(data){
                    return data.includes(expectedClaim);  // data is return as undefined
                })
            }

            return false;
        }
    }
};
app.factory('homeService',['featureClaims', homeService]);

Body:
I don't think you can use a value service this way. From this post the author states: "Note: Make sure that you never overwrite the value service/object as a whole otherwise your assignment is lost. Always reassign the property values of the value object. The following assignment is wrong and does not lead to the expected behavior"

Instead why don't you convert your value to a factory like so:

app.factory('featureClaims', function($q) {
    var featureClaims = {};

    featureClaims.init = function() {
        featureClaims.claims = [];
    }

    featureClaims.get = function() {
        return $q.when(featureClaims.claims);
    }

    featureClaims.set = function(data) {
        featureClaims.claims = data;
        return $q.when(featureClaims.claims); // I'm using the $q library to return a promise.
    }
    return featureClaims;
});

In your controller:

featureClaims.init();
// you need to wait for the promise to resolve with 'then'
featureClaims.set(['foo', 'bar']).then(function(response) {
   console.log(response); // logs ["foo", "bar"]
});

featureClaims.get().then(function(response) {
   console.log(response); // logs ["foo", "bar"]
});

Tested and working. You will want to create a get method that simply returns the data instead of setting it first.


问:
Free alternative to MPLAB (PIC development)
I started using MPLAB recently, but for someone that works with Eclipse and VS the IDE it's very limited. Do you know any free IDE or how to configure Ecplise or Netbeans to PIC development?

Thanks all

答:
The underlying toolchain (compiler/linker etc.) can be used from any environment including Eclipse and Visual Studio, though Eclipse is probably the more flexible in this respect.

MPLAB has a feature to export a project as a makefile that can be used with GNU make, although you may rather generate your own makefile, or use the project management provided by Eclipse.  In Visual Studio, create a Makefile Project, despite its name, you can specify any build command line, so invoke a batch file or makefile as necessary. Eclipse can use makefile projects also.

In Visual Studio, add all your project and compiler Include paths to teh project manually to get all the Intellisense navigation features to work.


问:
How to fetch custom label phone numbers in address book swift
I am trying to fetch custom label phone number's using address book (swift).

I have tried with kABOtherLabel property but i did not got desired result.

I would like to know is there any way to fetch custom label properties..?

Here i am sharing what i am doing currently.

Thanks in advance.

```<code>//phone

var phones : ABMultiValueRef = ABRecordCopyValue(contactRef,kABPersonPhoneProperty).takeUnretainedValue() as ABMultiValueRef

        for(var numberIndex : CFIndex = 0; numberIndex < ABMultiValueGetCount(phones); numberIndex++)
        {

            // Number in contact details of current index

            let phoneUnmaganed = ABMultiValueCopyValueAtIndex(phones, numberIndex)

            let phoneNumber : NSString = phoneUnmaganed.takeUnretainedValue() as! NSString

            // Label of Phone Number

            let locLabel : CFStringRef = (ABMultiValueCopyLabelAtIndex(phones, numberIndex) != nil) ? ABMultiValueCopyLabelAtIndex(phones, numberIndex).takeUnretainedValue() as CFStringRef : ""

            //check for home
            if (String(locLabel) == String(kABHomeLabel))
            {
                contact.sUserTelHome =  phoneNumber as String
                contact.sUserTelHomeTrim = contact.sUserTelHome?.trimmedContactNumber()

            }

                //check for work
            else if (String(locLabel) == String(kABWorkLabel))
            {
                contact.sUserTelWork = phoneNumber as String
                contact.sUserTelWorkTrim = contact.sUserTelWork?.trimmedContactNumber()

            }

                //check for mobile
            else if (String(locLabel) == String(kABPersonPhoneMobileLabel))
            {
                contact.sUserTelMobile = phoneNumber as String
                contact.sUserTelMobileTrim = contact.sUserTelMobile?.trimmedContactNumber()
            }

            else if(String(locLabel) == String(kABOtherLabel)){

            }
}
</code>```

答:
Works for Swift 3 (update of Aju's code):</p>

```<code>let status = ABAddressBookGetAuthorizationStatus()
        if status == .denied || status == .restricted {
            // user previously denied, to tell them to fix that in settings
            return
        }

        // open it

        var error: Unmanaged<CFError>?
        let addressBook: ABAddressBook? = ABAddressBookCreateWithOptions(nil, &error)?.takeRetainedValue()
        if addressBook == nil {
            print(error?.takeRetainedValue() as Any)
            return
        }

        // request permission to use it
        ABAddressBookRequestAccessWithCompletion(addressBook) {
            granted, error in

            if !granted {
                // warn the user that because they just denied permission, this functionality won't work
                // also let them know that they have to fix this in settings
                return
            }

            if let people: Array<ABRecord> = ABAddressBookCopyArrayOfAllPeople(self.addressBookRef)?.takeRetainedValue() as Array<ABRecord>? {
                // now do something with the array of people

                for record:ABRecord in people {
                let phones : ABMultiValue = ABRecordCopyValue(record,kABPersonPhoneProperty).takeUnretainedValue() as ABMultiValue

                for numberIndex:CFIndex in 0 ... ABMultiValueGetCount(phones)-1
                {
                    let phoneUnmaganed = ABMultiValueCopyValueAtIndex(phones, numberIndex)
                    let phoneNumber : String = phoneUnmaganed!.takeUnretainedValue() as! String

                    let locLabel: CFString = (ABMultiValueCopyLabelAtIndex(phones, numberIndex) != nil) ? ABMultiValueCopyLabelAtIndex(phones, numberIndex).takeUnretainedValue() as CFString : "" as CFString

                    //type of phone number
                    let cfStr:CFTypeRef = locLabel
                    let nsTypeString = cfStr as! String
                    let swiftString:String = nsTypeString as String

                    let customLabel = String (stringInterpolationSegment: ABAddressBookCopyLocalizedLabel(locLabel))
                    print("Name \(swiftString) NO \(phoneNumber)" )

                    }
                }

            }
        }
</code>```

Body:
I am trying to fetch custom label phone number's using address book (swift).

I have tried with kABOtherLabel property but i did not got desired result.

I would like to know is there any way to fetch custom label properties..?

Here i am sharing what i am doing currently.

Thanks in advance.

//phone

var phones : ABMultiValueRef = ABRecordCopyValue(contactRef,kABPersonPhoneProperty).takeUnretainedValue() as ABMultiValueRef

        for(var numberIndex : CFIndex = 0; numberIndex < ABMultiValueGetCount(phones); numberIndex++)
        {

            // Number in contact details of current index

            let phoneUnmaganed = ABMultiValueCopyValueAtIndex(phones, numberIndex)

            let phoneNumber : NSString = phoneUnmaganed.takeUnretainedValue() as! NSString

            // Label of Phone Number

            let locLabel : CFStringRef = (ABMultiValueCopyLabelAtIndex(phones, numberIndex) != nil) ? ABMultiValueCopyLabelAtIndex(phones, numberIndex).takeUnretainedValue() as CFStringRef : ""

            //check for home
            if (String(locLabel) == String(kABHomeLabel))
            {
                contact.sUserTelHome =  phoneNumber as String
                contact.sUserTelHomeTrim = contact.sUserTelHome?.trimmedContactNumber()

            }

                //check for work
            else if (String(locLabel) == String(kABWorkLabel))
            {
                contact.sUserTelWork = phoneNumber as String
                contact.sUserTelWorkTrim = contact.sUserTelWork?.trimmedContactNumber()

            }

                //check for mobile
            else if (String(locLabel) == String(kABPersonPhoneMobileLabel))
            {
                contact.sUserTelMobile = phoneNumber as String
                contact.sUserTelMobileTrim = contact.sUserTelMobile?.trimmedContactNumber()
            }

            else if(String(locLabel) == String(kABOtherLabel)){

            }
}

Body:
Works for Swift 3 (update of Aju's code):

let status = ABAddressBookGetAuthorizationStatus()
        if status == .denied || status == .restricted {
            // user previously denied, to tell them to fix that in settings
            return
        }

        // open it

        var error: Unmanaged<CFError>?
        let addressBook: ABAddressBook? = ABAddressBookCreateWithOptions(nil, &error)?.takeRetainedValue()
        if addressBook == nil {
            print(error?.takeRetainedValue() as Any)
            return
        }

        // request permission to use it
        ABAddressBookRequestAccessWithCompletion(addressBook) {
            granted, error in

            if !granted {
                // warn the user that because they just denied permission, this functionality won't work
                // also let them know that they have to fix this in settings
                return
            }

            if let people: Array<ABRecord> = ABAddressBookCopyArrayOfAllPeople(self.addressBookRef)?.takeRetainedValue() as Array<ABRecord>? {
                // now do something with the array of people

                for record:ABRecord in people {
                let phones : ABMultiValue = ABRecordCopyValue(record,kABPersonPhoneProperty).takeUnretainedValue() as ABMultiValue

                for numberIndex:CFIndex in 0 ... ABMultiValueGetCount(phones)-1
                {
                    let phoneUnmaganed = ABMultiValueCopyValueAtIndex(phones, numberIndex)
                    let phoneNumber : String = phoneUnmaganed!.takeUnretainedValue() as! String

                    let locLabel: CFString = (ABMultiValueCopyLabelAtIndex(phones, numberIndex) != nil) ? ABMultiValueCopyLabelAtIndex(phones, numberIndex).takeUnretainedValue() as CFString : "" as CFString

                    //type of phone number
                    let cfStr:CFTypeRef = locLabel
                    let nsTypeString = cfStr as! String
                    let swiftString:String = nsTypeString as String

                    let customLabel = String (stringInterpolationSegment: ABAddressBookCopyLocalizedLabel(locLabel))
                    print("Name \(swiftString) NO \(phoneNumber)" )

                    }
                }

            }
        }


问:
return self.func(*args) TypeError: menu() missing 1 required positional argument: 'self'
I keep getting this error and I cant seem to fix it, if anybody could help me I would really appreciate it. I have been looking at it for quite a while now and I can't seem to get my head around it, I am still quite new to programming in an Object Oriented Way.

Thanks & Merry Christmas

Welcome Page

```<code>from External_Menu import *
from tkinter import *

class Welcome(Frame):

def __init__(self, root):
    Frame.__init__(self, root)
    self.welcome_button()
    self.pack()

def welcome_button(self):
    self.welcome = Button(self, text="Welcome!", command=ExternalMenu.menu)
    self.welcome.pack()
    self.pack()

if __name__ == "__main__":
    root = Tk()
    main = Welcome(root)
    main.mainloop()
</code>```

External Menu

```<code>from tkinter import *

class ExternalMenu(Frame):

def __init__(self, root):
    Frame.__init__(self, root)
    self.menu()
    self.pack()

def menu(self):
    self.external_menu_lbl = Label(self, text="External Menu", font=("", 26))
    self.external_menu_lbl.pack()

    self.sign_in_button = Button(self, text="Sign In")
    self.sign_in_button.pack()

    self.sign_up_button = Button(self, text="Sign Up")
    self.sign_up_button.pack()

    self.pack()
</code>```

答:
Your menu is a method so it needs an object it can manipulate in order to work. But you're trying to call it without an object created for it, essentially you're calling it like a function. First you need to create an object of the class that method is defined on:

```<code>an_ex_men = ExternalMenu(root)
</code>```

and then you are able to call menu method on an_ex_men:

```<code>an_ex_men.menu()
</code>```

But since you already call menu under your ExternalMenu's __int__ method it is called as soon as an object instance for that class is created. Shortly, you creating an ExternalMenu object is enough to achieve that as in, even without putting it to a variable to refer later:

```<code>ExternalMenu(root)
</code>```

Since you want to swap between two windows you need an additional method to either hide or completely destroy the other window. Let's say you want to destroy the other window, and for that you could use a method defined for your button that does those 2 actions:

```<code>def welcome(self):
    self.destroy()
    ExternalMenu(root)
</code>```

As in:

```<code>...

    def welcome_button(self):
        self.welcome = Button(self, text="Welcome!", command=self.welcome)
        self.welcome.pack()

    def welcome(self):
        self.destroy()
        ExternalMenu(root)

...
</code>```

Below example does exactly what you expect, first I created a parent class App as according to you the two frames you have are in the same level of hierarchy and having a parent for them is in my opinion better structured:

```<code>import tkinter as tk

class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.welcome_frame = Welcome(self)
        #I believe it's better to call geometry managers as parent
        self.welcome_frame.pack()

        #assigning parent method as button command as it affects siblings
        self.welcome_frame.button['command'] = self.go_ex_men

    def go_ex_men(self):
        self.welcome_frame.destroy()
        self.ex_men = ExternalMenu(self)
        self.ex_men.pack()

class Welcome(tk.Frame):
    def __init__(self, master):
        super().__init__(master)

        self.button = tk.Button(self, text="Welcome!")
        self.button.pack()

class ExternalMenu(tk.Frame):
    def __init__(self, master):
        super().__init__(master)

        self.external_menu_lbl = tk.Label(self, text="External Menu", font=("", 26))
        self.external_menu_lbl.pack()

        self.sign_in_button = tk.Button(self, text="Sign In")
        self.sign_in_button.pack()

        self.sign_up_button = tk.Button(self, text="Sign Up")
        self.sign_up_button.pack()

if __name__ == "__main__":
    root = App()
    root.mainloop()
</code>```

Body:
I keep getting this error and I cant seem to fix it, if anybody could help me I would really appreciate it. I have been looking at it for quite a while now and I can't seem to get my head around it, I am still quite new to programming in an Object Oriented Way.

Thanks & Merry Christmas

Welcome Page

from External_Menu import *
from tkinter import *

class Welcome(Frame):

def __init__(self, root):
    Frame.__init__(self, root)
    self.welcome_button()
    self.pack()

def welcome_button(self):
    self.welcome = Button(self, text="Welcome!", command=ExternalMenu.menu)
    self.welcome.pack()
    self.pack()

if __name__ == "__main__":
    root = Tk()
    main = Welcome(root)
    main.mainloop()

External Menu

from tkinter import *

class ExternalMenu(Frame):

def __init__(self, root):
    Frame.__init__(self, root)
    self.menu()
    self.pack()

def menu(self):
    self.external_menu_lbl = Label(self, text="External Menu", font=("", 26))
    self.external_menu_lbl.pack()

    self.sign_in_button = Button(self, text="Sign In")
    self.sign_in_button.pack()

    self.sign_up_button = Button(self, text="Sign Up")
    self.sign_up_button.pack()

    self.pack()

Body:
Your menu is a method so it needs an object it can manipulate in order to work. But you're trying to call it without an object created for it, essentially you're calling it like a function. First you need to create an object of the class that method is defined on:

an_ex_men = ExternalMenu(root)

and then you are able to call menu method on an_ex_men:

an_ex_men.menu()

But since you already call menu under your ExternalMenu's __int__ method it is called as soon as an object instance for that class is created. Shortly, you creating an ExternalMenu object is enough to achieve that as in, even without putting it to a variable to refer later:

ExternalMenu(root)

Since you want to swap between two windows you need an additional method to either hide or completely destroy the other window. Let's say you want to destroy the other window, and for that you could use a method defined for your button that does those 2 actions:

def welcome(self):
    self.destroy()
    ExternalMenu(root)

As in:

...

    def welcome_button(self):
        self.welcome = Button(self, text="Welcome!", command=self.welcome)
        self.welcome.pack()

    def welcome(self):
        self.destroy()
        ExternalMenu(root)

...

Below example does exactly what you expect, first I created a parent class App as according to you the two frames you have are in the same level of hierarchy and having a parent for them is in my opinion better structured:

import tkinter as tk

class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.welcome_frame = Welcome(self)
        #I believe it's better to call geometry managers as parent
        self.welcome_frame.pack()

        #assigning parent method as button command as it affects siblings
        self.welcome_frame.button['command'] = self.go_ex_men

    def go_ex_men(self):
        self.welcome_frame.destroy()
        self.ex_men = ExternalMenu(self)
        self.ex_men.pack()

class Welcome(tk.Frame):
    def __init__(self, master):
        super().__init__(master)

        self.button = tk.Button(self, text="Welcome!")
        self.button.pack()

class ExternalMenu(tk.Frame):
    def __init__(self, master):
        super().__init__(master)

        self.external_menu_lbl = tk.Label(self, text="External Menu", font=("", 26))
        self.external_menu_lbl.pack()

        self.sign_in_button = tk.Button(self, text="Sign In")
        self.sign_in_button.pack()

        self.sign_up_button = tk.Button(self, text="Sign Up")
        self.sign_up_button.pack()

if __name__ == "__main__":
    root = App()
    root.mainloop()


问:
How to move existing git repository to new repository and preserve commit history
I want to move/clone repository into new location, migrate it from BitBucket to GitLab. I want to move all branches and preserve commit history.

I'd like to know if there is a way to do that via SourceTree or simply by command.
I tried searching for an answer but couldn't find a single, easy to understand tutorial.

答:
Assuming you have a blank repository set up in GitLab;</p>

```<code>git remote add gitlab <gitlab_repo_url>
git push --all gitlab
</code>```

Body:
Assuming you have a blank repository set up in GitLab;

git remote add gitlab <gitlab_repo_url>
git push --all gitlab


问:
How to mock localStorage in JavaScript unit tests?
Are there any libraries out there to mock localStorage?

I've been using Sinon.JS for most of my other javascript mocking and have found it is really great.

My initial testing shows that localStorage refuses to be assignable in firefox (sadface) so I'll probably need some sort of hack around this :/

My options as of now (as I see) are as follows:

Create wrapping functions that all my code uses and mock those

Create some sort of (might be complicated) state management (snapshot localStorage before test, in cleanup restore snapshot) for localStorage.

??????

What do you think of these approaches and do you think there are any other better ways to go about this?  Either way I'll put the resulting "library" that I end up making on github for open source goodness.

答:
This is how I like to do it. Keeps it simple.</p>

```<code>  let localStoreMock: any = {};

  beforeEach(() => {

    angular.mock.module('yourApp');

    angular.mock.module(function ($provide: any) {

      $provide.service('localStorageService', function () {
        this.get = (key: any) => localStoreMock[key];
        this.set = (key: any, value: any) => localStoreMock[key] = value;
      });

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

Body:
This is how I like to do it. Keeps it simple.

  let localStoreMock: any = {};

  beforeEach(() => {

    angular.mock.module('yourApp');

    angular.mock.module(function ($provide: any) {

      $provide.service('localStorageService', function () {
        this.get = (key: any) => localStoreMock[key];
        this.set = (key: any, value: any) => localStoreMock[key] = value;
      });

    });
  });