问:
xpath query to get other siblings by searching with array of values
```<code><multiRef id="id178" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="ns9:Map" xmlns:ns9="http://xml.apache.org/xml-soap" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
<key xsi:type="soapenc:string">templateContainerNames</key>
<value soapenc:arrayType="xsd:string[4]" xsi:type="soapenc:Array">
<value xsi:type="xsd:string">APM</value>
<value xsi:type="xsd:string">OPERATING_SYSTEM</value>
<value xsi:type="xsd:string">Unix_Virtual</value>
<value xsi:type="xsd:string">UNIX_HOST</value>
</value>
</item>
<key xsi:type="soapenc:string">Name</key>
<value xsi:type="soapenc:string">Unix_Remote_without_SSHKey</value>
</item>
</multiRef>
</code>```

I have the sample xml file and I would like to get value of 'Name' by passing templateContainerNames array values: [APM,OPERATING_SYSTEM,Unix_Virtual,UNIX_HOST].

How can I do this?

答:
I have got the solution myself. I found some clue on arrays somewhere and tried below query and it worked perfectly.

//value[value[1]='APM' and value[2]='OPERATING_SYSTEM' and value[3]='Unix_Virtual' and value[4]='UNIX_HOST']/../parent::*/item[key="Name"]/value

Thanks
Srinivas

Body:
<multiRef id="id178" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="ns9:Map" xmlns:ns9="http://xml.apache.org/xml-soap" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
<key xsi:type="soapenc:string">templateContainerNames</key>
<value soapenc:arrayType="xsd:string[4]" xsi:type="soapenc:Array">
<value xsi:type="xsd:string">APM</value>
<value xsi:type="xsd:string">OPERATING_SYSTEM</value>
<value xsi:type="xsd:string">Unix_Virtual</value>
<value xsi:type="xsd:string">UNIX_HOST</value>
</value>
</item>
<key xsi:type="soapenc:string">Name</key>
<value xsi:type="soapenc:string">Unix_Remote_without_SSHKey</value>
</item>
</multiRef>

I have the sample xml file and I would like to get value of 'Name' by passing templateContainerNames array values: [APM,OPERATING_SYSTEM,Unix_Virtual,UNIX_HOST].

How can I do this?


来源: stackexchange

问:
Django-Registration override Registration Form
I'm using Django-Registration 2.3 for a project and trying to override the standard RegistrationForm with the following:

```<code>class MyRegistrationForm(RegistrationForm):
    captcha = NoReCaptchaField()

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2']
        widgets = {
            'first_name' : forms.TextInput(attrs={'class' : 'form-control'}),
            'last_name' : forms.TextInput(attrs={'class' : 'form-control'}),
            'username' : forms.HiddenInput(),
            'email' : forms.EmailInput(attrs={'class' : 'form-control'}),
            'password1' : forms.PasswordInput(attrs={'class' : 'form-control'}),
            'password2' : forms.PasswordInput(attrs={'class' : 'form-control'}),
        }
</code>```

I'm then calling this from my urls.py with url(r'^accounts/register/$', RegistrationView.as_view(form_class=MyRegistrationForm), name='registration_register'),

In the template the captcha, first_name and last_name fields are rendered using form-control, the username is hidden but the other fields are rendered without the class.  What do I need to do?

答:
i had the same problem once and i used this </p>

```<code>
class MyRegistrationForm(RegistrationForm):
    captcha = NoReCaptchaField()
    first_name = forms.CharField(max_length=30, required=False, widget=forms.TextInput(attrs={'class': 'form-control'}))
    last_name = forms.CharField(max_length=30, required=False, widget=forms.TextInput(attrs={'class': 'form-control'}))
    email = forms.EmailField(max_length=254, widget=forms.TextInput(attrs={'class': 'form-control'}))
    password1 = forms.CharField(max_length=30, required=True, widget=forms.TextInput(attrs={'class': 'form-control',
                                                                                'name': "password1",
                                                                                'type': "password"}))
    password2 = forms.CharField(max_length=30, required=True, widget=forms.TextInput(attrs={'class': 'form-control',
                                                                                'name': "password2",
                                                                                'type': "password"}))
    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'email']
        widgets = {
            'username' : forms.TextInput(attrs = {'class': 'form-control'}),
        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using Django-Registration 2.3 for a project and trying to override the standard RegistrationForm with the following:

class MyRegistrationForm(RegistrationForm):
    captcha = NoReCaptchaField()

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2']
        widgets = {
            'first_name' : forms.TextInput(attrs={'class' : 'form-control'}),
            'last_name' : forms.TextInput(attrs={'class' : 'form-control'}),
            'username' : forms.HiddenInput(),
            'email' : forms.EmailInput(attrs={'class' : 'form-control'}),
            'password1' : forms.PasswordInput(attrs={'class' : 'form-control'}),
            'password2' : forms.PasswordInput(attrs={'class' : 'form-control'}),
        }

I'm then calling this from my urls.py with url(r'^accounts/register/$', RegistrationView.as_view(form_class=MyRegistrationForm), name='registration_register'),

In the template the captcha, first_name and last_name fields are rendered using form-control, the username is hidden but the other fields are rendered without the class.  What do I need to do?

Body:
i had the same problem once and i used this

class MyRegistrationForm(RegistrationForm):
    captcha = NoReCaptchaField()
    first_name = forms.CharField(max_length=30, required=False, widget=forms.TextInput(attrs={'class': 'form-control'}))
    last_name = forms.CharField(max_length=30, required=False, widget=forms.TextInput(attrs={'class': 'form-control'}))
    email = forms.EmailField(max_length=254, widget=forms.TextInput(attrs={'class': 'form-control'}))
    password1 = forms.CharField(max_length=30, required=True, widget=forms.TextInput(attrs={'class': 'form-control',
                                                                                'name': "password1",
                                                                                'type': "password"}))
    password2 = forms.CharField(max_length=30, required=True, widget=forms.TextInput(attrs={'class': 'form-control',
                                                                                'name': "password2",
                                                                                'type': "password"}))
    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'email']
        widgets = {
            'username' : forms.TextInput(attrs = {'class': 'form-control'}),
        }


问:
MySql Update takes very long
I found a strange behavior on following query:

```<code>UPDATE llx_socpeople SET no_email=1 WHERE rowid IN (SELECT source_id FROM llx_mailing_cibles where tag = "68d74c3bc618ebed67919ed5646d0ffb");
</code>```

takes 1 min and 30 seconds.

When I split up the commands to 2 queries:

```<code>SELECT source_id FROM llx_mailing_cibles where tag = "68d74c3bc618ebed67919ed5646d0ffb";
</code>```

Result is 10842

```<code>UPDATE llx_socpeople SET no_email=1 WHERE rowid = 10842;
</code>```

Result is shown in milliseconds.

Table llx_socpeople has about 7.000 records, llx_mailing_cibles has about 10.000 records.

MySQL Version is: 5.7.20-0ubuntu0.16.04.1

I already tried to optimize/repair both tables with no effect.

Any ideas?

答:
Currently, as the subquery is being run for each row of the main query, we can expect a longer execution time.
What I would suggest would be to rely on a inner join for performing the update:

```<code>UPDATE llx_socpeople AS t1
INNER JOIN llx_mailing_cibles AS t2
ON t1.rowid = t2.source_id
SET t1.no_email=1
WHERE t2.tag = "68d74c3bc618ebed67919ed5646d0ffb";
</code>```

This way you will definitely get far better performance.

You can troubleshoot your slow queries using the EXPLAIN MySql statement. Find more details about it on it's dedicated page from the official documentation. It might help you discover any missing indexes.

Title: MySql Update takes very long

Body:
I found a strange behavior on following query:

UPDATE llx_socpeople SET no_email=1 WHERE rowid IN (SELECT source_id FROM llx_mailing_cibles where tag = "68d74c3bc618ebed67919ed5646d0ffb");

takes 1 min and 30 seconds.

When I split up the commands to 2 queries:

SELECT source_id FROM llx_mailing_cibles where tag = "68d74c3bc618ebed67919ed5646d0ffb";

Result is 10842

UPDATE llx_socpeople SET no_email=1 WHERE rowid = 10842;

Result is shown in milliseconds.

Table llx_socpeople has about 7.000 records, llx_mailing_cibles has about 10.000 records.

MySQL Version is: 5.7.20-0ubuntu0.16.04.1

I already tried to optimize/repair both tables with no effect.

Any ideas?

Body:
Currently, as the subquery is being run for each row of the main query, we can expect a longer execution time.
What I would suggest would be to rely on a inner join for performing the update:

UPDATE llx_socpeople AS t1
INNER JOIN llx_mailing_cibles AS t2
ON t1.rowid = t2.source_id
SET t1.no_email=1
WHERE t2.tag = "68d74c3bc618ebed67919ed5646d0ffb";

This way you will definitely get far better performance.

You can troubleshoot your slow queries using the EXPLAIN MySql statement. Find more details about it on it's dedicated page from the official documentation. It might help you discover any missing indexes.


问:
File upload from <input type="file">
Using angular 2 beta, I cannot seem to get an <input type="file"> to work.

Using diagnostic, I can see two-way binding for other types such as text.

```<code><form>
    {{diagnostic}}
    <div class="form-group">
        <label for="fileupload">Upload</label>
        <input type="file" class="form-control" [(ngModel)]="model.fileupload">
    </div>
</form>
</code>```

In my TypeScript file, I have the following diagnostic line:

```<code>get diagnostic() { return JSON.stringify(this.model); }
</code>```

Could it be that it is the issue of not being JSON? The value is null.

I cannot really verify the value of the input. Уven though the text next to "Choose file ..." updates, I cannot see differences in the DOM for some reason.

答:
Try this small lib, works with Angular 5.0.0

https://www.npmjs.com/package/ng2-file-upload

Quickstart example with ng2-file-upload 1.3.0:

User clicks custom button, which triggers upload dialog from hidden input type="file" , uploading started automatically after selecting single file.

app.module.ts:

```<code>import {FileUploadModule} from "ng2-file-upload";
</code>```

your.component.html:

```<code>...
  <button mat-button onclick="document.getElementById('myFileInputField').click()" >
    Select and upload file
  </button>
  <input type="file" id="myFileInputField" ng2FileSelect [uploader]="uploader" style="display:none">
...
</code>```

your.component.ts:

```<code>import {FileUploader} from 'ng2-file-upload';
...
uploader: FileUploader;
...
constructor() {
   this.uploader = new FileUploader({url: "/your-api/some-endpoint"});
   this.uploader.onErrorItem = item => {
       console.error("Failed to upload");
       this.clearUploadField();
   };
   this.uploader.onCompleteItem = (item, response) => {
       console.info("Successfully uploaded");
       this.clearUploadField();

       // (Optional) Parsing of response
       let responseObject = JSON.parse(response) as MyCustomClass;

   };

   // Asks uploader to start upload file automatically after selecting file
  this.uploader.onAfterAddingFile = fileItem => this.uploader.uploadAll();
}

private clearUploadField(): void {
    (<HTMLInputElement>window.document.getElementById('myFileInputField'))
    .value = "";
}
</code>```

Alternative lib, works in Angular 4.2.4, but requires some workarounds to adopt to Angular 5.0.0

https://www.npmjs.com/package/angular2-http-file-upload

ContentLicense: CC BY-SA 4.0

Title: File upload from <input type="file">

Body:
Using angular 2 beta, I cannot seem to get an <input type="file"> to work.

Using diagnostic, I can see two-way binding for other types such as text.

<form>
    {{diagnostic}}

        Upload
        <input type="file" class="form-control" [(ngModel)]="model.fileupload">

</form>

In my TypeScript file, I have the following diagnostic line:

get diagnostic() { return JSON.stringify(this.model); }

Could it be that it is the issue of not being JSON? The value is null.

I cannot really verify the value of the input. Уven though the text next to "Choose file ..." updates, I cannot see differences in the DOM for some reason.

Body:
Try this small lib, works with Angular 5.0.0

https://www.npmjs.com/package/ng2-file-upload

Quickstart example with ng2-file-upload 1.3.0:

User clicks custom button, which triggers upload dialog from hidden input type="file" , uploading started automatically after selecting single file.

app.module.ts:

import {FileUploadModule} from "ng2-file-upload";

your.component.html:

...
  <button mat-button onclick="document.getElementById('myFileInputField').click()" >
    Select and upload file
  </button>
  <input type="file" id="myFileInputField" ng2FileSelect [uploader]="uploader" style="display:none">
...

your.component.ts:

import {FileUploader} from 'ng2-file-upload';
...
uploader: FileUploader;
...
constructor() {
   this.uploader = new FileUploader({url: "/your-api/some-endpoint"});
   this.uploader.onErrorItem = item => {
       console.error("Failed to upload");
       this.clearUploadField();
   };
   this.uploader.onCompleteItem = (item, response) => {
       console.info("Successfully uploaded");
       this.clearUploadField();

       // (Optional) Parsing of response
       let responseObject = JSON.parse(response) as MyCustomClass;

   };

   // Asks uploader to start upload file automatically after selecting file
  this.uploader.onAfterAddingFile = fileItem => this.uploader.uploadAll();
}

private clearUploadField(): void {
    (<HTMLInputElement>window.document.getElementById('myFileInputField'))
    .value = "";
}

Alternative lib, works in Angular 4.2.4, but requires some workarounds to adopt to Angular 5.0.0

https://www.npmjs.com/package/angular2-http-file-upload


问:
Image over an image using a class (CSS)
The problem I have here is because we use a theme (wordpress) for our clients that makes it easy for them to change an image and this is a simple version of the code it produces:

```<code><div class="row">
   <div class="column">
      <img class="image" src="image user can change">
   </div>
</div>
</code>```

What I need to try and achieve is a layer over the top of the image to put a logo on the image without changing the core HTML that the theme produces and only using CSS.

My thought was adding a background image to the class column and somehow bringing it in front. I tried z-index on the column with no luck. Any ideas?

答:
You can use pseudo-elements to achieve what you are after. Try using something like the following code:

```<code>.column {
  position:relative;
}
.column:after {
  content:"";
  position:absolute;
  z-index:2;
  background:url(your-image.jpg);
}
.column img {
  position:relative;
  z-index:1;
}
</code>```

Here is an example fiddle:
https://jsfiddle.net/scooterlord/cqhf2gw4/

Title: Image over an image using a class (CSS)

Body:
The problem I have here is because we use a theme (wordpress) for our clients that makes it easy for them to change an image and this is a simple version of the code it produces:

What I need to try and achieve is a layer over the top of the image to put a logo on the image without changing the core HTML that the theme produces and only using CSS.

My thought was adding a background image to the class column and somehow bringing it in front. I tried z-index on the column with no luck. Any ideas?

Body:
You can use pseudo-elements to achieve what you are after. Try using something like the following code:

.column {
  position:relative;
}
.column:after {
  content:"";
  position:absolute;
  z-index:2;
  background:url(your-image.jpg);
}
.column img {
  position:relative;
  z-index:1;
}

Here is an example fiddle:
https://jsfiddle.net/scooterlord/cqhf2gw4/


问:
AutoComplete txtfield from array items in Objective c
I have a textfield in which whenever user type it shows related items from array in tableView to select any of them but when user type anything in small keyword it does not show the array. when user enter any word in capital letters as store in an array it shows the array.

i want that when user enter any word whether in small or capital letter it should show the table view containing array. Following is my code,

```<code>    -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    NSLog(@"Range:%@",NSStringFromRange(range));
    NSLog(@"%@",textField.text);

    NSString *passcode = [textField.text stringByReplacingCharactersInRange:range withString:string];

    NSLog(@"%@",passcode);

    NSPredicate *predicate = [NSPredicate predicateWithFormat: @"SELF CONTAINS %@",passcode];

    carArray = [_staticCarArray filteredArrayUsingPredicate:predicate];

    city = [_staticCarArrays filteredArrayUsingPredicate:predicate];

    NSLog(@"%@", carArray);
    NSLog(@"%@", city);

    if ([carArray count]==0) {
        _carTable.hidden = TRUE;
    }else{
        _carTable.hidden = FALSE;
    }

    if ([city count]==0) {
        _autotable.hidden = TRUE;
    }else{
        _autotable.hidden = FALSE;
    }

    [_carTable reloadData];
    [_autotable reloadData];

    return TRUE;

}
</code>```

答:
Use UITextfieldDeleage,UITableViewDelegate,UITableViewDataSource

```<code>@interface ABCViewController : UIViewController <UITextFieldDelegate>
myTextField.delegate = self;
</code>```

1.Get the TextField Text and Save the Value in NSMutableArray

2.Retrieve the Array value and check if the TextField Text is already contains in Array using NSPredicate

3.Show the TableViewCell TextLabel Text to Textfield

```<code> #pragma mark - UITextField Delegate
 -(BOOL)textField:(UITextField *)textField
 shouldChangeCharactersInRange:(NSRange)range replacementString:
                                               (NSString *)string{

 NSLog(@"Range:%@",NSStringFromRange(range));
 NSLog(@"%@",textField.text);

 NSString *passcode = [textField.text stringByReplacingCharactersInRange:range withString:string];

 NSLog(@"%@",passcode);

 NSPredicate *predicate = [NSPredicate predicateWithFormat:
                          @"SELF CONTAINS %@",passcode];
 autoCompleteFilterArray = [autoCompleteArray filteredArrayUsingPredicate:predicate];
 NSLog(@"%@", autoCompleteFilterArray);

 if ([autoCompleteFilterArray count]==0) {
    autoCompleteTableView.hidden = TRUE;
 }else{
    autoCompleteTableView.hidden = FALSE;
 }
 [autoCompleteTableView reloadData];

return TRUE;
}
</code>```

Body:
I have a textfield in which whenever user type it shows related items from array in tableView to select any of them but when user type anything in small keyword it does not show the array. when user enter any word in capital letters as store in an array it shows the array.

i want that when user enter any word whether in small or capital letter it should show the table view containing array. Following is my code,

    -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    NSLog(@"Range:%@",NSStringFromRange(range));
    NSLog(@"%@",textField.text);

    NSString *passcode = [textField.text stringByReplacingCharactersInRange:range withString:string];

    NSLog(@"%@",passcode);

    NSPredicate *predicate = [NSPredicate predicateWithFormat: @"SELF CONTAINS %@",passcode];

    carArray = [_staticCarArray filteredArrayUsingPredicate:predicate];

    city = [_staticCarArrays filteredArrayUsingPredicate:predicate];

    NSLog(@"%@", carArray);
    NSLog(@"%@", city);

    if ([carArray count]==0) {
        _carTable.hidden = TRUE;
    }else{
        _carTable.hidden = FALSE;
    }

    if ([city count]==0) {
        _autotable.hidden = TRUE;
    }else{
        _autotable.hidden = FALSE;
    }

    [_carTable reloadData];
    [_autotable reloadData];

    return TRUE;

}

Body:
Use UITextfieldDeleage,UITableViewDelegate,UITableViewDataSource

@interface ABCViewController : UIViewController <UITextFieldDelegate>
myTextField.delegate = self;

1.Get the TextField Text and Save the Value in NSMutableArray

2.Retrieve the Array value and check if the TextField Text is already contains in Array using NSPredicate

3.Show the TableViewCell TextLabel Text to Textfield

 #pragma mark - UITextField Delegate
 -(BOOL)textField:(UITextField *)textField
 shouldChangeCharactersInRange:(NSRange)range replacementString:
                                               (NSString *)string{

 NSLog(@"Range:%@",NSStringFromRange(range));
 NSLog(@"%@",textField.text);

 NSString *passcode = [textField.text stringByReplacingCharactersInRange:range withString:string];

 NSLog(@"%@",passcode);

 NSPredicate *predicate = [NSPredicate predicateWithFormat:
                          @"SELF CONTAINS %@",passcode];
 autoCompleteFilterArray = [autoCompleteArray filteredArrayUsingPredicate:predicate];
 NSLog(@"%@", autoCompleteFilterArray);

 if ([autoCompleteFilterArray count]==0) {
    autoCompleteTableView.hidden = TRUE;
 }else{
    autoCompleteTableView.hidden = FALSE;
 }
 [autoCompleteTableView reloadData];

return TRUE;
}


问:
Java: I have joda Start and End DateTime, how would I slice it into N pieces?
I have a start Date and end Date and hence I have a duration it could be a small duration in hours or it could be a long duration in years, how can I slice it up in number of equal pieces of duration, for example :

below duration is of approx. 1 month

```<code>startDate = 2017-03-01 00:00:00.000Z
endDate = 2017-04-01 00:00:00.000Z
</code>```

How would I slice it up in 2 equal pieces ?
something like below :

```<code>startDate1 =  2017-03-01 00:00:00.000Z
endDate1 = 2017-03-15 00:00:00.000Z

startDate2 = 2017-03-15 00:00:00.000Z
endDate2 = 2017-04-01 00:00:00.000Z
</code>```

答:
In Case some is looking equal denominator between given time here is code.</p>

```<code>private List<Interval> splitDateTime(long start, long end, int intervalNo) {
        long interval = (end - start) / intervalNo;
        List<Interval> list = new ArrayList<Interval>();
        for (long i = start + interval; i < end; i += interval) {
            list.add(new Interval(start, i));
            start=start + interval;
        }
        list.add(new Interval(start, end));
        return list;
    }
</code>```

Body:
I have a start Date and end Date and hence I have a duration it could be a small duration in hours or it could be a long duration in years, how can I slice it up in number of equal pieces of duration, for example :

below duration is of approx. 1 month

startDate = 2017-03-01 00:00:00.000Z
endDate = 2017-04-01 00:00:00.000Z

How would I slice it up in 2 equal pieces ?
something like below :

startDate1 =  2017-03-01 00:00:00.000Z
endDate1 = 2017-03-15 00:00:00.000Z

startDate2 = 2017-03-15 00:00:00.000Z
endDate2 = 2017-04-01 00:00:00.000Z

Body:
In Case some is looking equal denominator between given time here is code.

private List<Interval> splitDateTime(long start, long end, int intervalNo) {
        long interval = (end - start) / intervalNo;
        List<Interval> list = new ArrayList<Interval>();
        for (long i = start + interval; i < end; i += interval) {
            list.add(new Interval(start, i));
            start=start + interval;
        }
        list.add(new Interval(start, end));
        return list;
    }


问:
twitter.stream is not a function in node.js?
I cannot able to monitor the twitter.I followed the procedure to do the sentiment analysis (twitter) in node.js code.It verified my twitter account correctly.but it shows stream is not a function. I enclosed the code .can anyone solve this issue.Thanks in advance...

app.get('/watchTwitter', function (req, res) {
    const twitter = new twitterAPI({
        consumerKey: "asas",
        consumerSecret: "sdcscs"
    });
    const accessToken = "cdccd";
    const accessTokenSecret = "csdcs";
    var stream;
    var testTweetCount = 0;
    var phrase = 'bieber';
    twitter.verifyCredentials(accessToken, accessTokenSecret, params, function (error, data, response) {
        if (error) {
            console.log(error);
        } else {
            console.log(data["screen_name"]);
            stream = twitter.stream('statuses/filter',
                {
                    'track': phrase
                }, function (stream) {
                    res.send("Monitoring Twitter for \'" + phrase + "\'...  Logging Twitter traffic.");
                    stream.on('data', function (data)
                    {
                        testTweetCount++;
                        if (testTweetCount % 50 === 0)
                        {
                            console.log("Tweet #" + testTweetCount + ":  " + data.text);
                        }
                    });
                });
        }
    });
});
app.listen(8086,function()
{
    console.log("port is listen on 8086");
});```

答:
You are referring Twitter npm package, but you are using node-twitter-api. See the documentations. For statuses, you need to use following method.

```<code>twitter.statuses("update", {
        status: "Hello world!"
    },
    accessToken,
    accessTokenSecret,
    function(error, data, response) {
        if (error) {
            console.log(error);
        } else {
            console.log(data);
        }
    }
);
</code>```

Body:
You are referring Twitter npm package, but you are using node-twitter-api. See the documentations. For statuses, you need to use following method.

twitter.statuses("update", {
        status: "Hello world!"
    },
    accessToken,
    accessTokenSecret,
    function(error, data, response) {
        if (error) {
            console.log(error);
        } else {
            console.log(data);
        }
    }
);


问:
while (i<=sqrt(static_cast<double>(n))
In the "C++ Without Fear: A Beginner's Guide That Makes You Feel Smart" book, in Chapter (2): Decisions, Decisions, you can see this lin of code as part of the prime number program:

```<code>while (i<=sqrt(static_cast<double>(n))
</code>```

Provided that "i" was initialized to "2", and "n" is the user's input.

Why are we comparing to the "sqrt" of "n" and not to "n" itself?

Thanks.

答: Because if a number has factors other than itself and 1, then at least one of those factors will be less than the number's sqrt.</p>

ContentLicense: CC BY-SA 2.5

Title: while (i<=sqrt(static_cast<double>(n))

Body:
In the "C++ Without Fear: A Beginner's Guide That Makes You Feel Smart" book, in Chapter (2): Decisions, Decisions, you can see this lin of code as part of the prime number program:

while (i<=sqrt(static_cast<double>(n))

Provided that "i" was initialized to "2", and "n" is the user's input.

Why are we comparing to the "sqrt" of "n" and not to "n" itself?

Thanks.


问:
background image in span element is overlapping another element background image
background image in span element is overlapping another element background image

```<code>background-color: inherit;
backface-visibility: hidden;
</code>```

i already give these two properties for prevent issue. but sometimes issues came in my web page.

```<code>.iconImage {
background-image: url(images/svg/S_TL_CATALOG.svg);
margin-left: -18px;
width: 36px;
height: 36px;
width: 36px;
margin: auto;
display: inline-block;
cursor: pointer;
background-size: contain;
background-position: center;
background-repeat: no-repeat;
position: relative;
left: 50%;
background-color: inherit;
backface-visibility: hidden;
}
</code>```

help me to solve this issue.thanks

```<code><div> // listed images for tools icon
   <span></span> //background image1 .. this is static image
   <span></span> //background image2 ..  coming images are dynamically adding images by drag and drop
   ---------
</div>
</code>```

this is my html format.
after refresh my webpage background image2 loading first then background image1 loading next image2 is overlapping the image1.

mouseover on the two images at that time also overlapping. anything css properties is there for solve this

答:
```<code>background-blend-mode: screen;
backface-visibility: hidden;
</code>```

give this css property to element

Body:
background image in span element is overlapping another element background image

background-color: inherit;
backface-visibility: hidden;

i already give these two properties for prevent issue. but sometimes issues came in my web page.

.iconImage {
background-image: url(images/svg/S_TL_CATALOG.svg);
margin-left: -18px;
width: 36px;
height: 36px;
width: 36px;
margin: auto;
display: inline-block;
cursor: pointer;
background-size: contain;
background-position: center;
background-repeat: no-repeat;
position: relative;
left: 50%;
background-color: inherit;
backface-visibility: hidden;
}

help me to solve this issue.thanks

 // listed images for tools icon
    //background image1 .. this is static image
    //background image2 ..  coming images are dynamically adding images by drag and drop
   ---------

this is my html format.
after refresh my webpage background image2 loading first then background image1 loading next image2 is overlapping the image1.

mouseover on the two images at that time also overlapping. anything css properties is there for solve this

Body:
background-blend-mode: screen;
backface-visibility: hidden;

give this css property to element


问:
Swift - How to do specific action on last row of a UITableView when the last row isn't visible?
I am trying to achieve a custom action on the last row of my UITableView.

I found a nice extension in order to know if I'm on the last row :

```<code>extension UITableView {

    func isLast(for indexPath: IndexPath) -> Bool {

        let indexOfLastSection = numberOfSections > 0 ? numberOfSections - 1 : 0
        let indexOfLastRowInLastSection = numberOfRows(inSection: indexOfLastSection) - 1

        return indexPath.section == indexOfLastSection && indexPath.row == indexOfLastRowInLastSection
    }
}
</code>```

The only issue I'm facing is that if my tableView has many rows, with scrollable content, the last row isn't visible.
Thus, in my cellForRow I am doing this :

```<code>if tableView.isLast(for: indexPath) {
   print("Last Row - Do Specific action")
} else {
}
</code>```

It is working, except that imagine my screen can display 6 rows, but the total number of rows of my tableView is 15.
It will apply my specific action on the row at indexPath 5 and 15.

I am guessing it is because each time cellForRow is called, it is checking for the last row, and it apply on the last visible row also.

How can I achieve a custom action ONLY on the last row even if it is not visible yet?

EDIT: After more investigation, the issue comes from UITableView not able to prefetch the cell, and cellLoaded and cellVisible is the same.

答:
I can't copy paste the code as I don't have xcode right now.

But if you want to perform action before cell gets displayed then do it in

func tableView(_ tableView: UITableView,
              willDisplay cell: UITableViewCell,
                 forRowAt indexPath: IndexPath)

And to check for the last row:

```<code>if indexPath.row == dataSourceArray.count - 1 {
   //Perform action
}
</code>```

dataSourceArray is the array from which you are fetching the data to show it in the cell.

Basically your code should be something like this

```<code>func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
       if indexPath.row == dataSourceArray.count - 1 {
            //Perform action
    }
}
</code>```

You may go through apple docs to know more about tableview delegate methods

Body:
I am trying to achieve a custom action on the last row of my UITableView.

I found a nice extension in order to know if I'm on the last row :

extension UITableView {

    func isLast(for indexPath: IndexPath) -> Bool {

        let indexOfLastSection = numberOfSections > 0 ? numberOfSections - 1 : 0
        let indexOfLastRowInLastSection = numberOfRows(inSection: indexOfLastSection) - 1

        return indexPath.section == indexOfLastSection && indexPath.row == indexOfLastRowInLastSection
    }
}

The only issue I'm facing is that if my tableView has many rows, with scrollable content, the last row isn't visible.
Thus, in my cellForRow I am doing this :

if tableView.isLast(for: indexPath) {
   print("Last Row - Do Specific action")
} else {
}

It is working, except that imagine my screen can display 6 rows, but the total number of rows of my tableView is 15.
It will apply my specific action on the row at indexPath 5 and 15.

I am guessing it is because each time cellForRow is called, it is checking for the last row, and it apply on the last visible row also.

How can I achieve a custom action ONLY on the last row even if it is not visible yet?

EDIT: After more investigation, the issue comes from UITableView not able to prefetch the cell, and cellLoaded and cellVisible is the same.

Body:
I can't copy paste the code as I don't have xcode right now.

But if you want to perform action before cell gets displayed then do it in

func tableView(_ tableView: UITableView,
              willDisplay cell: UITableViewCell,
                 forRowAt indexPath: IndexPath)

And to check for the last row:

if indexPath.row == dataSourceArray.count - 1 {
   //Perform action
}

dataSourceArray is the array from which you are fetching the data to show it in the cell.

Basically your code should be something like this

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
       if indexPath.row == dataSourceArray.count - 1 {
            //Perform action
    }
}

You may go through apple docs to know more about tableview delegate methods


问:
Input Layout toggle hintText color change
I am using TextInputLayout in which i want to change the color of hinttext  when i enter text then the color of hint text should be blue other wise color should be gray and when edittext contains some value then the color of hintText should blue for more information please check my image.

Ultimate i want this after edit text containing some value.

This is my current result after using this code

```<code>  <style name="labelcolor" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Hint color and label color in FALSE state -->
    <item name="android:textColorHint">#868686</item>
    <item name="android:textSize">16sp</item>
    <item name="android:paddingTop">5sp</item>
    <!-- Label color in TRUE state and bar color FALSE and TRUE State -->
    <item name="colorAccent">#0ea3ff</item>
    <item name="colorControlNormal">#0ea3ffr</item>
    <item name="colorControlActivated">#0ea3ff</item>
</style>
</code>```

please help me how can i solve this issues.

答:
Firstly you need to set your TextInputLayout

```<code> android.support.design.widget.TextInputLayout textInputLayout =        (TextInputLayout) view.findViewById(R.id.textInputLayout);

textInputLayout.setHintTextAppearance(R.style.Instyle);
</code>```

and then in styles.xml file you can create your styles with the color for the hint color.

```<code><style name="Instyle" parent="AppThemeLight">
    <itemname="android:textColorPrimary">@android:color/darker_gray</item>
    <item name="android:textColor">@android:color/darker_gray</item>
</style>
</code>```

Body:
I am using TextInputLayout in which i want to change the color of hinttext  when i enter text then the color of hint text should be blue other wise color should be gray and when edittext contains some value then the color of hintText should blue for more information please check my image.

Ultimate i want this after edit text containing some value.

This is my current result after using this code

please help me how can i solve this issues.

Body:
Firstly you need to set your TextInputLayout

 android.support.design.widget.TextInputLayout textInputLayout =        (TextInputLayout) view.findViewById(R.id.textInputLayout);

textInputLayout.setHintTextAppearance(R.style.Instyle);

and then in styles.xml file you can create your styles with the color for the hint color.

<style name="Instyle" parent="AppThemeLight">
    <itemname="android:textColorPrimary">@android:color/darker_gray</item>
    <item name="android:textColor">@android:color/darker_gray</item>
</style>


问:
Swift Safe Area Layout Guide and Visual Format Language
I want to use Apples visual format language to constrain a view to the new Safe Area Layout Guide in iOS 11. However, I get an exception:

-[NSLayoutYAxisAnchor nsli_superitem]: unrecognized selector sent to instance 0x1c447ed40

```<code>    //Make View Dictionary
    var views: [String: Any] = ["left": self.leftContainer]

    //Check swift version and add appropriate piece to the view dictionary
    if #available(iOS 11, *) {
        views["topGuide"] = self.view.safeAreaLayoutGuide.topAnchor
    }else{
        views["topGuide"] = self.topLayoutGuide
    }

    //Make the constraint using visual format language
    let leftVertical = NSLayoutConstraint.constraints(withVisualFormat: "V:[topGuide][left]|", options: [], metrics: nil, views: views)

    //Add the new constraint
    self.view.addConstraints(vertical)
</code>```

The reason I like visual format language is because you a can add lot of constraints with less code in some cases.

Any Ideas?

答:
I know it's not VFL, but there is a factory class called NSLayoutAnchor that makes creating constraints a bit more clean and concise.

For example, I was able to pin the top anchor of a UILabel to the top anchor of the safe area with one compact line:

```<code>label.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor).isActive = true
</code>```

Note that safeAreaLayoutGuide requires iOS 11. For older versions, replace self.view.safeAreaLayoutGuide.topAnchor by self.topLayoutGuide.bottomAnchor.

Again, I know it's not VFL, but this seems to be what we have for now.

Body:
I want to use Apples visual format language to constrain a view to the new Safe Area Layout Guide in iOS 11. However, I get an exception:

-[NSLayoutYAxisAnchor nsli_superitem]: unrecognized selector sent to instance 0x1c447ed40

    //Make View Dictionary
    var views: [String: Any] = ["left": self.leftContainer]

    //Check swift version and add appropriate piece to the view dictionary
    if #available(iOS 11, *) {
        views["topGuide"] = self.view.safeAreaLayoutGuide.topAnchor
    }else{
        views["topGuide"] = self.topLayoutGuide
    }

    //Make the constraint using visual format language
    let leftVertical = NSLayoutConstraint.constraints(withVisualFormat: "V:[topGuide][left]|", options: [], metrics: nil, views: views)

    //Add the new constraint
    self.view.addConstraints(vertical)

The reason I like visual format language is because you a can add lot of constraints with less code in some cases.

Any Ideas?

Body:
I know it's not VFL, but there is a factory class called NSLayoutAnchor that makes creating constraints a bit more clean and concise.

For example, I was able to pin the top anchor of a UILabel to the top anchor of the safe area with one compact line:

label.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor).isActive = true

Note that safeAreaLayoutGuide requires iOS 11. For older versions, replace self.view.safeAreaLayoutGuide.topAnchor by self.topLayoutGuide.bottomAnchor.

Again, I know it's not VFL, but this seems to be what we have for now.


问:
Ruby on Rails add nested controller/resource
I have an application that I want to have a route that is /admin/active_vulnerabilities but when I generate the controller as rails generate controller ActiveVulnerabilities and put the following in my routes.rb

```<code>namespace :admin do
    resources :users
    resources :active_vulnerabilities

    # Admin root
    root to: 'application#index'
  end
</code>```

But I get the error uninitialized constant Admin::ActiveVulnerabilitiesController so I changed my controller to class Admin::ActiveVulnerabilitiesController < ApplicationController

I then get the error Unable to autoload constant ActiveVulnerabilitiesController, expected /home/luke/projects/vuln_frontend/app/controllers/active_vulnerabilities_controller.rb to define it but the file mentioned is my controller named exactly as that.

答:
Your controller should be put in app/controllers/admin/ because the namespace. Otherwise, you can forget this directory and the namespace and use just scope

```<code>scope :admin do
  resources :active_vulnerabilities
end

class ActiveVulnerabilitiesController < ApplicationController
</code>```

Body:
I have an application that I want to have a route that is /admin/active_vulnerabilities but when I generate the controller as rails generate controller ActiveVulnerabilities and put the following in my routes.rb

namespace :admin do
    resources :users
    resources :active_vulnerabilities

    # Admin root
    root to: 'application#index'
  end

But I get the error uninitialized constant Admin::ActiveVulnerabilitiesController so I changed my controller to class Admin::ActiveVulnerabilitiesController < ApplicationController

I then get the error Unable to autoload constant ActiveVulnerabilitiesController, expected /home/luke/projects/vuln_frontend/app/controllers/active_vulnerabilities_controller.rb to define it but the file mentioned is my controller named exactly as that.

Body:
Your controller should be put in app/controllers/admin/ because the namespace. Otherwise, you can forget this directory and the namespace and use just scope

scope :admin do
  resources :active_vulnerabilities
end

class ActiveVulnerabilitiesController < ApplicationController


问:
JSON deserialization for property starting with underscore ("_id") not working
Posting the question as I can't find solution specific to below problem.

One of the 3rd part REST service we are consuming return response similar to

{ "_id": "d55eb7c0",
   "applicationType": "TEST",
   "applicationId": "uxhJ1hcT1F8bpL3xAWvTjsymNcd1RArv",
   "description": "Some Description"}

tried to map "_id" attribute as, to follow proper java bean naming

```<code>@JsonProperty("_id")
private String id;
</code>```

which results in following error.

```<code>org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class ] and content type [application/json;charset=utf-8]
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:109)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:917)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:901)
</code>```

if the field name is private String _id; json response is de-serialised without any issue. but I don't want to name field starting with '_' in our app.
We are using Jackson-2.7.3 & Spring RestTemplate to make REST calls.

Implementation for consuming the endpoint. Its a simple GET call using Spring RestTemplate.

HttpEntity<String> requestEntity = new HttpEntity<>(httpHeaders);
return restTemplate.exchange(authorizationProperties.getEndpoint() + "/roles", HttpMethod.GET, requestEntity,new ParameterizedTypeReference<Auth0Roles>() {});

Thanks in advance.

答:
Its not looking like the problem with JSON. Most probably you are missing the HttpMessageConverter.

Try Adding this dependency

```<code><dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.3</version>
</dependency>
</code>```

Body:
Posting the question as I can't find solution specific to below problem.

One of the 3rd part REST service we are consuming return response similar to

{ "_id": "d55eb7c0",
   "applicationType": "TEST",
   "applicationId": "uxhJ1hcT1F8bpL3xAWvTjsymNcd1RArv",
   "description": "Some Description"}

tried to map "_id" attribute as, to follow proper java bean naming

@JsonProperty("_id")
private String id;

which results in following error.

org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class ] and content type [application/json;charset=utf-8]
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:109)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:917)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:901)

if the field name is private String _id; json response is de-serialised without any issue. but I don't want to name field starting with '_' in our app.
We are using Jackson-2.7.3 & Spring RestTemplate to make REST calls.

Implementation for consuming the endpoint. Its a simple GET call using Spring RestTemplate.

HttpEntity<String> requestEntity = new HttpEntity<>(httpHeaders);
return restTemplate.exchange(authorizationProperties.getEndpoint() + "/roles", HttpMethod.GET, requestEntity,new ParameterizedTypeReference<Auth0Roles>() {});

Thanks in advance.

Body:
Its not looking like the problem with JSON. Most probably you are missing the HttpMessageConverter.

Try Adding this dependency

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.3</version>
</dependency>


问:
How to stop the jmeter execution if failure rate is high
I'm doing live jmeter monitoring using influxdB and grafana. i want to know how to stop the jmeter execution if failure rate is high when compared to success rate. I'm going to integrate this in jenkins.

I'm running the jmeter test in non GUI mode. I need to create a job which will monitor grafana and if the failure rate is high it has to kill the jmeter test which is running. Please help me with your suggestions and throw some light. Thanks in advance.

答:
Check out AutoStop listener, using it you will be able to define the error rate threshold, if the amount of errors will exceed it - JMeter test will be stopped.

You can install Auto Stop Listener using JMeter Plugins Manager

Check out Using the JMeter AutoStop Listener - How to Do it Right article for more details if needed.


问:
Angular 4 Property get binding does not show anything
I have following code

```<code>export class TestClass{
    private time: string = "Test";

    public get TimeFormatted(): string {
        return this.time;
    }
}
</code>```

and in my template

```<code>   <span>{{item.TimeFormatted}}</span>
</code>```

but nothing shows up in the html.

答:
if you want to use getters and setters, try the below code. every time you change the time, setter function will be called and you can use any condition over it. You can also see the working version here https://stackblitz.com/edit/ionic-getters-setters

TS file

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  public _time: string;
  public password : string;

  constructor() {
    this._time="Test";
    this.password="password";

  }

    public get time(): string {
        return this._time;
    }

    public set time(value) {
      alert("set");
      if(this.password==="password"){
    this._time = value+"verified";
      }
  }

}
</code>```

HTML code

```<code><input type="text" [(ngModel)]="time" />
</code>```

Body:
I have following code

export class TestClass{
    private time: string = "Test";

    public get TimeFormatted(): string {
        return this.time;
    }
}

and in my template

   {{item.TimeFormatted}}

but nothing shows up in the html.

Body:
if you want to use getters and setters, try the below code. every time you change the time, setter function will be called and you can use any condition over it. You can also see the working version here https://stackblitz.com/edit/ionic-getters-setters

TS file

import { Component } from '@angular/core';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  public _time: string;
  public password : string;

  constructor() {
    this._time="Test";
    this.password="password";

  }

    public get time(): string {
        return this._time;
    }

    public set time(value) {
      alert("set");
      if(this.password==="password"){
    this._time = value+"verified";
      }
  }

}

HTML code

<input type="text" [(ngModel)]="time" />


问:
python win32service - Getting triggered startup information for service
win32 API QueryServiceConfig2 function supports the SERVICE_CONFIG_TRIGGER_INFO structure to get event(s) that trigger the service startup. However, python's win32service.QueryServiceConfig2() does not list such value as a parameter option. Is it possible to get that information with the win32service module?</p>

答:
Unfortunately, no. Here's a simple code snippet ran under Python 3.5 and PyWin32 v221:

#!/usr/bin/env python3

import win32service

if __name__ == "__main__":
    for name in dir(win32service):
        if name.startswith("SERVICE_CONFIG_"):
            print(name, getattr(win32service, name))
```

<p><strong>Output</strong>:</p>

<blockquote>
<pre class="lang-bat prettyprint-override"><code>(py35x64_test) e:\Work\Dev\StackOverflow\q046916726>"c:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" a.py
SERVICE_CONFIG_DELAYED_AUTO_START_INFO 3
SERVICE_CONFIG_DESCRIPTION 1
SERVICE_CONFIG_FAILURE_ACTIONS 2
SERVICE_CONFIG_FAILURE_ACTIONS_FLAG 4
SERVICE_CONFIG_PRESHUTDOWN_INFO 7
SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO 6
SERVICE_CONFIG_SERVICE_SID_INFO 5
</code>```

I've also checked win32con (which is another PyWin32 module, that only contains constant definitions), but no luck either.

Then, I took a look at ${PYWIN32_SRC_DIR}/pywin32-221/win32/src/win32service.i, and noticed that for ChangeServiceConfig2 (and also QueryServiceConfig2), the InfoLevel argument is specifically checked against the above constants, and thus passing its value (8) directly, would raise an exception (NotImplementedError).

Before going further, let's spend a little bit understanding what happens when calling such a Python wrapper (like win32service.QueryServiceConfig2):

Arguments (Python style - if any) are converted to C style

C function is called with the above converted arguments

Function result (or output arguments) - if any - are converted back to Python

For [MS.Docs]: ChangeServiceConfig2W function, data is transferred back and forth via arguments (depending on dwInfoLevel value, lpInfo can have various meanings):

Let's take a look to a value that is supported: e.g. SERVICE_CONFIG_PRESHUTDOWN_INFO:

lpInfo is a pointer to a [MS.Docs]: SERVICE_PRESHUTDOWN_INFO structure which only has a dwPreshutdownTimeout member (which is a simple DWORD)

On the other hand, SERVICE_CONFIG_TRIGGER_INFO:

lpInfo is a pointer to a [MS.Docs]: SERVICE_TRIGGER_INFO structure

pTriggers member is a pointer to a [MS.Docs]: SERVICE_TRIGGER structure

pDataItems member is a pointer to a [MS.Docs]: SERVICE_TRIGGER_SPECIFIC_DATA_ITEM structure

which is waaay more complex (and note that all involved structures have other members as well, I only listed the ones that increase the nesting level).

Adding support for all those arguments is not exactly a trivial task, so they aren't handled (at least for the moment).

There are more examples like this one, I guess it's a matter of priority, as not many people requested the functionality, combined with MS's (unfortunate?) design decision to have functions with such complex behaviors.

As an alternative (a quite complex one), you can use [Python 3.Docs]: ctypes - A foreign function library for Python, but you'll have to define all the structures that I listed above in Python (to extend ctypes.Structure).

As a side note, I was in the exact situation once: I had to call [MS.Docs]: LsaLogonUser function (!!! 14 freaking arguments !!!). Obviously, it wasn't exported by PyWin32, so I called it via ctypes, but I had to write:

~170 lines of code to define structures (only the ones that I needed for my scenario)

~50 lines to populate them and call the function

Body:
Unfortunately, no. Here's a simple code snippet ran under Python 3.5 and PyWin32 v221:

#!/usr/bin/env python3

import win32service

if __name__ == "__main__":
    for name in dir(win32service):
        if name.startswith("SERVICE_CONFIG_"):
            print(name, getattr(win32service, name))

Output:

(py35x64_test) e:\Work\Dev\StackOverflow\q046916726>"c:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" a.py
SERVICE_CONFIG_DELAYED_AUTO_START_INFO 3
SERVICE_CONFIG_DESCRIPTION 1
SERVICE_CONFIG_FAILURE_ACTIONS 2
SERVICE_CONFIG_FAILURE_ACTIONS_FLAG 4
SERVICE_CONFIG_PRESHUTDOWN_INFO 7
SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO 6
SERVICE_CONFIG_SERVICE_SID_INFO 5

I've also checked win32con (which is another PyWin32 module, that only contains constant definitions), but no luck either.

Then, I took a look at ${PYWIN32_SRC_DIR}/pywin32-221/win32/src/win32service.i, and noticed that for ChangeServiceConfig2 (and also QueryServiceConfig2), the InfoLevel argument is specifically checked against the above constants, and thus passing its value (8) directly, would raise an exception (NotImplementedError).

Before going further, let's spend a little bit understanding what happens when calling such a Python wrapper (like win32service.QueryServiceConfig2):

Arguments (Python style - if any) are converted to C style

C function is called with the above converted arguments

Function result (or output arguments) - if any - are converted back to Python

For [MS.Docs]: ChangeServiceConfig2W function, data is transferred back and forth via arguments (depending on dwInfoLevel value, lpInfo can have various meanings):

Let's take a look to a value that is supported: e.g. SERVICE_CONFIG_PRESHUTDOWN_INFO:

lpInfo is a pointer to a [MS.Docs]: SERVICE_PRESHUTDOWN_INFO structure which only has a dwPreshutdownTimeout member (which is a simple DWORD)

On the other hand, SERVICE_CONFIG_TRIGGER_INFO:

lpInfo is a pointer to a [MS.Docs]: SERVICE_TRIGGER_INFO structure

pTriggers member is a pointer to a [MS.Docs]: SERVICE_TRIGGER structure

pDataItems member is a pointer to a [MS.Docs]: SERVICE_TRIGGER_SPECIFIC_DATA_ITEM structure

which is waaay more complex (and note that all involved structures have other members as well, I only listed the ones that increase the nesting level).

Adding support for all those arguments is not exactly a trivial task, so they aren't handled (at least for the moment).

There are more examples like this one, I guess it's a matter of priority, as not many people requested the functionality, combined with MS's (unfortunate?) design decision to have functions with such complex behaviors.

As an alternative (a quite complex one), you can use [Python 3.Docs]: ctypes - A foreign function library for Python, but you'll have to define all the structures that I listed above in Python (to extend ctypes.Structure).

As a side note, I was in the exact situation once: I had to call [MS.Docs]: LsaLogonUser function (!!! 14 freaking arguments !!!). Obviously, it wasn't exported by PyWin32, so I called it via ctypes, but I had to write:

~170 lines of code to define structures (only the ones that I needed for my scenario)

~50 lines to populate them and call the function


问:
change position of the snakBar to top programatically
I want when snakbar is appeared, to be displayed to top. for this I write this command:

```<code>Snackbar mSnak = Snackbar.make(viewHolder.messageBlock, str, Snackbar.LENGTH_SHORT);
TextView mTextView = mSnak.getView().findViewById(android.support.design.R.id.snackbar_text);
mTextView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)mSnak.getView().getLayoutParams();
params.gravity = Gravity.TOP;
mSnak.getView().setLayoutParams(params);
mSnak.show();
</code>```

But it does not work?? and still is appeared at bottom.How does one change the SnackBar 's initial alignment??

答:
make the snackbar appear on top of the screen using this:</p>

```<code>Snackbar snack = Snackbar.make(findViewById(android.R.id.content), "Had a snack at Snackbar", Snackbar.LENGTH_LONG);

View view = snack.getView();
FrameLayout.LayoutParams params =(FrameLayout.LayoutParams)view.getLayoutParams();
params.gravity = Gravity.TOP;
view.setLayoutParams(params);
snack.show();
</code>```

Body:
I want when snakbar is appeared, to be displayed to top. for this I write this command:

Snackbar mSnak = Snackbar.make(viewHolder.messageBlock, str, Snackbar.LENGTH_SHORT);
TextView mTextView = mSnak.getView().findViewById(android.support.design.R.id.snackbar_text);
mTextView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)mSnak.getView().getLayoutParams();
params.gravity = Gravity.TOP;
mSnak.getView().setLayoutParams(params);
mSnak.show();

But it does not work?? and still is appeared at bottom.How does one change the SnackBar 's initial alignment??

Body:
make the snackbar appear on top of the screen using this:

Snackbar snack = Snackbar.make(findViewById(android.R.id.content), "Had a snack at Snackbar", Snackbar.LENGTH_LONG);

View view = snack.getView();
FrameLayout.LayoutParams params =(FrameLayout.LayoutParams)view.getLayoutParams();
params.gravity = Gravity.TOP;
view.setLayoutParams(params);
snack.show();


问:
Boost array Initialization in C++
I need to declare a boost::array. I did it as boost::array<char, 116> buf;
is there a possibility that I can declare with the size stored as a constant that is initialized from property file. something like boost::array<char, BUFFER_SIZE> buf;

Any Help?

答:
If it's a constant available at compile-time, (meaning you #included your property file or something) then yes.

```<code>int const BUFFER_SIZE = 116;
boost::array<char, BUFFER_SIZE> buf;
</code>```

is valid. If it isn't available at compile-time, then no.

Title: Boost array Initialization in C++

Body:
If it's a constant available at compile-time, (meaning you #included your property file or something) then yes.

int const BUFFER_SIZE = 116;
boost::array<char, BUFFER_SIZE> buf;

is valid. If it isn't available at compile-time, then no.


问:
Is it possible to partially update rows using sequelize?
Suppose I have a table like this:

and an array of objects which contains [
  {ID: '0', Name: 'Leo', Age: 21, CurrentState: 5},
  {ID: '1', Name: 'George', Age: 26, , CurrentState: 6},
  {ID: '2', Name: 'Diana', Age: 27, , CurrentState: 4}
].

How can I update the columns ID, Name, Age, and CurrentState without affecting the values of IsAdmin column?

If I run the following code

```<code>Table.bulkCreate([
  {ID: '0', Name: 'Leo', Age: 21, CurrentState: 5},
  {ID: '1', Name: 'George', Age: 26, , CurrentState: 6},
  {ID: '2', Name: 'Diana', Age: 27, , CurrentState: 4}
], {
  updateOnDuplicate: true
})
</code>```

All the values of IsAdmin of the updated rows will be set to FALSE, which is its default value.

How can I avoid this problem?

答:
Just passe an array of only the attributes that need to be updated

```<code>Table.bulkCreate([
  {ID: '0', Name: 'Leo', Age: 21, CurrentState: 5},
  {ID: '1', Name: 'George', Age: 26, , CurrentState: 6},
  {ID: '2', Name: 'Diana', Age: 27, , CurrentState: 4}
], {
  updateOnDuplicate: ['Name','CurrentState']
})
</code>```

options.updateOnDuplicate

Array

optional

Fields to update if row key already exists (on duplicate key update)? (only supported by mysql). By default, all fields are updated.

Body:
Suppose I have a table like this:

and an array of objects which contains [
  {ID: '0', Name: 'Leo', Age: 21, CurrentState: 5},
  {ID: '1', Name: 'George', Age: 26, , CurrentState: 6},
  {ID: '2', Name: 'Diana', Age: 27, , CurrentState: 4}
].

How can I update the columns ID, Name, Age, and CurrentState without affecting the values of IsAdmin column?

If I run the following code

Table.bulkCreate([
  {ID: '0', Name: 'Leo', Age: 21, CurrentState: 5},
  {ID: '1', Name: 'George', Age: 26, , CurrentState: 6},
  {ID: '2', Name: 'Diana', Age: 27, , CurrentState: 4}
], {
  updateOnDuplicate: true
})

All the values of IsAdmin of the updated rows will be set to FALSE, which is its default value.

How can I avoid this problem?

Body:
Just passe an array of only the attributes that need to be updated

Table.bulkCreate([
  {ID: '0', Name: 'Leo', Age: 21, CurrentState: 5},
  {ID: '1', Name: 'George', Age: 26, , CurrentState: 6},
  {ID: '2', Name: 'Diana', Age: 27, , CurrentState: 4}
], {
  updateOnDuplicate: ['Name','CurrentState']
})

options.updateOnDuplicate

Array

optional

Fields to update if row key already exists (on duplicate key update)? (only supported by mysql). By default, all fields are updated.


问:
Image over an image using a class (CSS)
The problem I have here is because we use a theme (wordpress) for our clients that makes it easy for them to change an image and this is a simple version of the code it produces:

```<code><div class="row">
   <div class="column">
      <img class="image" src="image user can change">
   </div>
</div>
</code>```

What I need to try and achieve is a layer over the top of the image to put a logo on the image without changing the core HTML that the theme produces and only using CSS.

My thought was adding a background image to the class column and somehow bringing it in front. I tried z-index on the column with no luck. Any ideas?

答:
I think you could take advantage of the :after selector in your column class. Something like this:

```<code>.column {
    position: relative;
}

.column:after {
    content: "";
    position: absolute;
    width: 30px;
    height: 30px;
    bottom: 10px;
    right: 10px;
    background-image: url('path/to/logo.png');
}
</code>```

That would position a small logo in the bottom right.

Title: Image over an image using a class (CSS)

Body:
The problem I have here is because we use a theme (wordpress) for our clients that makes it easy for them to change an image and this is a simple version of the code it produces:

What I need to try and achieve is a layer over the top of the image to put a logo on the image without changing the core HTML that the theme produces and only using CSS.

My thought was adding a background image to the class column and somehow bringing it in front. I tried z-index on the column with no luck. Any ideas?

Body:
I think you could take advantage of the :after selector in your column class. Something like this:

.column {
    position: relative;
}

.column:after {
    content: "";
    position: absolute;
    width: 30px;
    height: 30px;
    bottom: 10px;
    right: 10px;
    background-image: url('path/to/logo.png');
}

That would position a small logo in the bottom right.


问:
How to slice a period of time into several slices in Joda Time?
I want to make a personal schedule manager using Java and Joda Time. The user has a certain period in a day (eg. 10am-4pm) , for each day in a month. He should be able to extract a period from his day and "add" a list of chores (ie strings) to this period. Then he will be shown the remaining portion of his day. He can extract more periods from this until he has no time periods left. He can add an extracted period back to the schedule for the day and remove all chores for that period, that is free time.

The size of a time slice that can be extracted is decided by the user. number of time slices = total time available in a day/size of time-slice set by user = num of time slices of desired size + remainder time

He can divide his day into chunks of 1hr, 30 mins, 15 mins, 20mins, 40mins etc.

ADDED: The user needs to have his whole schedule saved so that he can come back and check what he was doing in the past. The hours each day can be variable - 10am-4pm, 9am-1pm etc

I am new to Joda Time and I don't know if this is possible in Joda Time and if possible, is it easy or cumbersome. I only need some guidance. I am not asking for the whole code to be typed for me.

Thanks in advance.

答:
Method split start and end in given interval.</p>

```<code>private List<Interval> splitDateTime(long start, long end, int intervalNo) {
            long interval = (end - start) / intervalNo;
            List<Interval> list = new ArrayList<Interval>();
            for (long i = start + interval; i < end; i += interval) {
                list.add(new Interval(start, i));
                start=start + interval;
            }
            list.add(new Interval(start, end));
            return list;
        }
</code>```

Body:
Method split start and end in given interval.

private List<Interval> splitDateTime(long start, long end, int intervalNo) {
            long interval = (end - start) / intervalNo;
            List<Interval> list = new ArrayList<Interval>();
            for (long i = start + interval; i < end; i += interval) {
                list.add(new Interval(start, i));
                start=start + interval;
            }
            list.add(new Interval(start, end));
            return list;
        }


问:
Elasticsearch is giving unnecessary records on match query
I want to get All the documents whose dateofbirth is having substring "-11-09".

This is my elasticsearch query :

```<code>{ "query": { "bool" : { "must": { "match": { "dobdata": ".*-11-09.*"} } } } }
</code>```

And the result i am getting is

```<code>{
 "took": 8,
 "timed_out": false,
 "_shards": {
  "total": 5,
  "successful": 5,
  "failed": 0
 },
 "hits": {
  "total": 4,
  "max_score": 5.0782137,
  "hits": [
   {
     "_index": "userindexv1",
     "_type": "usertype",
     "_id": "58f9a9d1acf8c47037000038",
     "_score": 5.0782137,
     "_source": {
      "fullname": "Eshwar ",
      "fullname_raw": "Eshwar ",
      "mobile1": "7222222256",
      "uid": "UIDS1010",
      "mobile2": "",
      "classname": "Class 5",
      "classname_raw": "Class 5",
      "divid": 63,
      "category": "S",
      "dobdata": "2010-11-09"
     }
   },
   {
    "_index": "userindexv1",
    "_type": "usertype",
    "_id": "57960b35acf8c4c43000002c",
    "_score": 1.259227,
    "_source": {
     "fullname": "Sindhu ",
     "fullname_raw": "Sindhu ",
     "mobile1": "9467952335",
     "uid": "UIDS1006",
     "mobile2": "",
     "classname": "class 1s Group for class g",
     "classname_raw": "class 1s Group for class g",
     "divid": 63,
     "category": "S",
     "dobdata": "2012-11-08"
    }
   },
   {
    "_index": "userindexv1",
    "_type": "usertype",
    "_id": "58eb62d2acf8c4d43300002f",
    "_score": 1.1471639,
    "_source": {
     "fullname": "Himanshu ",
     "fullname_raw": "Himanshu ",
     "mobile1": "9898785484",
     "uid": "",
     "mobile2": "",
     "classname": "Play Group",
     "classname_raw": "Play Group",
     "divid": 63,
     "category": "S",
     "dobdata": "2012-11-08"
    }
   },
   {
    "_index": "userindexv1",
    "_type": "usertype",
    "_id": "580dbe5bacf8c4b82300002a",
    "_score": 1.1471639,
    "_source": {
     "fullname": "Sai Bhargav ",
     "fullname_raw": "Sai Bhargav ",
     "mobile1": "9739477159",
     "uid": "",
     "mobile2": "7396226318",
     "classname": "class 1s Group for class g",
     "classname_raw": "class 1s Group for class g",
     "divid": 63,
     "category": "S",
     "dobdata": "2012-11-07"
    }
   }
 ]
}}
</code>```

I am getting the records whose dateofbirth does not contain the string "-11-09". I tried to work around it. I am not able to find the soultion.

I am new to elasticsearch. I want only the first record. Can anyone please help me out. Sorry for bad english.

答:
Even I faced same problem and I solved it by doing two things.
1. Changed the format of date of birth from Y-m-d to YMd and made the index as not_analyzed.
2. Used wildcard query insteadof match query

```<code>{
"query": {
    "wildcard": {
       "dobdata": {
          "value": "*Nov09*"
       }
    }
  }
}
</code>```

It solved my problem.Hope this will solve your problem too.

Body:
I want to get All the documents whose dateofbirth is having substring "-11-09".

This is my elasticsearch query :

{ "query": { "bool" : { "must": { "match": { "dobdata": ".*-11-09.*"} } } } }

And the result i am getting is

{
 "took": 8,
 "timed_out": false,
 "_shards": {
  "total": 5,
  "successful": 5,
  "failed": 0
 },
 "hits": {
  "total": 4,
  "max_score": 5.0782137,
  "hits": [
   {
     "_index": "userindexv1",
     "_type": "usertype",
     "_id": "58f9a9d1acf8c47037000038",
     "_score": 5.0782137,
     "_source": {
      "fullname": "Eshwar ",
      "fullname_raw": "Eshwar ",
      "mobile1": "7222222256",
      "uid": "UIDS1010",
      "mobile2": "",
      "classname": "Class 5",
      "classname_raw": "Class 5",
      "divid": 63,
      "category": "S",
      "dobdata": "2010-11-09"
     }
   },
   {
    "_index": "userindexv1",
    "_type": "usertype",
    "_id": "57960b35acf8c4c43000002c",
    "_score": 1.259227,
    "_source": {
     "fullname": "Sindhu ",
     "fullname_raw": "Sindhu ",
     "mobile1": "9467952335",
     "uid": "UIDS1006",
     "mobile2": "",
     "classname": "class 1s Group for class g",
     "classname_raw": "class 1s Group for class g",
     "divid": 63,
     "category": "S",
     "dobdata": "2012-11-08"
    }
   },
   {
    "_index": "userindexv1",
    "_type": "usertype",
    "_id": "58eb62d2acf8c4d43300002f",
    "_score": 1.1471639,
    "_source": {
     "fullname": "Himanshu ",
     "fullname_raw": "Himanshu ",
     "mobile1": "9898785484",
     "uid": "",
     "mobile2": "",
     "classname": "Play Group",
     "classname_raw": "Play Group",
     "divid": 63,
     "category": "S",
     "dobdata": "2012-11-08"
    }
   },
   {
    "_index": "userindexv1",
    "_type": "usertype",
    "_id": "580dbe5bacf8c4b82300002a",
    "_score": 1.1471639,
    "_source": {
     "fullname": "Sai Bhargav ",
     "fullname_raw": "Sai Bhargav ",
     "mobile1": "9739477159",
     "uid": "",
     "mobile2": "7396226318",
     "classname": "class 1s Group for class g",
     "classname_raw": "class 1s Group for class g",
     "divid": 63,
     "category": "S",
     "dobdata": "2012-11-07"
    }
   }
 ]
}}

I am getting the records whose dateofbirth does not contain the string "-11-09". I tried to work around it. I am not able to find the soultion.

I am new to elasticsearch. I want only the first record. Can anyone please help me out. Sorry for bad english.

Body:
Even I faced same problem and I solved it by doing two things.
1. Changed the format of date of birth from Y-m-d to YMd and made the index as not_analyzed.
2. Used wildcard query insteadof match query

{
"query": {
    "wildcard": {
       "dobdata": {
          "value": "*Nov09*"
       }
    }
  }
}

It solved my problem.Hope this will solve your problem too.


问:
Setting the AVAudioSession category in AppDelegate.m
So I hate to have to ask this question but I've spent a fair bit of time searching through Apple's documentation and Google with no avail. I'm simply trying to set the AVAudioSession category for my app ONCE, when the applicationDidFinishLaunching. I have an app that plays an audio stream and I would like it to continue playing when the app enters the background, so I'm trying to use the Playback category. Here is my code for AppDelegate.m :

```<code>- (void)applicationDidFinishLaunching:(UIApplication *)application
{
// Set AudioSession
NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
[[AVAudioSession sharedInstance] setActive:YES error:&sessionError];
[[AVAudioSession sharedInstance] setDelegate:self];

// create window and set up navigation controller
[window addSubview:myNavController.view];
[window makeKeyAndVisible];

}

# pragma mark -
# pragma mark AVAudioSession Delegate Methods
- (void)beginInterruption {
}
- (void)endInterruption {
}
- (void)endInterruptionWithFlags:(NSUInteger)flags {
}
- (void)inputIsAvailableChanged:(BOOL)isInputAvailable {
}
</code>```

With this code, the audio fades out anytime I hit the home button, putting
the app in the background. Any help is much appreciated, I hope that it
is a quick fix type of answer for anybody who has done this before.

答:
First add the UIBackgroundModes key to your Info.plist file if you haven't done already.
More info here.

If you have done that already, which framework do you use to play your media?

Body:
So I hate to have to ask this question but I've spent a fair bit of time searching through Apple's documentation and Google with no avail. I'm simply trying to set the AVAudioSession category for my app ONCE, when the applicationDidFinishLaunching. I have an app that plays an audio stream and I would like it to continue playing when the app enters the background, so I'm trying to use the Playback category. Here is my code for AppDelegate.m :

- (void)applicationDidFinishLaunching:(UIApplication *)application
{
// Set AudioSession
NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
[[AVAudioSession sharedInstance] setActive:YES error:&sessionError];
[[AVAudioSession sharedInstance] setDelegate:self];

// create window and set up navigation controller
[window addSubview:myNavController.view];
[window makeKeyAndVisible];

}

# pragma mark -
# pragma mark AVAudioSession Delegate Methods
- (void)beginInterruption {
}
- (void)endInterruption {
}
- (void)endInterruptionWithFlags:(NSUInteger)flags {
}
- (void)inputIsAvailableChanged:(BOOL)isInputAvailable {
}

With this code, the audio fades out anytime I hit the home button, putting
the app in the background. Any help is much appreciated, I hope that it
is a quick fix type of answer for anybody who has done this before.


问:
How do you create a list of Observables in RxJava?
I've a API which gives me a list of ids. I need to use these ids to make another network request to get their details of individual items. Once I get all the details I need to put them in a list.

So here is an example. Make a network request, get a list of ids say

1, 2, 3, 4, 5.

Now I need to make 5 separate requests for these 5 ids.

And then once I get the response of all, I need to create a list which is used to populate the RecyclerView.

Let me know if further information are needed. I'm new to Reactive programming.

Body: Pseudocode: Observable.from(listOfIds).flatMap(return request(id)).toList()


问:
How to fix: Error message in TestNG java.lang.AbstractMethodError: org.openqa.selenium.MutableCapabilities.is(Ljava/lang/String;)Z
How to solve the following error message

java.lang.AbstractMethodError:
  org.openqa.selenium.MutableCapabilities.is(Ljava/lang/String;)Z in
  automation project with Java, Selenium Server (having the
  configuration : client-combined-3.7.1-sources, client-combined-3.7.1,
  commo ns-lang-2.6,  org.eclipse.jgit_4.5.0.201609210915-r,
  selenium-firefox-driver-3.0.0-beta1,  selenium-server-standalone-3.7.1
  firefox v. 44)

I have tried many combinations of selenium server & selenium Firefox driver but I was receiving other errors

```<code><dependencies>
  <dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>6.8.8</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.7.1</version>
  </dependency>
</dependencies>
</code>```

Only these lines of code I am using:

```<code>System.setProperty("webdriver.gecko.driver", "C:\\Users\\Aila\\Downloads\\geckodriver-v0.19.1-win32\\geckodriver.exe");
driver = new FirefoxDriver();
</code>```

答:
The error says it all:

```<code>java.lang.AbstractMethodError: org.openqa.selenium.MutableCapabilities.is(Ljava/lang/String;)Z in automation project with Java, Selenium Server (having the configuration : client-combined-3.7.1-sources, client-combined-3.7.1, commo ns-lang-2.6, org.eclipse.jgit_4.5.0.201609210915-r, selenium-firefox-driver-3.0.0-beta1, selenium-server-standalone-3.7.1
</code>```

First of all ensure that you are using all the binaries and jars of latest version (Selenium, GeckoDriver, Firefox Browser).

If you want to use Maven :

Remove all the Selenium related jars which you have added manually from your project.

Use Selenium and TestNG related jars only through Maven Dependencies.

Clean the Project

Execute mvn clean install test

If you want to use Selenium and TestNG without Maven:

Remove all the Selenium related jars once and add only the  selenium-server-standalone-3.7.1 within your project.

Clean the Project

Execute your @Test as TestNG Test or TestNG Suite

Body:
How to solve the following error message

java.lang.AbstractMethodError:
  org.openqa.selenium.MutableCapabilities.is(Ljava/lang/String;)Z in
  automation project with Java, Selenium Server (having the
  configuration : client-combined-3.7.1-sources, client-combined-3.7.1,
  commo ns-lang-2.6,  org.eclipse.jgit_4.5.0.201609210915-r,
  selenium-firefox-driver-3.0.0-beta1,  selenium-server-standalone-3.7.1
  firefox v. 44)

I have tried many combinations of selenium server & selenium Firefox driver but I was receiving other errors

<dependencies>
  <dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>6.8.8</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.7.1</version>
  </dependency>
</dependencies>

Only these lines of code I am using:

System.setProperty("webdriver.gecko.driver", "C:\\Users\\Aila\\Downloads\\geckodriver-v0.19.1-win32\\geckodriver.exe");
driver = new FirefoxDriver();

Body:
The error says it all:

java.lang.AbstractMethodError: org.openqa.selenium.MutableCapabilities.is(Ljava/lang/String;)Z in automation project with Java, Selenium Server (having the configuration : client-combined-3.7.1-sources, client-combined-3.7.1, commo ns-lang-2.6, org.eclipse.jgit_4.5.0.201609210915-r, selenium-firefox-driver-3.0.0-beta1, selenium-server-standalone-3.7.1

First of all ensure that you are using all the binaries and jars of latest version (Selenium, GeckoDriver, Firefox Browser).

If you want to use Maven :

Remove all the Selenium related jars which you have added manually from your project.

Use Selenium and TestNG related jars only through Maven Dependencies.

Clean the Project

Execute mvn clean install test

If you want to use Selenium and TestNG without Maven:

Remove all the Selenium related jars once and add only the  selenium-server-standalone-3.7.1 within your project.

Clean the Project

Execute your @Test as TestNG Test or TestNG Suite


问:
How can I close a specific file using a batch command
I'm trying to create a batch file that opens up an Access file. (Presses enter), and then closes the Access file again. I'm a complete noob  to batch file's, and the only part I got working was the open file part.

```<code>Start ""  "W:\Motorenfabriek\World Class Manufacturing\Verspaning\Area 1\PROVO Applicatie\Database tabellen\TblStoringDienst.accdb"
</code>```

When I run this code the application opens. Problem is within the organisation you first have to press enter before you can work with your Access file.

I know this question has been asked before, but I haven't seen any working answers yet.

I tried the code beneith to close the application again but this isn't working. The application stays opened:

```<code>taskill /f /im "W:\Motorenfabriek\World Class Manufacturing\Verspaning\Area 1\PROVO Applicatie\Database tabellen\TblStoringDienst.accdb"
</code>```

I only want this file to close, not all Access instances because there is running another one aswell.

答:
There are a few ways to kill a task, one of the easier methods are to kill it by window title. So as an example, I have a file open called test.txt and the file is open in notepad. the title is displayed as test.txt - Notepad.

I can then just do this to kill it.

```<code>taskkill /F /FI "WindowTitle eq test.txt - Notepad" /T
</code>```

The same will go for Window Titles such as:

```<code>my_devices.csv - Excel
My Document1 - Word
TblStoringDienst.accdb - Access
Hex edit TblStoringDienst.accdb
</code>```

etc.

As for your send keystroke option, pure batch cannot do it, you have to do wscript and batch combination. This will send enter to the screen after a timeout of 2 sconds, when the command was started. It is untested as I do not have your environment, so might need to be tuned.

```<code>@if (@CodeSection == @Batch) @then

@echo off
set SendKeys=CScript //nologo //E:JScript "%~F0"
        Start ""  "W:\Motorenfabriek\World Class Manufacturing\Verspaning\Area 1\PROVO Applicatie\Database tabellen\TblStoringDienst.accdb"
        timeout /t 2 /nobreak >nul
        %SendKeys% {ENTER}

@end

var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));
</code>```

Body:
I'm trying to create a batch file that opens up an Access file. (Presses enter), and then closes the Access file again. I'm a complete noob  to batch file's, and the only part I got working was the open file part.

Start ""  "W:\Motorenfabriek\World Class Manufacturing\Verspaning\Area 1\PROVO Applicatie\Database tabellen\TblStoringDienst.accdb"

When I run this code the application opens. Problem is within the organisation you first have to press enter before you can work with your Access file.

I know this question has been asked before, but I haven't seen any working answers yet.

I tried the code beneith to close the application again but this isn't working. The application stays opened:

taskill /f /im "W:\Motorenfabriek\World Class Manufacturing\Verspaning\Area 1\PROVO Applicatie\Database tabellen\TblStoringDienst.accdb"

I only want this file to close, not all Access instances because there is running another one aswell.

Body:
There are a few ways to kill a task, one of the easier methods are to kill it by window title. So as an example, I have a file open called test.txt and the file is open in notepad. the title is displayed as test.txt - Notepad.

I can then just do this to kill it.

taskkill /F /FI "WindowTitle eq test.txt - Notepad" /T

The same will go for Window Titles such as:

my_devices.csv - Excel
My Document1 - Word
TblStoringDienst.accdb - Access
Hex edit TblStoringDienst.accdb

etc.

As for your send keystroke option, pure batch cannot do it, you have to do wscript and batch combination. This will send enter to the screen after a timeout of 2 sconds, when the command was started. It is untested as I do not have your environment, so might need to be tuned.

@if (@CodeSection == @Batch) @then

@echo off
set SendKeys=CScript //nologo //E:JScript "%~F0"
        Start ""  "W:\Motorenfabriek\World Class Manufacturing\Verspaning\Area 1\PROVO Applicatie\Database tabellen\TblStoringDienst.accdb"
        timeout /t 2 /nobreak >nul
        %SendKeys% {ENTER}

@end

var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));


问:
How to make request every 2 seconds with angular js and node js?
I have a server written with Nodejs that collects data. My client side is written with AngularJS. I need to create http request every two seconds to my server (setInterval) and display updated data. My server running 24/7. Can chrome block my requests if it reaches maximum? Can I implement another way, instead of create request from client side, maybe to push from my server?

Example of some request:

```<code>var indicesTimer = setInterval(getIndices,2000);
getIndices();

function getIndices(){
  dataService.getIndices().then(function(res){
    $scope.recentIndeces = res.data;
  });
}
</code>```

答: You can use websocket. By using that, your server can notify your client in case something changed in the server side so you don't have to do a polling (polling is what you do when sending request every x seconds). Take a look at socket.io </p>

Body:
I have a server written with Nodejs that collects data. My client side is written with AngularJS. I need to create http request every two seconds to my server (setInterval) and display updated data. My server running 24/7. Can chrome block my requests if it reaches maximum? Can I implement another way, instead of create request from client side, maybe to push from my server?

Example of some request:

var indicesTimer = setInterval(getIndices,2000);
getIndices();

function getIndices(){
  dataService.getIndices().then(function(res){
    $scope.recentIndeces = res.data;
  });
}


问:
how do I detect a "long Tap" gesture on a UITableViewCell
In my app I'm displaying a table with different elements if a user taps on a tableviewcell a detailview gets pushed onto the navigationstack.
I now want to provide the user with abilty to "long tap" on a tableviewcell in order to pop up an alertview showing the user different options that can be applied on said tableviewcell (email information to a friend, print it out, add to bookmarks etc)

how do i implement a "long tap" gesture recognizer on a UITableViewCell??

thanks for your help

答:
Have you looked at UILongPressGestureRecognizer?
See: http://developer.apple.com/library/ios/#documentation/uikit/reference/UILongPressGestureRecognizer_Class/Reference/Reference.html%23//apple_ref/occ/cl/UILongPressGestureRecognizer

You might want to consider a swipe gesture as seen in the Twitter app instead, though: I don't think that a long tap on a table cell would be very intuitive to use or expected by the user. Just my 2 cents.

Johannes


问:
Remove a wrapper function in IntelliJ IDEA?
I have a foreach block that wraps multiple statements such as:

$outputArr[$type . "_" . "orgName"] = urlencode($this->params[$prefix."companyname"]);

Is there any shortcut handy that will just remove the urlencode wrapper, in this example, without me having to manually go to end of line, delete the end bracket?

Bonus point: Do it in one command for all the same repeating wrapping urlencode lines in the block :)

答:
For a single occurence, use the "Unwrap/Remove..." action (Ctrl-Shift-DELETE on Windows). (Place the caret inside the urlencode(......).

If there are many such occurences, I usually define my own method, that overwrites the other urlencode:

```<code>private String urlencode(String a) {
    return a;
}
</code>```

Then use "Inline" (Ctrl-Alt-N) to inline all calls to the method and remove the methopd again.

Body:
For a single occurence, use the "Unwrap/Remove..." action (Ctrl-Shift-DELETE on Windows). (Place the caret inside the urlencode(......).

If there are many such occurences, I usually define my own method, that overwrites the other urlencode:

private String urlencode(String a) {
    return a;
}

Then use "Inline" (Ctrl-Alt-N) to inline all calls to the method and remove the methopd again.


答:
You could take the center by taking the average of the positions.

var polygon = [[-73.9280684530257, 40.8099975343718], [-73.9282820374729, 40.8100875554645], [-73.9280124002104, 40.8103130893677], [-73.927875543761, 40.8102554080229], [-73.9280684530257, 40.8099975343718]],
    centers = polygon.map(function (point, i, points) {
        var neighbour = points[(i + 1) % points.length];
        return point.map(function (value, j) {
            return (value + neighbour[j]) / 2;
        });
    });

console.log(centers);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Center of each side of a polygon

Body:
Hi I have a polygon with coordintes

[
    [-73.9280684530257, 40.8099975343718],
    [-73.9282820374729, 40.8100875554645],
    [-73.9280124002104, 40.8103130893677],
    [-73.927875543761, 40.8102554080229],
    [-73.9280684530257, 40.8099975343718]
]

How I can find out the center of each side of this polygon using javascript?

Body:
You could take the center by taking the average of the positions.

var polygon = [[-73.9280684530257, 40.8099975343718], [-73.9282820374729, 40.8100875554645], [-73.9280124002104, 40.8103130893677], [-73.927875543761, 40.8102554080229], [-73.9280684530257, 40.8099975343718]],
    centers = polygon.map(function (point, i, points) {
        var neighbour = points[(i + 1) % points.length];
        return point.map(function (value, j) {
            return (value + neighbour[j]) / 2;
        });
    });

console.log(centers);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How a for loop should wait until a function inside it finish its execution in angularjs?
I have an array $scope.requisition that has three elements inside it and, for each element, I'm performing some task(api call and fetching some data), but the output I'm  getting is "item1" "item1" "item1" "item2" "item2" "item2" which is not synchronous. What I want is for the loop to wait for the api to fetch the data and then go for the next execution which is not happening.

The output expected is:

1st execution("item1" "item2")

2nd execution("item1" "item2")

3rd execution("item1" "item2")

```<code>for(var index in $scope.requisition){
    var tableName = JSON.parse($scope.requisition[index].applyFormConfig).table;
    console.log("item1 "+JSON.stringify($scope.requisition[index]));

    privateMetadata.getCustomFieldNames({entityName:tableName}).$promise.then(function(results) {
        $scope.target.tableFields = normalizeObjects(results);
        console.log("item2 "+JSON.parse($scope.requisition[index].applyFormConfig).items);
        angular.forEach(JSON.parse($scope.requisition[index].applyFormConfig).items,function(item){
            var mappedJsonObj = getObjectByIdFromArray(item.id, $scope.target.tableFields);
        });
    });
};
</code>```

I'm new to this framework so I don't know how to do this.

答:
Promises are asynchronous, but you can work around this by creating a counter variable and putting your promise in a function that recursively calls itself when successful, then incrementing the counter until the last index has been reached.
Snippet:</p>

```<code>var index = 0;
$scope.myFunction = function(){
    var tableName = JSON.parse($scope.requisition[index].applyFormConfig).table;
    console.log("item1 "+JSON.stringify($scope.requisition[index]));

    privateMetadata.getCustomFieldNames({entityName:tableName}).$promise.then(function(results) {
        $scope.target.tableFields = normalizeObjects(results);
        console.log("item2 "+JSON.parse($scope.requisition[index].applyFormConfig).items);
        angular.forEach(JSON.parse($scope.requisition[index].applyFormConfig).items,function(item){
            var mappedJsonObj = getObjectByIdFromArray(item.id, $scope.target.tableFields);
        });
        if(index!=$scope.requisition.length - 1){
            index++;
            $scope.myFunction();
        }
    });
}
</code>```

Body:
I have an array $scope.requisition that has three elements inside it and, for each element, I'm performing some task(api call and fetching some data), but the output I'm  getting is "item1" "item1" "item1" "item2" "item2" "item2" which is not synchronous. What I want is for the loop to wait for the api to fetch the data and then go for the next execution which is not happening.

The output expected is:

1st execution("item1" "item2")

2nd execution("item1" "item2")

3rd execution("item1" "item2")

for(var index in $scope.requisition){
    var tableName = JSON.parse($scope.requisition[index].applyFormConfig).table;
    console.log("item1 "+JSON.stringify($scope.requisition[index]));

    privateMetadata.getCustomFieldNames({entityName:tableName}).$promise.then(function(results) {
        $scope.target.tableFields = normalizeObjects(results);
        console.log("item2 "+JSON.parse($scope.requisition[index].applyFormConfig).items);
        angular.forEach(JSON.parse($scope.requisition[index].applyFormConfig).items,function(item){
            var mappedJsonObj = getObjectByIdFromArray(item.id, $scope.target.tableFields);
        });
    });
};

I'm new to this framework so I don't know how to do this.

Body:
Promises are asynchronous, but you can work around this by creating a counter variable and putting your promise in a function that recursively calls itself when successful, then incrementing the counter until the last index has been reached.
Snippet:

var index = 0;
$scope.myFunction = function(){
    var tableName = JSON.parse($scope.requisition[index].applyFormConfig).table;
    console.log("item1 "+JSON.stringify($scope.requisition[index]));

    privateMetadata.getCustomFieldNames({entityName:tableName}).$promise.then(function(results) {
        $scope.target.tableFields = normalizeObjects(results);
        console.log("item2 "+JSON.parse($scope.requisition[index].applyFormConfig).items);
        angular.forEach(JSON.parse($scope.requisition[index].applyFormConfig).items,function(item){
            var mappedJsonObj = getObjectByIdFromArray(item.id, $scope.target.tableFields);
        });
        if(index!=$scope.requisition.length - 1){
            index++;
            $scope.myFunction();
        }
    });
}


问:
My Eclipse E4 plugins only works with new workspaces, workbench.xmi not updating
When I create and export my E4 plugins to install in eclipse, my modifications don't show up at first.

I can only see my modifications in workspaces I create after I installed the plugin.

To see my modifications in old worksapaces, I have to manually delete workbench.xmi file (.metadata.plugins\org.eclipse.e4.workbench\workbench.xmi).

It does not matter if I export to "Deployable plug-ins and fragments" (copying to plugin folder) or "Deployable features" (installing it), it works all the same related to the workbench.xmi file issue.
I tried it with Eclipse Neon and Eclipse Oxygen last version.

I don't know if I am doing something wrong, if that is a knowing issue or the way it suppose to be.

I presume I am doing something wrong.
I would like a way to develop E4 plugins, without having to tell my final user to manually delete the workbench.xmi in their old workspaces, to be able to use it.
Or each time they install an update or new plugins I release.

I am new with E4 plugins development, thanks for any help!!!

答:
I found the answer in the other forum I asked it: https://www.eclipse.org/forums/index.php/t/1089590/

In the
plugin.xml file -> Extensions tab -> org.eclipse.e4.workbench.model extension -> (fragment)

Set apply to always, in my new plugin projects apply was set to initial by default.


问:
Subtracting a number of years from a Date
Say I have code: date('Y')."-".date('m')."-".date('d') How would I go about removing a number of years from the date that piece of code gives me?

答:
For your situation you could take advantage of PHP's implicit type casting and simply use

```<code>(date('Y')-42)."-".date('m')."-".date('d')
</code>```

or shorter

```<code>(date('Y')-42)."-".date('m-d')
</code>```

But, as Álvaro G. Vicario observed in a comment, there is the dreaded 29th of February that doesn't exist in all years so you'll have to use strtotime

Example:

```<code>$someDay = strtotime('2009-11-23');
$threeYearsBefore = strtotime('-3 years', $someDay);
echo date('Y-m-d', $threeYearsBefore);
</code>```

or, relative to the current time,

```<code>$threeYearsBefore = strtotime('-3 years');
echo date('Y-m-d', $threeYearsBefore);
</code>```

Body:
For your situation you could take advantage of PHP's implicit type casting and simply use

(date('Y')-42)."-".date('m')."-".date('d')

or shorter

(date('Y')-42)."-".date('m-d')

But, as Álvaro G. Vicario observed in a comment, there is the dreaded 29th of February that doesn't exist in all years so you'll have to use strtotime

Example:

$someDay = strtotime('2009-11-23');
$threeYearsBefore = strtotime('-3 years', $someDay);
echo date('Y-m-d', $threeYearsBefore);

or, relative to the current time,

$threeYearsBefore = strtotime('-3 years');
echo date('Y-m-d', $threeYearsBefore);


问:
Proper date formatting using Get-Date cmdlet in Powershell
I am trying to generate timestamp with the following format
2017-11-11T19:33:27.

With Get-Date -Format o I am able generate 2017-11-13T07:39:32.7958466-05:00

How can I remove milliseconds .7958466-05:00 in the generated output?

答:
Use Get-Date -Format s instead of Get-Date -Format o

Formatting Dates and Times


问:
Git ignores my .gitignore file contents
I'm having a tough time with .gitignore - It simply does not ignore the directories within the file. I have the .gitignore file on both my development and staging enviroment.

The contents are:

```<code>logs
/logs/
/logs/*
logs/
vendor
/vendor/
vendor/
vendor/*
/vendor/*
</code>```

However, each time I do a git pull on staging I am guaranteed that the merge conflict occured for a file logs/access.log - The same counts for composer packages. If I do a composer update with the very next git pull there is normally a conflict.

If I do a git status on my dev machine (after the last push and having visited the site in my dev enviroment) git status indicates changes in the logs/access.log file under "changes not staged for commit" - Why is the file not being ignored entirely?

What am I doing wrong here? The above code is exactly the same for both dev and staging .gitignore files located in the root of my project.

Any advice?

答:
You have to tell git to stop tracking the files. Try,</p>

```<code>git update-index --assume-unchanged [path]
</code>```

Title: Git ignores my .gitignore file contents

Body:
I'm having a tough time with .gitignore - It simply does not ignore the directories within the file. I have the .gitignore file on both my development and staging enviroment.

The contents are:

logs
/logs/
/logs/*
logs/
vendor
/vendor/
vendor/
vendor/*
/vendor/*

However, each time I do a git pull on staging I am guaranteed that the merge conflict occured for a file logs/access.log - The same counts for composer packages. If I do a composer update with the very next git pull there is normally a conflict.

If I do a git status on my dev machine (after the last push and having visited the site in my dev enviroment) git status indicates changes in the logs/access.log file under "changes not staged for commit" - Why is the file not being ignored entirely?

What am I doing wrong here? The above code is exactly the same for both dev and staging .gitignore files located in the root of my project.

Any advice?

Body:
You have to tell git to stop tracking the files. Try,

git update-index --assume-unchanged [path]