问:
Print out all subsets in an array that equal an given sum recursively
I have a weird homework that I have to write a program with a method that takes an array of non-negative integers (array elements can have repeated values) and a value sum as parameters. The method then prints out all the combinations of the elements in array whose sum is equal to sum. The weird part is, the teacher forces us to strictly follow the below structure:

```<code>public class Combinations {

    public static void printCombinations(int[] arr, int sum) {
       // Body of the method
    }

    public static void main(String[] args) {
       // Create 2-3 arrays of integers and 2-3 sums here then call the above
       // method with these arrays and sums to test the correctness of your method
    }

}
</code>```

We are not allow to add neither more methods nor more parameters for the current program. I have researched and understood several ways to do this recursively, but with this restriction, I don't really know how to do it. Therefore, I appreciate if you guys help me out.

EDIT: The array can have repeated elements. Here's an example run of the program.

```<code>arr = {1, 3, 2, 2, 25} and sum = 3
</code>```

Outputs:

(1, 2)  // 1st and 3rd element

(1, 2) // 1st and 4th element

(3) // 2nd element

答:
I think that all algorithms which can be solved with recursion can also be solved with stacks instead of recursion (see solution below). But very often it is easier to solve the problems with recursion before attempting the stack based solutions.

My recursive take on this problems would be in Java something like this:

```<code>public static void printCombinations(int[] array, int pos, int sum, int[] acc) {
    if (Arrays.stream(acc).sum() == sum) {
        System.out.println(Arrays.toString(acc));
    }
    for (int i = pos + 1; i < array.length; i++) {
        int[] newAcc = new int[acc.length + 1];
        System.arraycopy(acc, 0, newAcc, 0, acc.length);
        newAcc[acc.length] = array[i];
        printCombinations(array, i, sum, newAcc);
    }
}
</code>```

This function you can call like this:

```<code>printCombinations(new int[]{1, 3, 2, 2, 25}, -1, 3, new int[]{});
</code>```

And it will print this:

```<code>[1, 2]
[1, 2]
[3]
</code>```

Basically it goes through all possible sets in this array and then filters those out which have the sum of 3 in this case. It is not great, there are for sure better, more efficient ways to do this. But my point here is simply to show that you can convert this algorithm to a stack based implementation.

Here it goes how you can implement the same algorithm using stacks instead of recursion:

```<code>public static void printCombinationsStack(int[] array, int sum) {
    Stack<Integer> stack = new Stack<>();
    stack.push(0);
    while (true) {
        int i = stack.peek();
        if (i == array.length - 1) {
            stack.pop();
            if (stack.isEmpty()) {
                break;
            }
            int last = stack.pop();
            stack.push(last + 1);
        } else {
            stack.push(i + 1);
        }
        if (stack.stream().map(e -> array[e]).mapToInt(Integer::intValue).sum() == sum) {
            System.out.println(stack.stream().map(e -> Integer.toString(array[e]))
                    .collect(Collectors.joining(",")));
        }
    }
}
</code>```

This method can be called like this:

```<code>printCombinationsStack(new int[]{1, 3, 2, 2, 25}, 3);
</code>```

And it outputs also:

```<code>1,2
1,2
3
</code>```

How I came to this conversion of a recursive to a stack based algorithm:

If you observe the positions in the acc array on the first algorithm above, then you will see a pattern which can be emulated by a stack. If you have an initial array with 4 elements, then the positions which are in the acc array are always these:

```<code>[]
[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 3]
[0, 2]
[0, 2, 3]
[0, 3]
[1]
[1, 2]
[1, 2, 3]
[1, 3]
[2]
[2, 3]
[3]
</code>```

There is a pattern here which can easily be emulated with stacks:

The default operation is always to push into the stack, unless you reach the last position in the array. You push first 0 which is the first position in the array. When you reach the last position of the array, you pop once from the array and then pop again and a second popped item which you push back to the stack - incremented by one.

If the stack is empty you break the loop. You have gone through all possible combinations.

Body:
I have a weird homework that I have to write a program with a method that takes an array of non-negative integers (array elements can have repeated values) and a value sum as parameters. The method then prints out all the combinations of the elements in array whose sum is equal to sum. The weird part is, the teacher forces us to strictly follow the below structure:

public class Combinations {

    public static void printCombinations(int[] arr, int sum) {
       // Body of the method
    }

    public static void main(String[] args) {
       // Create 2-3 arrays of integers and 2-3 sums here then call the above
       // method with these arrays and sums to test the correctness of your method
    }

}

We are not allow to add neither more methods nor more parameters for the current program. I have researched and understood several ways to do this recursively, but with this restriction, I don't really know how to do it. Therefore, I appreciate if you guys help me out.

EDIT: The array can have repeated elements. Here's an example run of the program.

arr = {1, 3, 2, 2, 25} and sum = 3

Outputs:

(1, 2)  // 1st and 3rd element

(1, 2) // 1st and 4th element

(3) // 2nd element

Body:
I think that all algorithms which can be solved with recursion can also be solved with stacks instead of recursion (see solution below). But very often it is easier to solve the problems with recursion before attempting the stack based solutions.

My recursive take on this problems would be in Java something like this:

public static void printCombinations(int[] array, int pos, int sum, int[] acc) {
    if (Arrays.stream(acc).sum() == sum) {
        System.out.println(Arrays.toString(acc));
    }
    for (int i = pos + 1; i < array.length; i++) {
        int[] newAcc = new int[acc.length + 1];
        System.arraycopy(acc, 0, newAcc, 0, acc.length);
        newAcc[acc.length] = array[i];
        printCombinations(array, i, sum, newAcc);
    }
}

This function you can call like this:

printCombinations(new int[]{1, 3, 2, 2, 25}, -1, 3, new int[]{});

And it will print this:

[1, 2]
[1, 2]
[3]

Basically it goes through all possible sets in this array and then filters those out which have the sum of 3 in this case. It is not great, there are for sure better, more efficient ways to do this. But my point here is simply to show that you can convert this algorithm to a stack based implementation.

Here it goes how you can implement the same algorithm using stacks instead of recursion:

public static void printCombinationsStack(int[] array, int sum) {
    Stack<Integer> stack = new Stack<>();
    stack.push(0);
    while (true) {
        int i = stack.peek();
        if (i == array.length - 1) {
            stack.pop();
            if (stack.isEmpty()) {
                break;
            }
            int last = stack.pop();
            stack.push(last + 1);
        } else {
            stack.push(i + 1);
        }
        if (stack.stream().map(e -> array[e]).mapToInt(Integer::intValue).sum() == sum) {
            System.out.println(stack.stream().map(e -> Integer.toString(array[e]))
                    .collect(Collectors.joining(",")));
        }
    }
}

This method can be called like this:

printCombinationsStack(new int[]{1, 3, 2, 2, 25}, 3);

And it outputs also:

1,2
1,2
3

How I came to this conversion of a recursive to a stack based algorithm:

If you observe the positions in the acc array on the first algorithm above, then you will see a pattern which can be emulated by a stack. If you have an initial array with 4 elements, then the positions which are in the acc array are always these:

[]
[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 3]
[0, 2]
[0, 2, 3]
[0, 3]
[1]
[1, 2]
[1, 2, 3]
[1, 3]
[2]
[2, 3]
[3]

There is a pattern here which can easily be emulated with stacks:

The default operation is always to push into the stack, unless you reach the last position in the array. You push first 0 which is the first position in the array. When you reach the last position of the array, you pop once from the array and then pop again and a second popped item which you push back to the stack - incremented by one.

If the stack is empty you break the loop. You have gone through all possible combinations.


来源: stackexchange

问:
Pass Drawable from Fragment to Dialogfragment using Bundle
I need to pass a drawable (mDLlist.get(position).getImageId()) from a Fragment to a DialogFragment.

I can`t seem to find a way how to do this, any input would be great.

Thank you upfront.

```<code>...
FragmentManager ft = ((FragmentActivity)context1).getSupportFragmentManager();
DialogFragment newFragment = MyNotification.newInstance();

Bundle args = new Bundle();
// How to pass this value ?
args.put?("appdraw", mDLlist.get(position).getImageId());
//--//
args.putString("appname", (String)mDLlist.get(position).getLabelnameText());
args.putString("appversion", mDLlist.get(position).getVersionName());
args.putString("appinstalltime", "Downloaded");
newFragment.setArguments(args);

newFragment.show(ft, "mydialog");
...
</code>```

答:
You cannot pass a Drawable via a Bundle since it doesnt implement Serializable and I dont think you can implement Parcelable.

If its a Drawable thats already in your package you can just pass a String or Resource ID so you can look it up again.

If its Bitmap you will need to write it to local storage and pass the path.

ContentLicense: CC BY-SA 3.0

Body:
I need to pass a drawable (mDLlist.get(position).getImageId()) from a Fragment to a DialogFragment.

I can`t seem to find a way how to do this, any input would be great.

Thank you upfront.

...
FragmentManager ft = ((FragmentActivity)context1).getSupportFragmentManager();
DialogFragment newFragment = MyNotification.newInstance();

Bundle args = new Bundle();
// How to pass this value ?
args.put?("appdraw", mDLlist.get(position).getImageId());
//--//
args.putString("appname", (String)mDLlist.get(position).getLabelnameText());
args.putString("appversion", mDLlist.get(position).getVersionName());
args.putString("appinstalltime", "Downloaded");
newFragment.setArguments(args);

newFragment.show(ft, "mydialog");
...


问:
How can I erase my data from textarea using javascript?
How can i erase my data from textarea using javascript ?

This code:

```<code><textarea class="mails" tabindex="1" onfocus="this.className='writing'" onblur="this.className='mails'" onkeypress="this.className='writing'" >يمكنك إضافة أكثر من بريد إلكتروني. أضف "," بين كل إدخال</textarea>
</code>```

答:
give your textarea an id first

```<code><textarea id="txtarea" class="mails" tabindex="1" onfocus="this.className='writing'" onblur="this.className='mails'" onkeypress="this.className='writing'" >يمكنك إضافة أكثر من بريد إلكتروني. أضف "," بين كل إدخال</textarea>
</code>```

and use this in your JS

```<code>document.getElementById("txtarea").value = "";
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can i erase my data from textarea using javascript ?

This code:

<textarea class="mails" tabindex="1" onfocus="this.className='writing'" onblur="this.className='mails'" onkeypress="this.className='writing'" >يمكنك إضافة أكثر من بريد إلكتروني. أضف "," بين كل إدخال</textarea>

Body:
give your textarea an id first

<textarea id="txtarea" class="mails" tabindex="1" onfocus="this.className='writing'" onblur="this.className='mails'" onkeypress="this.className='writing'" >يمكنك إضافة أكثر من بريد إلكتروني. أضف "," بين كل إدخال</textarea>

and use this in your JS

document.getElementById("txtarea").value = "";

ContentLicense: CC BY-SA 2.5


问:
Dropbox API V2 authenticateWithCordova not working as expected
I have Cordova application in which have implemented the Dropbox functionality using javascript SDK. I use authenticateWithCordova method to authenticate the users.

The authenticateWithCordova method works fine for the first time and successfully returns the access token. The access token can then be subsequently used for other operations such as upload, download etc.

I am using as below URI as redirect URI,

```<code>https://www.dropbox.com/1/oauth2/redirect_receiver
</code>```

When I call authenticateWithCordova method for the second time it shows a login screen for second and returns to the app. I want the users to be able to use different Dropbox accounts.Need Some Help!

答:
If the user signed in to the browser has already authorized your app, they may be automatically redirected back to your app instead of having to provide explicit authorization again.

The API offers the ability to control that using the force_reapprove parameter on /oauth2/authorize, though that's unfortunately not currently implemented in the API v2 JavaScript SDK itself, e.g., for the authenticateWithCordova method. We'll consider it a feature request for implementing that in the SDK, but I can't promise if/when that would be done.

If you need a workaround, you can direct the user to https://www.dropbox.com/logout to log out of the account first.

Body:
I have Cordova application in which have implemented the Dropbox functionality using javascript SDK. I use authenticateWithCordova method to authenticate the users.

The authenticateWithCordova method works fine for the first time and successfully returns the access token. The access token can then be subsequently used for other operations such as upload, download etc.

I am using as below URI as redirect URI,

https://www.dropbox.com/1/oauth2/redirect_receiver

When I call authenticateWithCordova method for the second time it shows a login screen for second and returns to the app. I want the users to be able to use different Dropbox accounts.Need Some Help!


问:
Form Validation between multiple input fields
So I have a form with multiple input form fields,and a nested form group. In the nested formgroup, the validation should be such that if any one of the three inputs is filled, then the form should be valid. The person can fill either all, or even just one and the form should be valid. My template code is as follows:

```<code> <h3 class="form-title">{{title}}</h3>
<form [formGroup]="formX" novalidate>
    <div formGroupName="brandIdentifier">
        <mat-form-field class="full-width">
            <mat-icon matSuffix color="primary" *ngIf="brandName.valid && brandName.touched">done</mat-icon>
            <mat-icon matSuffix color="primary" *ngIf="brandName.invalid && brandName.touched">close</mat-icon>
            <input matInput type="text" placeholder="Brand Name" formControlName="brandName" />
        </mat-form-field>
        <mat-form-field class="full-width">
            <mat-icon matSuffix color="primary" *ngIf="brandId.valid && brandId.touched">done</mat-icon>
            <mat-icon matSuffix color="primary" *ngIf="brandId.invalid && brandId.touched">close</mat-icon>
            <input matInput type="text" placeholder="Brand Id" formControlName="brandId" />
        </mat-form-field>
        <mat-form-field class="full-width">
            <mat-icon matSuffix color="primary" *ngIf="contentId.valid && contentId.touched">done</mat-icon>
            <mat-icon matSuffix color="primary" *ngIf="contentId.invalid && contentId.touched">close</mat-icon>
            <input matInput type="text" placeholder="Content Id" formControlName="contentId" />
        </mat-form-field>
    </div>
    <mat-form-field class="full-width">
        <mat-icon matSuffix color="primary" *ngIf="startTime.valid && startTime.touched">done</mat-icon>
        <mat-icon matSuffix color="primary" *ngIf="startTime.invalid && startTime.touched">close</mat-icon>
        <input matInput type="text" placeholder="Start Time" formControlName="startTime" />
    </mat-form-field>
    <mat-form-field class="full-width">
        <mat-icon matSuffix color="primary" *ngIf="endTime.valid && endTime.touched">done</mat-icon>
        <mat-icon matSuffix color="primary" *ngIf="endTime.invalid && endTime.touched">close</mat-icon>
        <input matInput type="text" placeholder="End Time" formControlName="endTime" />
    </mat-form-field>

    <button mat-raised-button color="primary" (click)="startAnalysis()" [ngClass]="{'form-valid':formX.valid, 'form-invalid':formX.invalid}">Submit</button>

    ```{{formX.value | json}}```
</form>
</code>```

How would I go about this? using Validator class is a given, but I'm unable to get it optional.

答:
You can use a custom validator for this, apply the custom validator for the nested group, where we check that at least one of the three fields has a value else than empty string, so here's a sample:

Build form:

```<code>this.myForm = this.fb.group({
  nestedGroup: this.fb.group({
    first: [''],
    second: [''],
    third: ['']
    // apply custom validator for the nested group only
  }, {validator: this.myCustomValidator})
});
</code>```

Custom validator:

```<code> myCustomValidator(group: FormGroup) {
   // if true, all fields are empty
   let bool = Object.keys(group.value).every(x => group.value[x] === '')
   if(bool) {
     // return validation error
     return { allEmpty: true}
   }
   // valid
   return null;
 }
</code>```

Then in your form you can show the validation message by:

```<code><small *ngIf="myForm.hasError('allEmpty','nestedGroup')">
  Please fill at least one field
</small>
</code>```

Finally a DEMO :)

Body:
So I have a form with multiple input form fields,and a nested form group. In the nested formgroup, the validation should be such that if any one of the three inputs is filled, then the form should be valid. The person can fill either all, or even just one and the form should be valid. My template code is as follows:

{{title}}

<form [formGroup]="formX" novalidate>

        <mat-form-field class="full-width">
            <mat-icon matSuffix color="primary" *ngIf="brandName.valid && brandName.touched">done</mat-icon>
            <mat-icon matSuffix color="primary" *ngIf="brandName.invalid && brandName.touched">close</mat-icon>
            <input matInput type="text" placeholder="Brand Name" formControlName="brandName" />
        </mat-form-field>
        <mat-form-field class="full-width">
            <mat-icon matSuffix color="primary" *ngIf="brandId.valid && brandId.touched">done</mat-icon>
            <mat-icon matSuffix color="primary" *ngIf="brandId.invalid && brandId.touched">close</mat-icon>
            <input matInput type="text" placeholder="Brand Id" formControlName="brandId" />
        </mat-form-field>
        <mat-form-field class="full-width">
            <mat-icon matSuffix color="primary" *ngIf="contentId.valid && contentId.touched">done</mat-icon>
            <mat-icon matSuffix color="primary" *ngIf="contentId.invalid && contentId.touched">close</mat-icon>
            <input matInput type="text" placeholder="Content Id" formControlName="contentId" />
        </mat-form-field>

    <mat-form-field class="full-width">
        <mat-icon matSuffix color="primary" *ngIf="startTime.valid && startTime.touched">done</mat-icon>
        <mat-icon matSuffix color="primary" *ngIf="startTime.invalid && startTime.touched">close</mat-icon>
        <input matInput type="text" placeholder="Start Time" formControlName="startTime" />
    </mat-form-field>
    <mat-form-field class="full-width">
        <mat-icon matSuffix color="primary" *ngIf="endTime.valid && endTime.touched">done</mat-icon>
        <mat-icon matSuffix color="primary" *ngIf="endTime.invalid && endTime.touched">close</mat-icon>
        <input matInput type="text" placeholder="End Time" formControlName="endTime" />
    </mat-form-field>

    <button mat-raised-button color="primary" (click)="startAnalysis()" [ngClass]="{'form-valid':formX.valid, 'form-invalid':formX.invalid}">Submit</button>

{{formX.value | json}}

</form>

How would I go about this? using Validator class is a given, but I'm unable to get it optional.

Body:
You can use a custom validator for this, apply the custom validator for the nested group, where we check that at least one of the three fields has a value else than empty string, so here's a sample:

Build form:

this.myForm = this.fb.group({
  nestedGroup: this.fb.group({
    first: [''],
    second: [''],
    third: ['']
    // apply custom validator for the nested group only
  }, {validator: this.myCustomValidator})
});

Custom validator:

 myCustomValidator(group: FormGroup) {
   // if true, all fields are empty
   let bool = Object.keys(group.value).every(x => group.value[x] === '')
   if(bool) {
     // return validation error
     return { allEmpty: true}
   }
   // valid
   return null;
 }

Then in your form you can show the validation message by:

<small *ngIf="myForm.hasError('allEmpty','nestedGroup')">
  Please fill at least one field
</small>

Finally a DEMO :)


问:
Memcpy uint32_t into char*
I testing a bit with different formats and stuff like that. And we got a task where we have to put uint32_t into char*. This is the code i use:

```<code>void appendString(string *s, uint32_t append){
    char data[4];
    memcpy(data, &append, sizeof(append));
    s->append(data);
}

void appendString(string *s, short append){
    char data[2];
    memcpy(data, &append, sizeof(append));
    s->append(data);
}
</code>```

From string to char is simple and we have to add multiple uints into the char*. So now i'm just calling it like:

```<code>string s;
appendString(&s, (uint32_t)1152); //this works
appendString(&s, (uint32_t)640); //this also works
appendString(&s, (uint32_t)512); //this doesn't work
</code>```

I absolutely don't understand why the last one isn't working properly. I've tested multiple variations of transform this. One way always gave me output like (in bits): 00110100 | 00110101 ... so the first 2 bits are always zero, followed by 11 and then for me some random numbers.. What am i doing wrong?

答:
Assuming that string is std::string, then the single-argument version of std::string::append is being used, which assumes the input data is NUL-terminated.  Yours is not, but append will go looking for the first NUL byte anyway.

512 is 0x00000100, which on a little endian machine is 0x00 0x01 0x00 0x00.  Since the first byte is NUL, std::string::append() stops there.

Use the version of std::string::append() where you pass in the length.

Title: Memcpy uint32_t into char*

Body:
I testing a bit with different formats and stuff like that. And we got a task where we have to put uint32_t into char*. This is the code i use:

void appendString(string *s, uint32_t append){
    char data[4];
    memcpy(data, &append, sizeof(append));
    s->append(data);
}

void appendString(string *s, short append){
    char data[2];
    memcpy(data, &append, sizeof(append));
    s->append(data);
}

From string to char is simple and we have to add multiple uints into the char*. So now i'm just calling it like:

string s;
appendString(&s, (uint32_t)1152); //this works
appendString(&s, (uint32_t)640); //this also works
appendString(&s, (uint32_t)512); //this doesn't work

I absolutely don't understand why the last one isn't working properly. I've tested multiple variations of transform this. One way always gave me output like (in bits): 00110100 | 00110101 ... so the first 2 bits are always zero, followed by 11 and then for me some random numbers.. What am i doing wrong?


问:
Why don't we instantiate delegating classes with their delegate objects?
I can't imagine a delegating downloader class or CLLLocationManager or tableView be without a delegate. So why do we need create it as an optional?

Why do we do

```<code>tableview = UITableView()
tableview.delegate = self
tableview.dataSource = self
</code>```

Why isn't the API made so we could just do:

```<code>tableview = UITableView(delegate: self, dataSource: self)
</code>```

Is this because memory cycles, so we could first nil either the delegating class or the delegate class and then the other? Is that the only reason?

Even if that's the case, still isn't it just more convenient to make it insatiable using

```<code>class tableView{
    var delegate: UITableViewDelegate?
    var dataSource: UITableViewDataSource?

    init(delegate: UITableViewDelegate? = nil, dataSource: UITableViewDataSource?){
        self.delegate = delegate
        self.dataSource = dataSource
    }
}

var tableView = tableView()
</code>```

答:
Actually there are several scenarios where you do not need a delegate.

Look at the following screen.

Question

How many elements without its delegate can you find?

Answer

There are 4 UI elements without a delegate:

A UITableView in the top of the screen

The UITextField for the Username

The UITextField for the Password

A UITextView in the bottom of the screen

Body:
I can't imagine a delegating downloader class or CLLLocationManager or tableView be without a delegate. So why do we need create it as an optional?

Why do we do

tableview = UITableView()
tableview.delegate = self
tableview.dataSource = self

Why isn't the API made so we could just do:

tableview = UITableView(delegate: self, dataSource: self)

Is this because memory cycles, so we could first nil either the delegating class or the delegate class and then the other? Is that the only reason?

Even if that's the case, still isn't it just more convenient to make it insatiable using

class tableView{
    var delegate: UITableViewDelegate?
    var dataSource: UITableViewDataSource?

    init(delegate: UITableViewDelegate? = nil, dataSource: UITableViewDataSource?){
        self.delegate = delegate
        self.dataSource = dataSource
    }
}

var tableView = tableView()


问:
Drupal temporary wizard form
I am creating a wizard form to order items, I have 4 content types, project | door | dooroptions | projectoptions.

This is done in 4 steps: You give tour measurements, the doors that fit are show, you pick a door, you pick the options for the door. then you can add another door, or you can save the project (with the doors).

Saving the project then requires you to log in, or register. So one project has multiple doors. Only then the nodes should be saved

Everything you selected and configured, should be editable before saving. When filling in the forms, there is no known user.

My question is: how would you handle this?

Any info is welcome.

@edit

I was thinking to save all the content anyhow. Putting a boolean on the most parent node which defines if the project is "stored" or not. Then when the user registers or logs in, the bit is set to true, and a user reference is created in the project node.

Every (... hours) a cron job runs and removes the nodes that have "stored" bit false, and creationdate older then ... hours.

Another way would be to save al the forms in drupacl cache, and when logged in save all the nodes. I don't know if this is possible tough

答:
after save it by unauthorized user, I think you should save Node id in session and after log in you should read from session and do something with it and destroy session. for this I think this steps is necessary:

1- some Drupal Trigger to save Node ID before log in,

2- redirect user after log in to a page with some PHP code that read session and assign them to authorized user

3- some rules for continue

Title: Drupal temporary wizard form


问:
Sorting by Subarray type value and then alphabetically
I have an array that looks something like this:

```<code>$array = [
    'field1' => [
        '#type' => 'text',
        '#label' => 'Field 11',
    ],
    'field4' => [
        '#type' => 'fieldset',
        '#label' => 'Field 4',
    ],
    'field12' => [
        '#type' => 'text',
        '#label' => 'Field 12',
    ],
    'field3' => [
        '#type' => 'fieldset',
        '#label' => 'Field 3',
    ],
    'field18' => [
        '#type' => 'text',
        '#label' => 'Field 18',
    ],
];
</code>```

I would like to sort this array in such a way where all the fields of type fieldset are at the bottom. At the same time, I would like the text fields (which are on top) to be sorted alphabetically by the #label and the fieldsets (which should be at the bottom) should also be sorted alphabetically by the label. This is what I had so far.

```<code>ksort($array);
uasort($array, function($field1) {
    if ($field1['#type'] !== 'fieldset') {
        return 0;
    }
    return 1;
});
</code>```

Sorting the array by the key value successfully sorts my entire array alphabetically. But once I add the uasort, although my fieldset's are at the bottom, the alphabetical order is no longer present.

Any ideas?

答:
Use usort with 2 conditions</p>

```<code> usort($array, function ($i1, $i2) {
                 // compare types
                 $r = ($i1['#type'] == 'fieldset' ? 1 : 0) -  ($i2['#type'] == 'fieldset' ? 1 : 0);
                 // if both are (or not) fieldset (r == 0), compare labels
                 return $r ? $r : strcmp($i1['#label'], $i2['#label']);  } );
</code>```

Body:
I have an array that looks something like this:

$array = [
    'field1' => [
        '#type' => 'text',
        '#label' => 'Field 11',
    ],
    'field4' => [
        '#type' => 'fieldset',
        '#label' => 'Field 4',
    ],
    'field12' => [
        '#type' => 'text',
        '#label' => 'Field 12',
    ],
    'field3' => [
        '#type' => 'fieldset',
        '#label' => 'Field 3',
    ],
    'field18' => [
        '#type' => 'text',
        '#label' => 'Field 18',
    ],
];

I would like to sort this array in such a way where all the fields of type fieldset are at the bottom. At the same time, I would like the text fields (which are on top) to be sorted alphabetically by the #label and the fieldsets (which should be at the bottom) should also be sorted alphabetically by the label. This is what I had so far.

ksort($array);
uasort($array, function($field1) {
    if ($field1['#type'] !== 'fieldset') {
        return 0;
    }
    return 1;
});

Sorting the array by the key value successfully sorts my entire array alphabetically. But once I add the uasort, although my fieldset's are at the bottom, the alphabetical order is no longer present.

Any ideas?

Body:
Use usort with 2 conditions

 usort($array, function ($i1, $i2) {
                 // compare types
                 $r = ($i1['#type'] == 'fieldset' ? 1 : 0) -  ($i2['#type'] == 'fieldset' ? 1 : 0);
                 // if both are (or not) fieldset (r == 0), compare labels
                 return $r ? $r : strcmp($i1['#label'], $i2['#label']);  } );


问:
Getting the correct output value in calculator for Sin, Cos & Tan
I am learning Swift by using the Stanford ios10 course notes and I was checking the output of Cos and found it was not correct.
By research I found that the input value of the cos must be in Radians.
I have written a func to calculate the correct Natural Cosine.

```<code>func cosine(degrees: Double) -> Double {
    return cos(degrees*Double.pi/180)
}
</code>```

When I tried modifying the following, to:

```<code>"cos" : Operation.unaryOperation(cosine(degrees)),
</code>```

It said "use of unresolved identifier 'degrees'"

This is the var I was trying to modify:

```<code>private var operations: Dictionary<String,Operation> = [
    "π" : Operation.constant(Double.pi),
    "e" : Operation.constant(M_E),
    "√" : Operation.unaryOperation(sqrt),
    "cos" : Operation.unaryOperation(cos),
    "±" : Operation.unaryOperation({-$0}),
    "×" : Operation.binaryOperation({ $0 * $1}),
    "÷" : Operation.binaryOperation({ $0 / $1}),
    "+" : Operation.binaryOperation(){ $0 + $1},
    "−" : Operation.binaryOperation(){ $0 - $1},
    "=" : Operation.equals
]
</code>```

As I am a beginner I'm not sure that I am doing it right!
Please help!

答:
Look at the arguments you pass to the binary operators and the - unary operator. Pass the same argument to cosine.

```<code>"cos" : Operation.unaryOperation({cosine(degrees: $0)}),
</code>```

Do the same for your sqrt function.

Body:
I am learning Swift by using the Stanford ios10 course notes and I was checking the output of Cos and found it was not correct.
By research I found that the input value of the cos must be in Radians.
I have written a func to calculate the correct Natural Cosine.

func cosine(degrees: Double) -> Double {
    return cos(degrees*Double.pi/180)
}

When I tried modifying the following, to:

"cos" : Operation.unaryOperation(cosine(degrees)),

It said "use of unresolved identifier 'degrees'"

This is the var I was trying to modify:

private var operations: Dictionary<String,Operation> = [
    "π" : Operation.constant(Double.pi),
    "e" : Operation.constant(M_E),
    "√" : Operation.unaryOperation(sqrt),
    "cos" : Operation.unaryOperation(cos),
    "±" : Operation.unaryOperation({-$0}),
    "×" : Operation.binaryOperation({ $0 * $1}),
    "÷" : Operation.binaryOperation({ $0 / $1}),
    "+" : Operation.binaryOperation(){ $0 + $1},
    "−" : Operation.binaryOperation(){ $0 - $1},
    "=" : Operation.equals
]

As I am a beginner I'm not sure that I am doing it right!
Please help!

Body:
Look at the arguments you pass to the binary operators and the - unary operator. Pass the same argument to cosine.

"cos" : Operation.unaryOperation({cosine(degrees: $0)}),

Do the same for your sqrt function.


问:
Ubuntu 14.04: crontab -e open a weird file
Since I've reboot my server now when I open my crontab file using

crontab -e

Vim is opening a file called:

/tmp/crontab.yWhf4u/crontab

Who is empty...

I would like to know what I did wrong and how I can fix my mistake, please?

My command to reboot the server was

shutdown -r now

答:
crontab -e creates a temporary file that's a copy of your crontab. After you leave the editor, it rereads the temporary file and uses it to update your crontab. (Your actual crontab is in a file in a system directory that you won't have access to without root permissions. Don't try to edit that file directly.)

Apparently your crontab is empty. crontab -l dumps the contents of your crontab to standard output; if that produces no output, it will verify that you have an empty crontab.

You didn't say so, but I presume you thought you had a non-empty crontab. It's easy to clobber your crontab accidentally. For example, if you type crontab with no arguments, it will read a new crontab from standard input; if you then type ctrl-D, it will replace your existing crontab with an empty one.

There's not really a good way to restore your previous crontab. It might exist in a system backup.

In the future, I suggest keeping a copy of your crontab in a separate file, backed up in some way (I use a version control system), and use crontab filename to load the contents of that file into your crontab. That way if you accidentally clobber your crontab, you can easily reload it.


问:
Extract columns from text based table output
qfarm /load command shows me the load from my servers.
Output:

```<code>PS> qfarm /load

Server Name           Server Load  Load Throttling Load  Logon Mode
--------------------  -----------  --------------------  ------------------
SERVER-01             400          0                     AllowLogons
SERVER-02             1364         OFF                   AllowLogons
SERVER-03             1364         OFF                   AllowLogons
SERVER-04             1000         0                     AllowLogons
SERVER-05             700          0                     AllowLogons
SERVER-06             1200         0                     AllowLogons
</code>```

I need to display only first column (Server Name) and the second one (Server Load) and loop through them, in order to make some logic later, but it seems the powershell doesn't see it as object with properties:

```<code>PS> qfarm /load | Select -ExpandProperty "Server Name"
Select-Object : Property "Server Name" cannot be found.
</code>```

Is there any other possibility, like a table or something?

答:
I have answered something very similar to this in the past. I have a larger function for this but a simplified on work on left aligned string table just as you have shown in you example. See the linked answer for more explanation.

```<code>function ConvertFrom-LeftAlignedStringData{
    param (
        [string[]]$data
    )

    $headerString = $data[0]
    $headerElements = $headerString -split "\s{2,}" | Where-Object{$_}
    $headerIndexes = $headerElements | ForEach-Object{$headerString.IndexOf($_)}

    $results = $data | Select-Object -Skip 2  | ForEach-Object{
        $props = @{}
        $line = $_
        For($indexStep = 0; $indexStep -le $headerIndexes.Count - 1; $indexStep++){
            $value = $null            # Assume a null value
            $valueLength = $headerIndexes[$indexStep + 1] - $headerIndexes[$indexStep]
            $valueStart = $headerIndexes[$indexStep]
            If(($valueLength -gt 0) -and (($valueStart + $valueLength) -lt $line.Length)){
                $value = ($line.Substring($valueStart,$valueLength)).Trim()
            } ElseIf ($valueStart -lt $line.Length){
                $value = ($line.Substring($valueStart)).Trim()
            }
            $props.($headerElements[$indexStep]) = $value
        }
        New-Object -TypeName PsCustomObject -Property $props
    }

    return $results
}

$qfarmOutput = qfarm /load
ConvertFrom-LeftAlignedStringData $qfarmOutput | select "Server Name","Server Load"
</code>```

This approach is based on the position of the header fields. Nothing is hardcoded and it is all custom built based on those indexes and field names. Using those $headerIndexes we carve up every line and place the results, if present, into its respective column. There is logic to ensure that we don't try and grab any part of the string that might not exist and treat the last field special.

Results

```<code>Server Name Server Load
----------- -----------
SERVER-01   400
SERVER-02   1364
SERVER-03   1364
SERVER-04   1000
SERVER-05   700
SERVER-06   1200
</code>```

Body:
qfarm /load command shows me the load from my servers.
Output:

PS> qfarm /load

Server Name           Server Load  Load Throttling Load  Logon Mode
--------------------  -----------  --------------------  ------------------
SERVER-01             400          0                     AllowLogons
SERVER-02             1364         OFF                   AllowLogons
SERVER-03             1364         OFF                   AllowLogons
SERVER-04             1000         0                     AllowLogons
SERVER-05             700          0                     AllowLogons
SERVER-06             1200         0                     AllowLogons

I need to display only first column (Server Name) and the second one (Server Load) and loop through them, in order to make some logic later, but it seems the powershell doesn't see it as object with properties:

PS> qfarm /load | Select -ExpandProperty "Server Name"
Select-Object : Property "Server Name" cannot be found.

Is there any other possibility, like a table or something?

Body:
I have answered something very similar to this in the past. I have a larger function for this but a simplified on work on left aligned string table just as you have shown in you example. See the linked answer for more explanation.

function ConvertFrom-LeftAlignedStringData{
    param (
        [string[]]$data
    )

    $headerString = $data[0]
    $headerElements = $headerString -split "\s{2,}" | Where-Object{$_}
    $headerIndexes = $headerElements | ForEach-Object{$headerString.IndexOf($_)}

    $results = $data | Select-Object -Skip 2  | ForEach-Object{
        $props = @{}
        $line = $_
        For($indexStep = 0; $indexStep -le $headerIndexes.Count - 1; $indexStep++){
            $value = $null            # Assume a null value
            $valueLength = $headerIndexes[$indexStep + 1] - $headerIndexes[$indexStep]
            $valueStart = $headerIndexes[$indexStep]
            If(($valueLength -gt 0) -and (($valueStart + $valueLength) -lt $line.Length)){
                $value = ($line.Substring($valueStart,$valueLength)).Trim()
            } ElseIf ($valueStart -lt $line.Length){
                $value = ($line.Substring($valueStart)).Trim()
            }
            $props.($headerElements[$indexStep]) = $value
        }
        New-Object -TypeName PsCustomObject -Property $props
    }

    return $results
}

$qfarmOutput = qfarm /load
ConvertFrom-LeftAlignedStringData $qfarmOutput | select "Server Name","Server Load"

This approach is based on the position of the header fields. Nothing is hardcoded and it is all custom built based on those indexes and field names. Using those $headerIndexes we carve up every line and place the results, if present, into its respective column. There is logic to ensure that we don't try and grab any part of the string that might not exist and treat the last field special.

Results

Server Name Server Load
----------- -----------
SERVER-01   400
SERVER-02   1364
SERVER-03   1364
SERVER-04   1000
SERVER-05   700
SERVER-06   1200


问:
Graph categorical variable in R
Picture of how I want the graph to look

I have a dataset with the following 3 variables:

Condition, categorical with 3 levels: control, eyes, camera

mean_destruction, continuous, values range between 0-10, n=120

mean_expectation, continuous, range between 0-10, n=120

For example:

```<code>df1 <- data.frame(Condition = c(rep('Control', 40), rep('Eyes', 40), rep('Camera', 40)),
                 mean_destruction = sample(0:10, 120, replace = T),
                 mean_expectation = sample(0:10, 120, replace = T))
</code>```

I am trying to graph this in ggplot 2 and failing.  Here is one of my many ahem efforts to reproduce the below image:

```<code>ggplot(data=df1, aes(x= Condition, y=(mean.destruction), fill=(mean.expected)) +
    geom_bar(stat="identity", position=position_dodge(), colour="black")))
</code>```

答:
Here's an answer that uses dplyr and tidyr.

Here's how I'm interpreting your data:

```<code>set.seed(2112)

df1 <- data.frame(Condition = c(rep('Control', 40), rep('Eyes', 40), rep('Camera', 40)),
                 mean_destruction = sample(0:10, 120, replace = T),
                 mean_expectation = sample(0:10, 120, replace = T))
</code>```

You'll need to transform your data into long so you can get different bars for destruction and expectation:

```<code>library(ggplot2)
library(dplyr)
library(tidyr)

df1 <- df1 %>%
      gather(mean_destruction, mean_expectation, key = mean_type, value = value) %>%
      group_by(Condition, mean_type) %>%
      summarize(mean = mean(value))

> df1
Source: local data frame [6 x 3]
Groups: Condition [?]

  Condition        mean_type  mean
     (fctr)            (chr) (dbl)
1    Camera mean_destruction  4.90
2    Camera mean_expectation  5.20
3   Control mean_destruction  4.85
4   Control mean_expectation  5.30
5      Eyes mean_destruction  4.40
6      Eyes mean_expectation  4.15
</code>```

Then your ggplot2 call just needs a bit of tweaking:

```<code>ggplot(data=df1, aes(x = Condition, y = mean, fill = mean_type)) +
         geom_bar(stat="identity", position = 'dodge', colour="black")
</code>```

Title: Graph categorical variable in R

Body:
Picture of how I want the graph to look

I have a dataset with the following 3 variables:

Condition, categorical with 3 levels: control, eyes, camera

mean_destruction, continuous, values range between 0-10, n=120

mean_expectation, continuous, range between 0-10, n=120

For example:

df1 <- data.frame(Condition = c(rep('Control', 40), rep('Eyes', 40), rep('Camera', 40)),
                 mean_destruction = sample(0:10, 120, replace = T),
                 mean_expectation = sample(0:10, 120, replace = T))

I am trying to graph this in ggplot 2 and failing.  Here is one of my many ahem efforts to reproduce the below image:

ggplot(data=df1, aes(x= Condition, y=(mean.destruction), fill=(mean.expected)) +
    geom_bar(stat="identity", position=position_dodge(), colour="black")))

Body:
Here's an answer that uses dplyr and tidyr.

Here's how I'm interpreting your data:

set.seed(2112)

df1 <- data.frame(Condition = c(rep('Control', 40), rep('Eyes', 40), rep('Camera', 40)),
                 mean_destruction = sample(0:10, 120, replace = T),
                 mean_expectation = sample(0:10, 120, replace = T))

You'll need to transform your data into long so you can get different bars for destruction and expectation:

library(ggplot2)
library(dplyr)
library(tidyr)

df1 <- df1 %>%
      gather(mean_destruction, mean_expectation, key = mean_type, value = value) %>%
      group_by(Condition, mean_type) %>%
      summarize(mean = mean(value))

> df1
Source: local data frame [6 x 3]
Groups: Condition [?]

  Condition        mean_type  mean
     (fctr)            (chr) (dbl)
1    Camera mean_destruction  4.90
2    Camera mean_expectation  5.20
3   Control mean_destruction  4.85
4   Control mean_expectation  5.30
5      Eyes mean_destruction  4.40
6      Eyes mean_expectation  4.15

Then your ggplot2 call just needs a bit of tweaking:

ggplot(data=df1, aes(x = Condition, y = mean, fill = mean_type)) +
         geom_bar(stat="identity", position = 'dodge', colour="black")


问:
How to perform two results with a single $('#id').on('change', function);
I have let's say sets of div:

```<code><body>
<div id="div1" style="display: block">
    <p> paragraph here </p>``
    <img>
    <table></table>
</div>

<div id="div2" style="display: none">
    <p> paragraph here </p>
    <img>
    <table></table>
</div>
</code>```

I surrounded each contents with div.

Now I have two radio buttons:

```<code><label for="button1"> Button1 </label>
<input id="button1" name="button" type="radio" value="block">
<label for="button2"> Button2</label>
<input id="button2" name="button" type="radio" value="block">
</code>```

Now what I want to do is to hide the current div and display the second div in place of the first div using .css().
The method I have now is:

```<code>$('#button1').on('change', function1);
function function1() {
    let change1 = $('#button1').val();
        $('#div1').css('display', change1);
</code>```

but here, when I tried the second button:

```<code>$('#button2').on('change',function2);
function function2() {
    let change2 = $('#button2').val();
        $('#div2').css('display', change2);
        $('#div1').css('display', 'none');
</code>```

but it doesn't work, it can only execute one or the other but not both of them. Anyone knows the problem?
Thank you.

答:
Is this what you are trying for?

$('#btn1').click(function () {
  $('#div1').css('display', 'block')
  $('#div2').css('display', 'none')
})

$('#btn2').click(function () {
  $('#div2').css('display', 'block')
  $('#div1').css('display', 'none')
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#div1, #div2 {
  width: 200px;
  border: 1px solid black;
}

#div1 p, #div2 p {
  line-height: 100px;
  text-align: center;
}</code>```

paragraph in div 1

paragraph in div 2

<button id="btn1">Button 1</button>
<button id="btn2">Button 2</button>

```

Body:
I have let's say sets of div:

 paragraph here
``

 paragraph here

I surrounded each contents with div.

Now I have two radio buttons:

 Button1
<input id="button1" name="button" type="radio" value="block">
 Button2
<input id="button2" name="button" type="radio" value="block">

Now what I want to do is to hide the current div and display the second div in place of the first div using .css().
The method I have now is:

$('#button1').on('change', function1);
function function1() {
    let change1 = $('#button1').val();
        $('#div1').css('display', change1);

but here, when I tried the second button:

$('#button2').on('change',function2);
function function2() {
    let change2 = $('#button2').val();
        $('#div2').css('display', change2);
        $('#div1').css('display', 'none');

but it doesn't work, it can only execute one or the other but not both of them. Anyone knows the problem?
Thank you.

Body:
Is this what you are trying for?

$('#btn1').click(function () {
  $('#div1').css('display', 'block')
  $('#div2').css('display', 'none')
})

$('#btn2').click(function () {
  $('#div2').css('display', 'block')
  $('#div1').css('display', 'none')
})

#div1, #div2 {
  width: 200px;
  border: 1px solid black;
}

#div1 p, #div2 p {
  line-height: 100px;
  text-align: center;
}

<div id="div1" style="display: none;">
  <p>paragraph in div 1</p>
</div>

<div id="div2" class="hidden">
    <p>paragraph in div 2</p>
</div>

<button id="btn1">Button 1</button>
<button id="btn2">Button 2</button>

<script src="https://unpkg.com/jquery"></script>


问:
Security advice: SSL and API access
My API (a desktop application) communicates with my web app using basic HTTP authentication over SSL (Basically I'm just using https instead of http in the requests). My API has implemented logic that makes sure that users don't send incorrect information, but the problem I have is that someone could bypass the API and use curl to potentially post incorrect data (obtaining credentials is trivial since signing up on my web app is free).

I have thought about the following options:

Duplicate the API's logic in the web app so that even if users try to cheat the system using curl or some other tool they are presented with the same conditions.

Implement a further authentication check to make sure only my API can communicate with my web app. (Perhaps SSL client certificates?).

Encrypt the data (Base 64?)

I know I'm being a little paranoid about users spoofing my web app with curl-like tools but I'd rather be safe than sorry. Duplicating the logic is really painful and I would rather not do that. I don't know much about SSL client certificates, can I use them in conjunction with basic HTTP authentication? Will they make my requests take longer to process? What other options do I have?

Thanks in advance.

答:
SSL protects you from the man-in-the-middle attacks, but not from attacks originated on the client side of the SSL. A client certificate built into your client API would allow you to identify that data was crafted by the client side API, but will not help you figuring out if client side manually modified the data just before it got encrypted. Technically ssavy user on the client end can always find a way to modify data by debugging through your client side API.  The best you can do is to put roadblocks to your client side API, to make it harder to decipher it. Validation on the server side is indeed the way to go.

Consider refactoring your validation code so that it can be used on both sides.

Title: Security advice: SSL and API access


问:
How do I set up Visual Studio Code to compile C++ code?
Microsoft's Visual Studio Code editor is quite nice, but it has no default support for building C++ projects.

How do I configure it to do this?

答:
You can reference to this latest gist having a version 2.0.0 task for Visual Studio Code, https://gist.github.com/akanshgulati/56b4d469523ec0acd9f6f59918a9e454

You can easily compile and run each file without updating the task. It's generic and also opens the terminal for input entries.


问:
About Golang pointer,Why is that?
What happened ?

```<code>var n interface{} = 2
var pn = &n
var pf = (*int64)(unsafe.Pointer(pn))
fmt.Println(pf)
fmt.Println(pn)
fmt.Println(*pn) // 2
fmt.Println(*pf) // not 2
*pf = 9
fmt.Println(*pn) //error invalid memory address or nil pointer dereference
fmt.Println(*pf) // 9
</code>```

My question is Why is *pf not equal to *pn and error ?

Thanks for your reply.

答:
For simplicity let’s think we have 64-bit machine.
n is pair of 2 words of 64-bit: first is a pointer to a variable, second is a pointer to information about type - so called itab.

When you get a value pointed by pn compiler knows you want value of an interface, so it goes by the first pointer and returns int value. Compiler thinks pf is a pointer to float64 . So it lets. You to overwrite first word in the interface n with some likely incorrect address (equal to binary value of 9.0). Next time you see the value in the interface compiler uses incorrect address. And return some garbage or even SegFault.

That’s why it’s called unsafe.Pointer and is not recommended to use. Until you have very serious concerns.

Title: About Golang pointer,Why is that?

Body:
What happened ?

var n interface{} = 2
var pn = &n
var pf = (*int64)(unsafe.Pointer(pn))
fmt.Println(pf)
fmt.Println(pn)
fmt.Println(*pn) // 2
fmt.Println(*pf) // not 2
*pf = 9
fmt.Println(*pn) //error invalid memory address or nil pointer dereference
fmt.Println(*pf) // 9

My question is Why is *pf not equal to *pn and error ?

Thanks for your reply.


问:
Stream rtsp video from opencv in python in h.264 with low latency
I'm quite new to video streaming and opencv in general.
I wanted to stream my computations to another device via rtsp from a raspberry pi 3 using h264.
I tried writing to a pipe using popen with ffmpeg to a ffserver anf with vlc creating rtsp servers to stream the content. Unfortunately I have huge lag in the stream, the best I could do was go down to 3 seconds.

Is there any way to achieve this? I'm open to consider other technologies.

Thank you

答:
RTMP is no the best way to achieve low latency (< 5s).

I suggest you to use FFMPEG with pure RTP to stream the video to a RTPS server. Or use directly Gstreamer with Gst-RTSP-server, both are open solutions in C.

Latency will also be impacted by your encoder and the hardware it uses to process.

This question has more information.


问:
Can I create a component as an attribute?
I'm trying to create a component that will register itself with a parent component and provide it with information specific to that child when the parent update is called.

parent:

```<code>    angular
    .module('app')
    .component('parentComponent', {
        templateUrl: function ($attrs) {
            return '/Components/Component/template.cshtml';
        },
        bindings: {
            api: "=",
        },
        controller: controller
    });

function controller() {
    var vm = this;
    vm.subscribedApis = [];

    vm.$onInit = function () {
        vm.api.register = register;
        vm.api.update = update;
        vm.api.performOperation = performOperation;
    };

    function update() {
        vm.subscribedApis.forEach(function (api) {
            api.update();
        });
    }

    function register(api) {
        vm.subscribedApis.push(api);
    }

    function performOperation(viewValue){
        //do something given the childs value
    }
</code>```

child:

```<code>    angular
    .module('app')
    .component('childComponent', {
        require: ['^parentComponent', 'ngModel'],
        bindings: {
            parentApi: "<",
        },
        link: function (scope, element, attrs, controller) {
            controller.getViewValue = function () {
                return ngModel.$viewValue;
            }
        },
        controller: childController
    });

function childController() {
    var vm = this;
    vm.$onInit = function () {
        vm.api = {};
        vm.api.update = update;
        vm.parentApi.register(vm.api);
        update();
    };
    function update() {
        var tag = filterTagApi.performOperation(vm.getViewValue());
    }
</code>```

my problem is that I wish to use the child tag like this

```<code><input type="text" id="title" class="form-control input-sm"
       ng-model="search.parameters.title" autofocus
       child-component parent-api="parentApi" />

<select class="form-control input-sm" ng-model="search.parameters.typeId"
        ng-options="lookup.id as lookup.lookupValue for lookup in lookups.typesOfSomething"
        child-component parent-api="parentApi">
    <option value="" selected>All</option>
</select>
</code>```

Is this possible to do with a generic child component that I can attach to different elements containing an ng-model, or do I need to find a different approach?

答:
Found my answer. Components restrict to elements and do not allow for usage as an attribute. I'll have to make it a directive if I want it available as an attribute.

Source: https://docs.angularjs.org/guide/component#creating-and-configuring-a-component

Body:
I'm trying to create a component that will register itself with a parent component and provide it with information specific to that child when the parent update is called.

parent:

    angular
    .module('app')
    .component('parentComponent', {
        templateUrl: function ($attrs) {
            return '/Components/Component/template.cshtml';
        },
        bindings: {
            api: "=",
        },
        controller: controller
    });

function controller() {
    var vm = this;
    vm.subscribedApis = [];

    vm.$onInit = function () {
        vm.api.register = register;
        vm.api.update = update;
        vm.api.performOperation = performOperation;
    };

    function update() {
        vm.subscribedApis.forEach(function (api) {
            api.update();
        });
    }

    function register(api) {
        vm.subscribedApis.push(api);
    }

    function performOperation(viewValue){
        //do something given the childs value
    }

child:

    angular
    .module('app')
    .component('childComponent', {
        require: ['^parentComponent', 'ngModel'],
        bindings: {
            parentApi: "<",
        },
        link: function (scope, element, attrs, controller) {
            controller.getViewValue = function () {
                return ngModel.$viewValue;
            }
        },
        controller: childController
    });

function childController() {
    var vm = this;
    vm.$onInit = function () {
        vm.api = {};
        vm.api.update = update;
        vm.parentApi.register(vm.api);
        update();
    };
    function update() {
        var tag = filterTagApi.performOperation(vm.getViewValue());
    }

my problem is that I wish to use the child tag like this

<input type="text" id="title" class="form-control input-sm"
       ng-model="search.parameters.title" autofocus
       child-component parent-api="parentApi" />

<select class="form-control input-sm" ng-model="search.parameters.typeId"
        ng-options="lookup.id as lookup.lookupValue for lookup in lookups.typesOfSomething"
        child-component parent-api="parentApi">
    <option value="" selected>All</option>
</select>

Is this possible to do with a generic child component that I can attach to different elements containing an ng-model, or do I need to find a different approach?


问:
Calling other xll files from C#/ExcelDNA code
I have some ExcelDNA C# code which I am working on, and within Excel an xll plugin that I'd like to be able to access.  I am not able to get the source code of this plugin - it has to be used as is.  So is there a method of being able to access these functions from C#?</p>

答:
Great to see an ExcelDna tag on StackOverflow!

You should take a look at making a call to xlUDF. It should allow you make a call to any UDF (including that of your XLL so long as it's loaded).

The MSDN description is here, with a similar question answered on Google Groups.

I hope this helps - please let me know how you get on as I would like to add xlUDF to my list of ExcelDna examples.

Chris


问:
hidden symbol `__aeabi_uidivmod' final link failed: Bad value
I have three C files a.c, b.c and d.c, compiling as below:

```<code>arm-linux-gnueabihf-gcc -c -fPIC  -Iab/inc/  -I../inc  ab/src/a.c -oa.o

arm-linux-gnueabihf-gcc -c -fPIC  -Iab/inc/  -I../inc  ab/src/b.c -ob.o

arm-linux-gnueabihf-ld -fPIC -shared a.o b.o -olibab.so

arm-linux-gnueabihf-gcc -pthread -Iab/inc/ -I../inc/ -L.  ab/test/src/d.c -L. -lab
</code>```

If not cross compile I don't have an error or warning but, in cross compile I get error:

Error as below

```<code>arm-linux-gnueabihf/bin/ld: a.out: hidden symbol `__aeabi_uidivmod' in gcc-linaro-arm-linux-gnueabihf-4.8-2014.04_linux/bin/../lib/gcc/arm-linux-gnueabihf/4.8.3/libgcc.a(_udivsi3.o) is referenced by DSO
arm-linux-gnueabihf/bin/ld: final link failed: Bad value
collect2: error: ld returned 1 exit status
</code>```

Any help will be appreciated. Thanks!

答:
Problem is because of linking with linker(ld), If I link through gcc then this error is not seen.

linker doesn't link against libgcc.a due to which this error is seen this was response from linaro IRC channel

Body:
I have three C files a.c, b.c and d.c, compiling as below:

arm-linux-gnueabihf-gcc -c -fPIC  -Iab/inc/  -I../inc  ab/src/a.c -oa.o

arm-linux-gnueabihf-gcc -c -fPIC  -Iab/inc/  -I../inc  ab/src/b.c -ob.o

arm-linux-gnueabihf-ld -fPIC -shared a.o b.o -olibab.so

arm-linux-gnueabihf-gcc -pthread -Iab/inc/ -I../inc/ -L.  ab/test/src/d.c -L. -lab

If not cross compile I don't have an error or warning but, in cross compile I get error:

Error as below

arm-linux-gnueabihf/bin/ld: a.out: hidden symbol `__aeabi_uidivmod' in gcc-linaro-arm-linux-gnueabihf-4.8-2014.04_linux/bin/../lib/gcc/arm-linux-gnueabihf/4.8.3/libgcc.a(_udivsi3.o) is referenced by DSO
arm-linux-gnueabihf/bin/ld: final link failed: Bad value
collect2: error: ld returned 1 exit status

Any help will be appreciated. Thanks!


问:
Cannot save string to file on android
I am trying to create txt file and write to it on sdcard in android. I am getting "Directory not created" error. path.mkdirs() should create needed directories, shouldn't it ? I have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in AndroidManifest.xml and I have turned on storage permission for app.

Android version: 7.0

```<code>public void addData(View v) {
    wordList.add(inAddWord.getText().toString());

    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
    File file = new File(path, "wordDatabase.txt");

    try {

        if(!(path.exists() && path.isDirectory())) {
            while (!path.mkdir()) {
                Log.e("Path", "Directory not created");
            }
        }

        OutputStream os = new FileOutputStream(file);
        os.write((inAddWord.getText().toString() + "\n").getBytes());
        os.close();

    } catch (IOException e) {
        e.printStackTrace();
        Log.w("ExternalStorage", "Error writing " + file, e);
    }
}
</code>```

答:
On Android 6+ you should add code to ask the user to confirm the permissions you request in manifest.

Google for runtime pemissions.

Title: Cannot save string to file on android

Body:
I am trying to create txt file and write to it on sdcard in android. I am getting "Directory not created" error. path.mkdirs() should create needed directories, shouldn't it ? I have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in AndroidManifest.xml and I have turned on storage permission for app.

Android version: 7.0

public void addData(View v) {
    wordList.add(inAddWord.getText().toString());

    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
    File file = new File(path, "wordDatabase.txt");

    try {

        if(!(path.exists() && path.isDirectory())) {
            while (!path.mkdir()) {
                Log.e("Path", "Directory not created");
            }
        }

        OutputStream os = new FileOutputStream(file);
        os.write((inAddWord.getText().toString() + "\n").getBytes());
        os.close();

    } catch (IOException e) {
        e.printStackTrace();
        Log.w("ExternalStorage", "Error writing " + file, e);
    }
}


问:
How to check if a point is inside a set of contours

Hello to everyone. The above image is sum of two images in which i did feature matching and draw all matching points. I also found the contours of the pcb parts in the first image (half left image-3 contours). The question is, how could i draw only the matching points that is inside those contours in the first image instead this blue mess? I'm using python 2.7 and opencv 2.4.12.

I wrote a function for draw matches cause in opencv 2.4.12 there isn't any implemented method for that. If i didn't include something please tell me. Thank you in advance!

```<code>import numpy as np
import cv2

def drawMatches(img1, kp1, img2, kp2, matches):

    # Create a new output image that concatenates the two images
    # (a.k.a) a montage
    rows1 = img1.shape[0]
    cols1 = img1.shape[1]
    rows2 = img2.shape[0]
    cols2 = img2.shape[1]

    # Create the output image
    # The rows of the output are the largest between the two images
    # and the columns are simply the sum of the two together
    # The intent is to make this a colour image, so make this 3 channels
    out = np.zeros((max([rows1,rows2]),cols1+cols2,3), dtype='uint8')

    # Place the first image to the left
    out[:rows1,:cols1] = np.dstack([img1, img1, img1])

    # Place the next image to the right of it
    out[:rows2,cols1:] = np.dstack([img2, img2, img2])

    # For each pair of points we have between both images
    # draw circles, then connect a line between them
    for mat in matches:

        # Get the matching keypoints for each of the images
        img1_idx = mat.queryIdx
        img2_idx = mat.trainIdx

        # x - columns
        # y - rows
        (x1,y1) = kp1[img1_idx].pt
        (x2,y2) = kp2[img2_idx].pt

        # Draw a small circle at both co-ordinates
        # radius 4
        # colour blue
        # thickness = 1
        cv2.circle(out, (int(x1),int(y1)), 4, (255, 0, 0), 1)
        cv2.circle(out, (int(x2)+cols1,int(y2)), 4, (255, 0, 0), 1)

        # Draw a line in between the two points
        # thickness = 1
        # colour blue
        cv2.line(out, (int(x1),int(y1)), (int(x2)+cols1,int(y2)), (255,0,0), 1)

    # Show the image
    cv2.imshow('Matched Features', out)
    cv2.imwrite("shift_points.png", out)
    cv2.waitKey(0)
    cv2.destroyWindow('Matched Features')

    # Also return the image if you'd like a copy
    return out

img1 = cv2.imread('pic3.png', 0) # Original image - ensure grayscale
img2 = cv2.imread('pic1.png', 0) # Rotated image - ensure grayscale

sift = cv2.SIFT()

# find the keypoints and descriptors with SIFT
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)

# Create matcher
bf = cv2.BFMatcher()

# Perform KNN matching
matches = bf.knnMatch(des1, des2, k=2)

# Apply ratio test
good = []
for m,n in matches:
    if m.distance < 0.75*n.distance:
       # Add first matched keypoint to list
       # if ratio test passes
       good.append(m)

# Show only the top 10 matches - also save a copy for use later
out = drawMatches(img1, kp1, img2, kp2, good)
</code>```

答:
Based on what you are asking I am assuming you mean you have some sort of closed contour outlining the areas you want to bound your data point pairs to.

This is fairly simple for polygonal contours and more math is required for more complex curved lines but the solution is the same.

You draw a line from the point in question to infinity. Most people draw out a line to +x infinity, but any direction works. If there are an odd number of line intersections, the point is inside the contour.

See this article:
http://www.geeksforgeeks.org/how-to-check-if-a-given-point-lies-inside-a-polygon/

For point pairs, only pairs where both points are inside the contour are fully inside the contour. For complex contour shapes with concave sections, if you also want to test that the linear path between the points does not cross the contour, you perform a similar test with just the line segment between the two points, if there are any line intersections the direct path between the points crosses outside the contour.

Edit:

Since your contours are rectangles, a simpler approach will suffice for determining if your points are inside the rectangle.

If your rectangles are axis aligned (they are straight and not rotated), then you can use your values for top,left and bottom,right to check.

Let point A = Top,Left, point B = Bottom,Right, and point C = your test point.

I am assuming an image based coordinate system where 0,0 is the left,top of the image, and width,height is the bottom right. (I'm writing in C#)

```<code>bool PointIsInside(Point A, Point B, Point C)
{
    if (A.X <= C.X && B.X >= C.X   &&   A.Y <= C.Y && B.Y >= C.Y)
        return true;
    return false;
}
</code>```

if your rectangle is NOT axis aligned, then you can perform four half-space tests to determine if your point is inside the rectangle.

Let Point A = Top,Left, Point B = Bottom,Right, double W = Width, double H = Height, double N = rotation angle, and Point C = test point.

for an axis aligned rectangle, Top,Right can be calculated by taking the vector (1,0) , multiplying by Width, and adding that vector to Top,Left. For Bottom,Right We take the vector (0,1), multiply by height, and add to Top,Right.

(1,0) is the equivalent of a Unit Vector (length of 1) at Angle 0. Similarly, (0,1) is a unit vector at angle 90 degrees. These vectors can also be considered the direction the line is pointing. This also means these same vectors can be used to go from Bottom,Left to Bottom,Right, and from Top,Left to Bottom,Left as well.

We need to use different unit vectors, at the angle provided. To do this we simply need to take the Cosine and Sine of the angle provided.

Let Vector X = direction from Top,Left to Top,Right, Vector Y = direction from Top,Right to Bottom,Right.

I am using angles in degrees for this example.

```<code>Vector X = new Vector();
Vector Y = new Vector();
X.X = Math.Cos(R);
X.Y = Math.Sin(R);
Y.X = Math.Cos(R+90);
Y.Y = Math.Sin(R+90);
</code>```

Since we started with Top,Left, we can find Bottom,Right by simply adding the two vectors to Top,Left

```<code>Point B = new Point();
B = A + X + Y;
</code>```

We now want to do a half-space test using the dot product for our test point. The first two test will use the test point, and Top,Left, the other two will use the test point, and Bottom,Right.

The half-space test is inherently based on directionality. Is the point in front, behind, or perpendicular to a given direction? We have the two directions we need, but they are directions based on the top,left point of the rectangle, not the full space of the image, so we need to get a vector from the top,left, to the point in question, and another from the bottom, right, since those are the two points we test against.

This is simple to calculate, as it is just Destination - Origin.

Let Vector D = Top,Left to test point C, and Vector E = Bottom,Right to test point.

```<code>Vector D = C - A;
Vector E = C - B;
</code>```

The dot product is x1 * x2 + y1*y2 of the two vectors. if the result is positive, the two directions have an absolute angle of less than 90 degrees, or are roughly going in the same direction, a result of zero means they are perpendicular. In our case it means the test point is directly on a side of the rectangle we are testing against. Less than zero means an absolute angle of greater than 90 degrees, or they are roughly going opposite directions.

If a point is inside the rectangle, then the dot products from top left will be >= 0, while the dot products from bottom right will be <= 0. In essence the test point is closer to bottom right when testing from top left, but when taking the same directions when we are already at bottom right, it will be going away, back toward top,left.

```<code>double DotProd(Vector V1, Vector V2)
{
    return V1.X * V2.X + V1.Y * V2.Y;
}
</code>```

and so our test ends up as:

```<code>if( DotProd(X, D) >= 0 && DotProd(Y, D) >= 0    &&    DotProd(X, E) <= 0 && DotProd(Y, E) <= 0)
</code>```

then the point is inside the rectangle. Do this for both points, if both are true then the line is inside the rectangle.

Body:
Hello to everyone. The above image is sum of two images in which i did feature matching and draw all matching points. I also found the contours of the pcb parts in the first image (half left image-3 contours). The question is, how could i draw only the matching points that is inside those contours in the first image instead this blue mess? I'm using python 2.7 and opencv 2.4.12.

I wrote a function for draw matches cause in opencv 2.4.12 there isn't any implemented method for that. If i didn't include something please tell me. Thank you in advance!

import numpy as np
import cv2

def drawMatches(img1, kp1, img2, kp2, matches):

    # Create a new output image that concatenates the two images
    # (a.k.a) a montage
    rows1 = img1.shape[0]
    cols1 = img1.shape[1]
    rows2 = img2.shape[0]
    cols2 = img2.shape[1]

    # Create the output image
    # The rows of the output are the largest between the two images
    # and the columns are simply the sum of the two together
    # The intent is to make this a colour image, so make this 3 channels
    out = np.zeros((max([rows1,rows2]),cols1+cols2,3), dtype='uint8')

    # Place the first image to the left
    out[:rows1,:cols1] = np.dstack([img1, img1, img1])

    # Place the next image to the right of it
    out[:rows2,cols1:] = np.dstack([img2, img2, img2])

    # For each pair of points we have between both images
    # draw circles, then connect a line between them
    for mat in matches:

        # Get the matching keypoints for each of the images
        img1_idx = mat.queryIdx
        img2_idx = mat.trainIdx

        # x - columns
        # y - rows
        (x1,y1) = kp1[img1_idx].pt
        (x2,y2) = kp2[img2_idx].pt

        # Draw a small circle at both co-ordinates
        # radius 4
        # colour blue
        # thickness = 1
        cv2.circle(out, (int(x1),int(y1)), 4, (255, 0, 0), 1)
        cv2.circle(out, (int(x2)+cols1,int(y2)), 4, (255, 0, 0), 1)

        # Draw a line in between the two points
        # thickness = 1
        # colour blue
        cv2.line(out, (int(x1),int(y1)), (int(x2)+cols1,int(y2)), (255,0,0), 1)

    # Show the image
    cv2.imshow('Matched Features', out)
    cv2.imwrite("shift_points.png", out)
    cv2.waitKey(0)
    cv2.destroyWindow('Matched Features')

    # Also return the image if you'd like a copy
    return out

img1 = cv2.imread('pic3.png', 0) # Original image - ensure grayscale
img2 = cv2.imread('pic1.png', 0) # Rotated image - ensure grayscale

sift = cv2.SIFT()

# find the keypoints and descriptors with SIFT
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)

# Create matcher
bf = cv2.BFMatcher()

# Perform KNN matching
matches = bf.knnMatch(des1, des2, k=2)

# Apply ratio test
good = []
for m,n in matches:
    if m.distance < 0.75*n.distance:
       # Add first matched keypoint to list
       # if ratio test passes
       good.append(m)

# Show only the top 10 matches - also save a copy for use later
out = drawMatches(img1, kp1, img2, kp2, good)

Body:
Based on what you are asking I am assuming you mean you have some sort of closed contour outlining the areas you want to bound your data point pairs to.

This is fairly simple for polygonal contours and more math is required for more complex curved lines but the solution is the same.

You draw a line from the point in question to infinity. Most people draw out a line to +x infinity, but any direction works. If there are an odd number of line intersections, the point is inside the contour.

See this article:
http://www.geeksforgeeks.org/how-to-check-if-a-given-point-lies-inside-a-polygon/

For point pairs, only pairs where both points are inside the contour are fully inside the contour. For complex contour shapes with concave sections, if you also want to test that the linear path between the points does not cross the contour, you perform a similar test with just the line segment between the two points, if there are any line intersections the direct path between the points crosses outside the contour.

Edit:

Since your contours are rectangles, a simpler approach will suffice for determining if your points are inside the rectangle.

If your rectangles are axis aligned (they are straight and not rotated), then you can use your values for top,left and bottom,right to check.

Let point A = Top,Left, point B = Bottom,Right, and point C = your test point.

I am assuming an image based coordinate system where 0,0 is the left,top of the image, and width,height is the bottom right. (I'm writing in C#)

bool PointIsInside(Point A, Point B, Point C)
{
    if (A.X <= C.X && B.X >= C.X   &&   A.Y <= C.Y && B.Y >= C.Y)
        return true;
    return false;
}

if your rectangle is NOT axis aligned, then you can perform four half-space tests to determine if your point is inside the rectangle.

Let Point A = Top,Left, Point B = Bottom,Right, double W = Width, double H = Height, double N = rotation angle, and Point C = test point.

for an axis aligned rectangle, Top,Right can be calculated by taking the vector (1,0) , multiplying by Width, and adding that vector to Top,Left. For Bottom,Right We take the vector (0,1), multiply by height, and add to Top,Right.

(1,0) is the equivalent of a Unit Vector (length of 1) at Angle 0. Similarly, (0,1) is a unit vector at angle 90 degrees. These vectors can also be considered the direction the line is pointing. This also means these same vectors can be used to go from Bottom,Left to Bottom,Right, and from Top,Left to Bottom,Left as well.

We need to use different unit vectors, at the angle provided. To do this we simply need to take the Cosine and Sine of the angle provided.

Let Vector X = direction from Top,Left to Top,Right, Vector Y = direction from Top,Right to Bottom,Right.

I am using angles in degrees for this example.

Vector X = new Vector();
Vector Y = new Vector();
X.X = Math.Cos(R);
X.Y = Math.Sin(R);
Y.X = Math.Cos(R+90);
Y.Y = Math.Sin(R+90);

Since we started with Top,Left, we can find Bottom,Right by simply adding the two vectors to Top,Left

Point B = new Point();
B = A + X + Y;

We now want to do a half-space test using the dot product for our test point. The first two test will use the test point, and Top,Left, the other two will use the test point, and Bottom,Right.

The half-space test is inherently based on directionality. Is the point in front, behind, or perpendicular to a given direction? We have the two directions we need, but they are directions based on the top,left point of the rectangle, not the full space of the image, so we need to get a vector from the top,left, to the point in question, and another from the bottom, right, since those are the two points we test against.

This is simple to calculate, as it is just Destination - Origin.

Let Vector D = Top,Left to test point C, and Vector E = Bottom,Right to test point.

Vector D = C - A;
Vector E = C - B;

The dot product is x1 * x2 + y1*y2 of the two vectors. if the result is positive, the two directions have an absolute angle of less than 90 degrees, or are roughly going in the same direction, a result of zero means they are perpendicular. In our case it means the test point is directly on a side of the rectangle we are testing against. Less than zero means an absolute angle of greater than 90 degrees, or they are roughly going opposite directions.

If a point is inside the rectangle, then the dot products from top left will be >= 0, while the dot products from bottom right will be <= 0. In essence the test point is closer to bottom right when testing from top left, but when taking the same directions when we are already at bottom right, it will be going away, back toward top,left.

double DotProd(Vector V1, Vector V2)
{
    return V1.X * V2.X + V1.Y * V2.Y;
}

and so our test ends up as:

if( DotProd(X, D) >= 0 && DotProd(Y, D) >= 0    &&    DotProd(X, E) <= 0 && DotProd(Y, E) <= 0)

then the point is inside the rectangle. Do this for both points, if both are true then the line is inside the rectangle.


问:
change tint of button programmatically
I simply want to change the backgroundTint of a normal button from inside the java code. I tried many different approaches like ColorStateList or setColorFilter, but nothing worked. I am purposefully not using setBackgroundColor since I want to keep the original shape of the button.

Furthermore, the colors I want to use are already defined in my resources. After lots of trial and error I managed to access these colors with this code:

```<code>int colorBtnDeactivated = ContextCompat.getColor(this, R.color.colorBtnDeactivated);
</code>```

So basically I only need this one line of java code which enables me to access the background tint. The rest I can do myself.

I would really appreciate help, I have been stuck on this problem for hours. Thanks!

Edit: Using a selector-xlm didn't work, since it only changed the color of the button while being pressed. Also the buttons will influence each other, so by pressing one button I will need to be able to change the background tint of another button.

Edit 2: I tried again with setColorFilter:

```<code>//this is all inside the onCreate-method

int colorBtnActiveTest= ContextCompat.getColor(this, colorBtnActive);
int colorBtnDeactivatedTest=ContextCompat.getColor(this, colorBtnDeactivated);

Button btnKnockOne = (Button)findViewById(R.id.btnKnockOne);
boolean stateBtnKnockOne = false;
btnKnockOne.getBackground().setColorFilter(colorBtnDeactivatedTest, PorterDuff.Mode.SRC_IN);

btnKnockOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (stateBtnKnockOne==false){
                    btnKnockOne.getBackground().setColorFilter(colorBtnActiveTest, PorterDuff.Mode.SRC_IN);
                    stateBtnKnockOne=true;
                }

                else if (stateBtnKnockOne==true){
                    btnKnockOne.getBackground().setColorFilter(colorBtnDeactivatedTest, PorterDuff.Mode.SRC_IN);
                    stateBtnKnockOne=false;
                }
            }
        });
</code>```

This is the result:

When I open the activity, the button is displayed in the default grey button color, not in my custom color colorBtnDeactivatedTest

When I press the button, it briefly changes its color to colorBtnActiveTest, but then goes back to its grey color

答:
I finally found a solution! This post helped me find it: https://stackoverflow.com/a/8748112/8952749

Now I basically have two buttons of which only one can be selected at one time. For this to work I created a selector-xlm:

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:state_selected="true"
        android:drawable="@drawable/button_active" />
    <item
        android:state_selected="false"
        android:drawable="@drawable/button_deactivated" />

</selector>
</code>```

This is the java code, which enables me to change state_selected of the buttons:

```<code>    stateBtn1=false;
    stateBtn2=false;

    btnTest1=(Button)findViewById(R.id.button);
    btnTest2=(Button)findViewById(R.id.button2);

    btnTest1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (stateBtn1==false){
                btnTest1.setSelected(true);
                stateBtn1=true;

                btnTest2.setSelected(false);
                stateBtn2=false;
            }
            else if (stateBtn1==true){
                btnTest1.setSelected(false);
                stateBtn1=false;
            }
        }
    });

    btnTest2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (stateBtn2==false){
                btnTest2.setSelected(true);
                stateBtn2=true;

                btnTest1.setSelected(false);
                stateBtn1=false;
            }
            else if (stateBtn2==true){
                btnTest2.setSelected(false);
                stateBtn2=false;
            }
        }
    });
</code>```

Title: change tint of button programmatically

Body:
I simply want to change the backgroundTint of a normal button from inside the java code. I tried many different approaches like ColorStateList or setColorFilter, but nothing worked. I am purposefully not using setBackgroundColor since I want to keep the original shape of the button.

Furthermore, the colors I want to use are already defined in my resources. After lots of trial and error I managed to access these colors with this code:

int colorBtnDeactivated = ContextCompat.getColor(this, R.color.colorBtnDeactivated);

So basically I only need this one line of java code which enables me to access the background tint. The rest I can do myself.

I would really appreciate help, I have been stuck on this problem for hours. Thanks!

Edit: Using a selector-xlm didn't work, since it only changed the color of the button while being pressed. Also the buttons will influence each other, so by pressing one button I will need to be able to change the background tint of another button.

Edit 2: I tried again with setColorFilter:

//this is all inside the onCreate-method

int colorBtnActiveTest= ContextCompat.getColor(this, colorBtnActive);
int colorBtnDeactivatedTest=ContextCompat.getColor(this, colorBtnDeactivated);

Button btnKnockOne = (Button)findViewById(R.id.btnKnockOne);
boolean stateBtnKnockOne = false;
btnKnockOne.getBackground().setColorFilter(colorBtnDeactivatedTest, PorterDuff.Mode.SRC_IN);

btnKnockOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (stateBtnKnockOne==false){
                    btnKnockOne.getBackground().setColorFilter(colorBtnActiveTest, PorterDuff.Mode.SRC_IN);
                    stateBtnKnockOne=true;
                }

                else if (stateBtnKnockOne==true){
                    btnKnockOne.getBackground().setColorFilter(colorBtnDeactivatedTest, PorterDuff.Mode.SRC_IN);
                    stateBtnKnockOne=false;
                }
            }
        });

This is the result:

When I open the activity, the button is displayed in the default grey button color, not in my custom color colorBtnDeactivatedTest

When I press the button, it briefly changes its color to colorBtnActiveTest, but then goes back to its grey color

Body:
I finally found a solution! This post helped me find it: https://stackoverflow.com/a/8748112/8952749

Now I basically have two buttons of which only one can be selected at one time. For this to work I created a selector-xlm:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:state_selected="true"
        android:drawable="@drawable/button_active" />
    <item
        android:state_selected="false"
        android:drawable="@drawable/button_deactivated" />

</selector>

This is the java code, which enables me to change state_selected of the buttons:

    stateBtn1=false;
    stateBtn2=false;

    btnTest1=(Button)findViewById(R.id.button);
    btnTest2=(Button)findViewById(R.id.button2);

    btnTest1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (stateBtn1==false){
                btnTest1.setSelected(true);
                stateBtn1=true;

                btnTest2.setSelected(false);
                stateBtn2=false;
            }
            else if (stateBtn1==true){
                btnTest1.setSelected(false);
                stateBtn1=false;
            }
        }
    });

    btnTest2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (stateBtn2==false){
                btnTest2.setSelected(true);
                stateBtn2=true;

                btnTest1.setSelected(false);
                stateBtn1=false;
            }
            else if (stateBtn2==true){
                btnTest2.setSelected(false);
                stateBtn2=false;
            }
        }
    });


问:
How can I get "call" to execute for each data element in D3?
Using D3, I'm trying to implement a word wrap plugin for each quotation displayed from myData. The call function on the last line is that. </p>

<p>The problem is that it only works for the first quote. It makes the all other quotes not appear. I'm not sure how to structure the call to happen while enter() would typically renders thing. </p>

```<code>var quote=svg.selectAll("text.quote").data(myData);
quote.exit().remove()
quote.enter().append("text")
quote
.attr("class","quote")
.attr("x", function (d,i){ return xScale(i);})
.attr("y", function(d){ return yScale(d.y);})
.text(function(d, i){return d.quote;})
.call(d3.util.wrap(125))
</code>```

答:
You want selection.each() rather than selection.call(). Selection.call will will invoke a function just once, while .each will invoke it for each datum:

selection.each(function) <>

Invokes the specified function for each selected element, in order,
  being passed the current datum (d), the current index (i), and the
  current group (nodes), with this as the current DOM element
  (nodes[i]). This method can be used to invoke arbitrary code for each
  selected element...

Compare to:

selection.call(function[, arguments…]) <>

Invokes the specified function exactly once, passing in this selection
  along with any optional arguments.

(API Documentation (v4, but both methods exist in v3))

See the following snippet for a comparison of both:

var data = [10,20,30,40];

var selection = d3.select("body").selectAll(null)
  .data(data)
  .enter()
  .append("p")
  .each(function(d) {
    console.log("each: " + d); // d is datum
  })
  .call(function(d) {
    console.log("call: ")
    console.log(d.data()); // d is selection
  })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script></code>```

To call this function once on each item, you could use .call within the .each. I've used a g to place the text, so that the tspans this utility creates are positioned correctly (otherwise they overlap). The following snippet otherwise uses your code (the word wrap utility is on top as I could not find a cdn for it quickly enough):

d3.util = d3.util || {};

d3.util.wrap = function(_wrapW){
    return function(d, i){
        var that = this;

        function tspanify(){
            var lineH = this.node().getBBox().height;
            this.text('')
                .selectAll('tspan')
                .data(lineArray)
                .enter().append('tspan')
                .attr({
                    x: 0,
                    y: function(d, i){ return (i + 1) * lineH; }
                })
                .text(function(d, i){ return d.join(' '); })
        }

        function checkW(_text){
            var textTmp = that
                .style({visibility: 'hidden'})
                .text(_text);
            var textW = textTmp.node().getBBox().width;
            that.style({visibility: 'visible'}).text(text);
            return textW;
        }

        var text = this.text();
        var parentNode = this.node().parentNode;
        var textSplitted = text.split(' ');
        var lineArray = [[]];
        var count = 0;
        textSplitted.forEach(function(d, i){
            if(checkW(lineArray[count].concat(d).join(' '), parentNode) >= _wrapW){
                count++;
                lineArray[count] = [];
            }
            lineArray[count].push(d)
        });

        this.call(tspanify)
    }
};

var wrap = d3.util.wrap(11);

var svg = d3.select("body")
 .append("svg")
 .attr("height",400)
 .attr("width",400);

var myData = ["text 1","text 2","text 3"]

var quote = svg.selectAll("text.quote").data(myData);
quote.enter().append("g")

quote.attr("class","quote")
.attr("transform", function (d,i){ return "translate(20," + (i * 40 + 20) + ")" })
.append("text")
.text(function(d, i){return d})
.each(function() {
  d3.select(this).call(d3.util.wrap(11));
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script></code>```

Body:
Using D3, I'm trying to implement a word wrap plugin for each quotation displayed from myData. The call function on the last line is that.

The problem is that it only works for the first quote. It makes the all other quotes not appear. I'm not sure how to structure the call to happen while enter() would typically renders thing.

var quote=svg.selectAll("text.quote").data(myData);
quote.exit().remove()
quote.enter().append("text")
quote
.attr("class","quote")
.attr("x", function (d,i){ return xScale(i);})
.attr("y", function(d){ return yScale(d.y);})
.text(function(d, i){return d.quote;})
.call(d3.util.wrap(125))

Body:
You want selection.each() rather than selection.call(). Selection.call will will invoke a function just once, while .each will invoke it for each datum:

selection.each(function) <>

Invokes the specified function for each selected element, in order,
  being passed the current datum (d), the current index (i), and the
  current group (nodes), with this as the current DOM element
  (nodes[i]). This method can be used to invoke arbitrary code for each
  selected element...

Compare to:

selection.call(function[, arguments…]) <>

Invokes the specified function exactly once, passing in this selection
  along with any optional arguments.

(API Documentation (v4, but both methods exist in v3))

See the following snippet for a comparison of both:

var data = [10,20,30,40];

var selection = d3.select("body").selectAll(null)
  .data(data)
  .enter()
  .append("p")
  .each(function(d) {
    console.log("each: " + d); // d is datum
  })
  .call(function(d) {
    console.log("call: ")
    console.log(d.data()); // d is selection
  })

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>

To call this function once on each item, you could use .call within the .each. I've used a g to place the text, so that the tspans this utility creates are positioned correctly (otherwise they overlap). The following snippet otherwise uses your code (the word wrap utility is on top as I could not find a cdn for it quickly enough):

d3.util = d3.util || {};

d3.util.wrap = function(_wrapW){
    return function(d, i){
        var that = this;

        function tspanify(){
            var lineH = this.node().getBBox().height;
            this.text('')
                .selectAll('tspan')
                .data(lineArray)
                .enter().append('tspan')
                .attr({
                    x: 0,
                    y: function(d, i){ return (i + 1) * lineH; }
                })
                .text(function(d, i){ return d.join(' '); })
        }

        function checkW(_text){
            var textTmp = that
                .style({visibility: 'hidden'})
                .text(_text);
            var textW = textTmp.node().getBBox().width;
            that.style({visibility: 'visible'}).text(text);
            return textW;
        }

        var text = this.text();
        var parentNode = this.node().parentNode;
        var textSplitted = text.split(' ');
        var lineArray = [[]];
        var count = 0;
        textSplitted.forEach(function(d, i){
            if(checkW(lineArray[count].concat(d).join(' '), parentNode) >= _wrapW){
                count++;
                lineArray[count] = [];
            }
            lineArray[count].push(d)
        });

        this.call(tspanify)
    }
};

var wrap = d3.util.wrap(11);

var svg = d3.select("body")
 .append("svg")
 .attr("height",400)
 .attr("width",400);

var myData = ["text 1","text 2","text 3"]

var quote = svg.selectAll("text.quote").data(myData);
quote.enter().append("g")

quote.attr("class","quote")
.attr("transform", function (d,i){ return "translate(20," + (i * 40 + 20) + ")" })
.append("text")
.text(function(d, i){return d})
.each(function() {
  d3.select(this).call(d3.util.wrap(11));
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>


问:
Shortening repeating functions
I am trying to make the sliders output the values depending on the which button has been clicked.

<!DOCTYPE html>

  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">

Value:

<input type="button" onclick="function1()" value="1">
<input type="button" onclick="function2()" value="2">
<input type="button" onclick="function3()" value="3">

</script>

```

As you can see for each of the buttons, the functions are being repeated and only the variable 'a' is being changed. I was wondering if there was a way to make this code more efficient, in other words shorter.

Please let me know if you have any solutions for this.
Thanks.

答:
let slider = document.getElementById('myRange');
let output = document.getElementById('output');

let setOutputHTML = function (value) {
  output.innerHTML = value;
};

let setSliderValue = function (e) {
  slider.value = e.currentTarget.value;
  slider.dispatchEvent(new Event('input'));
};

slider.addEventListener('input', function (e) {
  setOutputHTML(e.currentTarget.value);
});

setOutputHTML(slider.value);

Array.from(document.querySelectorAll('[type="button"]'))
  .forEach(function (input) {
    input.addEventListener('click', setSliderValue);
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">
  <p>Value: <span id="output"></span></p>
</div>

<input type="button" value="25" name="field_slug" />
<input type="button" value="50" name="field_dlug" />
<input type="button" value="75" name="field_flug" /></code>```

Title: Shortening repeating functions

Body:
I am trying to make the sliders output the values depending on the which button has been clicked.

<!DOCTYPE html>

  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">

Value:

<input type="button" onclick="function1()" value="1">
<input type="button" onclick="function2()" value="2">
<input type="button" onclick="function3()" value="3">

</script>

As you can see for each of the buttons, the functions are being repeated and only the variable 'a' is being changed. I was wondering if there was a way to make this code more efficient, in other words shorter.

Please let me know if you have any solutions for this.
Thanks.

Body:
let slider = document.getElementById('myRange');
let output = document.getElementById('output');

let setOutputHTML = function (value) {
  output.innerHTML = value;
};

let setSliderValue = function (e) {
  slider.value = e.currentTarget.value;
  slider.dispatchEvent(new Event('input'));
};

slider.addEventListener('input', function (e) {
  setOutputHTML(e.currentTarget.value);
});

setOutputHTML(slider.value);

Array.from(document.querySelectorAll('[type="button"]'))
  .forEach(function (input) {
    input.addEventListener('click', setSliderValue);
  });

<div>
  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">
  <p>Value: <span id="output"></span></p>
</div>

<input type="button" value="25" name="field_slug" />
<input type="button" value="50" name="field_dlug" />
<input type="button" value="75" name="field_flug" />